Corrected spinning loop potential in getrandombytes
[netsniff-ng.git] / astraceroute.c
bloba4cfa3dd498378814fdd6332330350782126cb38
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann.
4 * Subject to the GPL, version 2.
6 * The road must be trod, but it will be very hard. And neither strength nor
7 * wisdom will carry us far upon it. This quest may be attempted by the weak
8 * with as much hope as the strong. Yet such is oft the course of deeds that
9 * move the wheels of the world: small hands do them because they must,
10 * while the eyes of the great are elsewhere.
12 * -- The Lord of the Rings, Elrond, Chapter 'The Council of Elrond'.
15 #define _BSD_SOURCE
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <signal.h>
19 #include <getopt.h>
20 #include <ctype.h>
21 #include <stdint.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/socket.h>
25 #include <sys/fsuid.h>
26 #include <fcntl.h>
27 #include <time.h>
28 #include <string.h>
29 #include <asm/byteorder.h>
30 #include <linux/tcp.h>
31 #include <netinet/ip.h>
32 #include <netinet/ip6.h>
33 #include <netinet/in.h>
34 #include <errno.h>
35 #include <netdb.h>
36 #include <sys/time.h>
37 #include <arpa/inet.h>
38 #include <linux/if_ether.h>
39 #include <linux/icmp.h>
40 #include <linux/icmpv6.h>
42 #include "bpf.h"
43 #include "die.h"
44 #include "tprintf.h"
45 #include "pkt_buff.h"
46 #include "proto.h"
47 #include "xmalloc.h"
48 #include "xio.h"
49 #include "csum.h"
50 #include "geoip.h"
51 #include "xutils.h"
52 #include "ring_rx.h"
53 #include "built_in.h"
55 struct ctx {
56 char *host, *port, *dev, *payload;
57 int init_ttl, max_ttl, dns_resolv, queries, timeout, totlen, rcvlen;
58 int syn, ack, ecn, fin, psh, rst, urg, tos, nofrag, proto, show;
59 int sd_len, dport, latitude;
62 struct proto_ops {
63 int (*assembler)(uint8_t *packet, size_t len, int ttl, int proto,
64 const struct ctx *ctx, const struct sockaddr *dst,
65 const struct sockaddr *src);
66 const struct sock_filter *filter;
67 unsigned int flen;
68 unsigned int min_len_tcp, min_len_icmp;
69 int (*check)(uint8_t *packet, size_t len, int ttl, int id,
70 const struct sockaddr *src);
71 void (*handler)(uint8_t *packet, size_t len, int dns_resolv,
72 int latitude);
75 sig_atomic_t sigint = 0;
77 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
78 const struct ctx *ctx, const struct sockaddr *dst,
79 const struct sockaddr *src);
80 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
81 const struct ctx *ctx, const struct sockaddr *dst,
82 const struct sockaddr *src);
83 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
84 const struct sockaddr *ss);
85 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv,
86 int latitude);
87 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
88 const struct sockaddr *ss);
89 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv,
90 int latitude);
92 static const char *short_options = "H:p:nNf:m:i:d:q:x:SAEFPURt:Gl:hv46X:ZuL";
93 static const struct option long_options[] = {
94 {"host", required_argument, NULL, 'H'},
95 {"port", required_argument, NULL, 'p'},
96 {"init-ttl", required_argument, NULL, 'f'},
97 {"max-ttl", required_argument, NULL, 'm'},
98 {"dev", required_argument, NULL, 'd'},
99 {"num-probes", required_argument, NULL, 'q'},
100 {"timeout", required_argument, NULL, 'x'},
101 {"tos", required_argument, NULL, 't'},
102 {"payload", required_argument, NULL, 'X'},
103 {"totlen", required_argument, NULL, 'l'},
104 {"numeric", no_argument, NULL, 'n'},
105 {"latitude", no_argument, NULL, 'L'},
106 {"update", no_argument, NULL, 'u'},
107 {"dns", no_argument, NULL, 'N'},
108 {"ipv4", no_argument, NULL, '4'},
109 {"ipv6", no_argument, NULL, '6'},
110 {"syn", no_argument, NULL, 'S'},
111 {"ack", no_argument, NULL, 'A'},
112 {"urg", no_argument, NULL, 'U'},
113 {"fin", no_argument, NULL, 'F'},
114 {"psh", no_argument, NULL, 'P'},
115 {"rst", no_argument, NULL, 'R'},
116 {"ecn-syn", no_argument, NULL, 'E'},
117 {"show-packet", no_argument, NULL, 'Z'},
118 {"nofrag", no_argument, NULL, 'G'},
119 {"version", no_argument, NULL, 'v'},
120 {"help", no_argument, NULL, 'h'},
121 {NULL, 0, NULL, 0}
124 static const struct sock_filter ipv4_icmp_type_11[] = {
125 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
126 { 0x15, 0, 8, 0x00000800 }, /* jneq #0x800, drop */
127 { 0x30, 0, 0, 0x00000017 }, /* ldb [23] */
128 { 0x15, 0, 6, 0x00000001 }, /* jneq #0x1, drop */
129 { 0x28, 0, 0, 0x00000014 }, /* ldh [20] */
130 { 0x45, 4, 0, 0x00001fff }, /* jset #0x1fff, drop */
131 { 0xb1, 0, 0, 0x0000000e }, /* ldxb 4*([14]&0xf) */
132 { 0x50, 0, 0, 0x0000000e }, /* ldb [x + 14] */
133 { 0x15, 0, 1, 0x0000000b }, /* jneq #0xb, drop */
134 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
135 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
138 static const struct sock_filter ipv6_icmp6_type_3[] = {
139 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
140 { 0x15, 0, 5, 0x000086dd }, /* jneq #0x86dd, drop */
141 { 0x30, 0, 0, 0x00000014 }, /* ldb [20] */
142 { 0x15, 0, 3, 0x0000003a }, /* jneq #0x3a, drop */
143 { 0x30, 0, 0, 0x00000036 }, /* ldb [54] */
144 { 0x15, 0, 1, 0x00000003 }, /* jneq #0x3, drop */
145 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
146 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
149 static const struct proto_ops af_ops[] = {
150 [IPPROTO_IP] = {
151 .assembler = assemble_ipv4,
152 .handler = handle_ipv4,
153 .check = check_ipv4,
154 .filter = ipv4_icmp_type_11,
155 .flen = array_size(ipv4_icmp_type_11),
156 .min_len_tcp = sizeof(struct iphdr) + sizeof(struct tcphdr),
157 .min_len_icmp = sizeof(struct iphdr) + sizeof(struct icmphdr),
159 [IPPROTO_IPV6] = {
160 .assembler = assemble_ipv6,
161 .handler = handle_ipv6,
162 .check = check_ipv6,
163 .filter = ipv6_icmp6_type_3,
164 .flen = array_size(ipv6_icmp6_type_3),
165 .min_len_tcp = sizeof(struct ip6_hdr) + sizeof(struct tcphdr),
166 .min_len_icmp = sizeof(struct ip6_hdr) + sizeof(struct icmp6hdr),
170 static void signal_handler(int number)
172 switch (number) {
173 case SIGINT:
174 sigint = 1;
175 default:
176 break;
180 static void help(void)
182 printf("\nastraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
183 puts("http://www.netsniff-ng.org\n\n"
184 "Usage: astraceroute [options]\n"
185 "Options:\n"
186 " -H|--host <host> Host/IPv4/IPv6 to lookup AS route to\n"
187 " -p|--port <port> Hosts port to lookup AS route to\n"
188 " -i|-d|--dev <device> Networking device, e.g. eth0\n"
189 " -f|--init-ttl <ttl> Set initial TTL\n"
190 " -m|--max-ttl <ttl> Set maximum TTL (def: 30)\n"
191 " -q|--num-probes <num> Number of max probes for each hop (def: 2)\n"
192 " -x|--timeout <sec> Probe response timeout in sec (def: 3)\n"
193 " -X|--payload <string> Specify a payload string to test DPIs\n"
194 " -l|--totlen <len> Specify total packet len\n"
195 " -4|--ipv4 Use IPv4-only requests\n"
196 " -6|--ipv6 Use IPv6-only requests\n"
197 " -n|--numeric Do not do reverse DNS lookup for hops\n"
198 " -u|--update Update GeoIP databases\n"
199 " -L|--latitude Show latitude and longtitude\n"
200 " -N|--dns Do a reverse DNS lookup for hops\n"
201 " -S|--syn Set TCP SYN flag\n"
202 " -A|--ack Set TCP ACK flag\n"
203 " -F|--fin Set TCP FIN flag\n"
204 " -P|--psh Set TCP PSH flag\n"
205 " -U|--urg Set TCP URG flag\n"
206 " -R|--rst Set TCP RST flag\n"
207 " -E|--ecn-syn Send ECN SYN packets (RFC3168)\n"
208 " -t|--tos <tos> Set the IP TOS field\n"
209 " -G|--nofrag Set do not fragment bit\n"
210 " -Z|--show-packet Show returned packet on each hop\n"
211 " -v|--version Print version\n"
212 " -h|--help Print this help\n\n"
213 "Examples:\n"
214 " IPv4 trace of AS with TCP SYN probe (this will most-likely pass):\n"
215 " astraceroute -i eth0 -N -S -H netsniff-ng.org\n"
216 " IPv4 trace of AS with TCP ECN SYN probe:\n"
217 " astraceroute -i eth0 -N -E -H netsniff-ng.org\n"
218 " IPv4 trace of AS with TCP FIN probe:\n"
219 " astraceroute -i eth0 -N -F -H netsniff-ng.org\n"
220 " IPv4 trace of AS with Xmas probe:\n"
221 " astraceroute -i eth0 -N -FPU -H netsniff-ng.org\n"
222 " IPv4 trace of AS with Null probe with ASCII payload:\n"
223 " astraceroute -i eth0 -N -H netsniff-ng.org -X \"censor-me\" -Z\n"
224 " IPv6 trace of AS up to www.6bone.net:\n"
225 " astraceroute -6 -i eth0 -S -E -N -H www.6bone.net\n\n"
226 "Note:\n"
227 " If the TCP probe did not give any results, then astraceroute will\n"
228 " automatically probe for classic ICMP packets! To gather more\n"
229 " information about astraceroute's fetched AS numbers, see e.g.\n"
230 " http://bgp.he.net/AS<number>!\n\n"
231 "Please report bugs to <bugs@netsniff-ng.org>\n"
232 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
233 "Swiss federal institute of technology (ETH Zurich)\n"
234 "License: GNU GPL version 2.0\n"
235 "This is free software: you are free to change and redistribute it.\n"
236 "There is NO WARRANTY, to the extent permitted by law.\n");
237 die();
240 static void version(void)
242 printf("\nastraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
243 puts("http://www.netsniff-ng.org\n\n"
244 "Please report bugs to <bugs@netsniff-ng.org>\n"
245 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
246 "Swiss federal institute of technology (ETH Zurich)\n"
247 "License: GNU GPL version 2.0\n"
248 "This is free software: you are free to change and redistribute it.\n"
249 "There is NO WARRANTY, to the extent permitted by law.\n");
250 die();
253 static void __assemble_data(uint8_t *packet, size_t len, const char *payload)
255 int i;
257 if (payload == NULL) {
258 for (i = 0; i < len; ++i)
259 packet[i] = (uint8_t) rand();
260 } else {
261 int lmin = min(len, strlen(payload));
263 for (i = 0; i < lmin; ++i)
264 packet[i] = (uint8_t) payload[i];
265 for (i = lmin; i < len; ++i)
266 packet[i] = (uint8_t) rand();
270 static void __assemble_icmp4(uint8_t *packet, size_t len)
272 struct icmphdr *icmph = (struct icmphdr *) packet;
274 bug_on(len < sizeof(struct icmphdr));
276 icmph->type = ICMP_ECHO;
277 icmph->code = 0;
278 icmph->checksum = 0;
281 static void __assemble_icmp6(uint8_t *packet, size_t len)
283 struct icmp6hdr *icmp6h = (struct icmp6hdr *) packet;
285 bug_on(len < sizeof(struct icmp6hdr));
287 icmp6h->icmp6_type = ICMPV6_ECHO_REQUEST;
288 icmp6h->icmp6_code = 0;
289 icmp6h->icmp6_cksum = 0;
292 static void __assemble_tcp(uint8_t *packet, size_t len, int syn, int ack,
293 int urg, int fin, int rst, int psh, int ecn,
294 int dport)
296 struct tcphdr *tcph = (struct tcphdr *) packet;
298 bug_on(len < sizeof(struct tcphdr));
300 tcph->source = htons((uint16_t) rand());
301 tcph->dest = htons((uint16_t) dport);
303 tcph->seq = htonl(rand());
304 tcph->ack_seq = (!!ack ? htonl(rand()) : 0);
306 tcph->doff = 5;
308 tcph->syn = !!syn;
309 tcph->ack = !!ack;
310 tcph->urg = !!urg;
311 tcph->fin = !!fin;
312 tcph->rst = !!rst;
313 tcph->psh = !!psh;
314 tcph->ece = !!ecn;
315 tcph->cwr = !!ecn;
317 tcph->window = htons((uint16_t) (100 + (rand() % 65435)));
318 tcph->urg_ptr = (!!urg ? htons((uint16_t) rand()) : 0);
319 tcph->check = 0;
322 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
323 const struct ctx *ctx, const struct sockaddr *dst,
324 const struct sockaddr *src)
326 uint8_t *data;
327 size_t data_len, off_next = 0;
328 struct iphdr *iph = (struct iphdr *) packet;
330 bug_on(!src || !dst);
331 bug_on(src->sa_family != PF_INET || dst->sa_family != PF_INET);
332 bug_on(len < sizeof(*iph) + min(sizeof(struct tcphdr),
333 sizeof(struct icmphdr)));
335 iph->ihl = 5;
336 iph->version = 4;
337 iph->tos = (uint8_t) ctx->tos;
339 iph->tot_len = htons((uint16_t) len);
340 iph->id = htons((uint16_t) rand());
342 iph->frag_off = ctx->nofrag ? IP_DF : 0;
343 iph->ttl = (uint8_t) ttl;
345 iph->saddr = ((const struct sockaddr_in *) src)->sin_addr.s_addr;
346 iph->daddr = ((const struct sockaddr_in *) dst)->sin_addr.s_addr;
348 iph->protocol = (uint8_t) proto;
350 data = packet + sizeof(*iph);
351 data_len = len - sizeof(*iph);
353 switch (proto) {
354 case IPPROTO_TCP:
355 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
356 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
357 off_next = sizeof(struct tcphdr);
358 break;
359 case IPPROTO_ICMP:
360 __assemble_icmp4(data, data_len);
361 off_next = sizeof(struct icmphdr);
362 break;
363 default:
364 bug();
367 data = packet + sizeof(*iph) + off_next;
368 data_len = len - sizeof(*iph) - off_next;
370 __assemble_data(data, data_len, ctx->payload);
372 iph->check = csum((unsigned short *) packet, ntohs(iph->tot_len) >> 1);
374 return ntohs(iph->id);
377 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
378 const struct ctx *ctx, const struct sockaddr *dst,
379 const struct sockaddr *src)
381 uint8_t *data;
382 size_t data_len, off_next = 0;
383 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
385 bug_on(!src || !dst);
386 bug_on(src->sa_family != PF_INET6 || dst->sa_family != PF_INET6);
387 bug_on(len < sizeof(*ip6h) + min(sizeof(struct tcphdr),
388 sizeof(struct icmp6hdr)));
390 ip6h->ip6_flow = htonl(rand() & 0x000fffff);
391 ip6h->ip6_vfc = 0x60;
393 ip6h->ip6_plen = htons((uint16_t) len - sizeof(*ip6h));
394 ip6h->ip6_nxt = (uint8_t) proto;
395 ip6h->ip6_hlim = (uint8_t) ttl;
397 memcpy(&ip6h->ip6_src, &(((const struct sockaddr_in6 *)
398 src)->sin6_addr), sizeof(ip6h->ip6_src));
399 memcpy(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
400 dst)->sin6_addr), sizeof(ip6h->ip6_dst));
402 data = packet + sizeof(*ip6h);
403 data_len = len - sizeof(*ip6h);
405 switch (proto) {
406 case IPPROTO_TCP:
407 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
408 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
409 off_next = sizeof(struct tcphdr);
410 break;
411 case IPPROTO_ICMP:
412 case IPPROTO_ICMPV6:
413 __assemble_icmp6(data, data_len);
414 off_next = sizeof(struct icmp6hdr);
415 break;
416 default:
417 bug();
420 data = packet + sizeof(*ip6h) + off_next;
421 data_len = len - sizeof(*ip6h) - off_next;
423 __assemble_data(data, data_len, ctx->payload);
425 return ntohl(ip6h->ip6_flow) & 0x000fffff;
428 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
429 const struct sockaddr *ss)
431 struct iphdr *iph = (struct iphdr *) packet;
432 struct iphdr *iph_inner;
433 struct icmphdr *icmph;
435 if (iph->protocol != IPPROTO_ICMP)
436 return -EINVAL;
437 if (iph->daddr != ((const struct sockaddr_in *) ss)->sin_addr.s_addr)
438 return -EINVAL;
440 icmph = (struct icmphdr *) (packet + sizeof(struct iphdr));
441 if (icmph->type != ICMP_TIME_EXCEEDED)
442 return -EINVAL;
443 if (icmph->code != ICMP_EXC_TTL)
444 return -EINVAL;
446 iph_inner = (struct iphdr *) (packet + sizeof(struct iphdr) +
447 sizeof(struct icmphdr));
448 if (ntohs(iph_inner->id) != id)
449 return -EINVAL;
451 return len;
454 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv, int latitude)
456 char hbuff[256];
457 struct iphdr *iph = (struct iphdr *) packet;
458 struct sockaddr_in sd;
459 struct hostent *hent;
460 const char *as, *country, *city;
462 memset(hbuff, 0, sizeof(hbuff));
463 memset(&sd, 0, sizeof(sd));
464 sd.sin_family = PF_INET;
465 sd.sin_addr.s_addr = iph->saddr;
467 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
468 hbuff, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
470 as = geoip4_as_name(sd);
471 country = geoip4_country_name(sd);
472 city = geoip4_city_name(sd);
474 if (dns_resolv) {
475 hent = gethostbyaddr(&sd.sin_addr, sizeof(sd.sin_addr), PF_INET);
476 if (hent)
477 printf(" %s (%s)", hent->h_name, hbuff);
478 else
479 printf(" %s", hbuff);
480 } else {
481 printf(" %s", hbuff);
483 if (as)
484 printf(" in %s", as);
485 if (country) {
486 printf(" in %s", country);
487 if (city)
488 printf(", %s", city);
490 if (latitude)
491 printf(" (%f/%f)", geoip4_latitude(sd), geoip4_longitude(sd));
494 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
495 const struct sockaddr *ss)
497 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
498 struct ip6_hdr *ip6h_inner;
499 struct icmp6hdr *icmp6h;
501 if (ip6h->ip6_nxt != 0x3a)
502 return -EINVAL;
503 if (memcmp(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
504 ss)->sin6_addr), sizeof(ip6h->ip6_dst)))
505 return -EINVAL;
507 icmp6h = (struct icmp6hdr *) (packet + sizeof(*ip6h));
508 if (icmp6h->icmp6_type != ICMPV6_TIME_EXCEED)
509 return -EINVAL;
510 if (icmp6h->icmp6_code != ICMPV6_EXC_HOPLIMIT)
511 return -EINVAL;
513 ip6h_inner = (struct ip6_hdr *) (packet + sizeof(*ip6h) + sizeof(*icmp6h));
514 if ((ntohl(ip6h_inner->ip6_flow) & 0x000fffff) != id)
515 return -EINVAL;
517 return len;
520 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv, int latitude)
522 char hbuff[256];
523 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
524 struct sockaddr_in6 sd;
525 struct hostent *hent;
526 const char *as, *country, *city;
528 memset(hbuff, 0, sizeof(hbuff));
529 memset(&sd, 0, sizeof(sd));
530 sd.sin6_family = PF_INET6;
531 memcpy(&sd.sin6_addr, &ip6h->ip6_src, sizeof(ip6h->ip6_src));
533 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
534 hbuff, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
536 as = geoip6_as_name(sd);
537 country = geoip6_country_name(sd);
538 city = geoip6_city_name(sd);
540 if (dns_resolv) {
541 hent = gethostbyaddr(&sd.sin6_addr, sizeof(sd.sin6_addr), PF_INET6);
542 if (hent)
543 printf(" %s (%s)", hent->h_name, hbuff);
544 else
545 printf(" %s", hbuff);
546 } else {
547 printf(" %s", hbuff);
549 if (as)
550 printf(" in %s", as);
551 if (country) {
552 printf(" in %s", country);
553 if (city)
554 printf(", %s", city);
556 if (latitude)
557 printf(" (%f/%f)", geoip6_latitude(sd), geoip6_longitude(sd));
560 static void show_trace_info(struct ctx *ctx, const struct sockaddr_storage *ss,
561 const struct sockaddr_storage *sd)
563 char hbuffs[256], hbuffd[256];
565 memset(hbuffd, 0, sizeof(hbuffd));
566 getnameinfo((struct sockaddr *) sd, sizeof(*sd),
567 hbuffd, sizeof(hbuffd), NULL, 0, NI_NUMERICHOST);
569 memset(hbuffs, 0, sizeof(hbuffs));
570 getnameinfo((struct sockaddr *) ss, sizeof(*ss),
571 hbuffs, sizeof(hbuffs), NULL, 0, NI_NUMERICHOST);
573 printf("AS path IPv%d TCP trace from %s to %s:%s (%s) with len %d "
574 "Bytes, %u max hops\n", ctx->proto == IPPROTO_IP ? 4 : 6,
575 hbuffs, hbuffd, ctx->port, ctx->host, ctx->totlen, ctx->max_ttl);
577 printf("Using flags SYN:%d,ACK:%d,ECN:%d,FIN:%d,PSH:%d,RST:%d,URG:%d\n",
578 ctx->syn, ctx->ack, ctx->ecn, ctx->fin, ctx->psh, ctx->rst, ctx->urg);
580 if (ctx->payload)
581 printf("With payload: \'%s\'\n", ctx->payload);
584 static int get_remote_fd(struct ctx *ctx, struct sockaddr_storage *ss,
585 struct sockaddr_storage *sd)
587 int fd = -1, ret, one = 1;
588 struct addrinfo hints, *ahead, *ai;
590 memset(&hints, 0, sizeof(hints));
591 hints.ai_family = PF_UNSPEC;
592 hints.ai_socktype = SOCK_STREAM;
593 hints.ai_protocol = IPPROTO_TCP;
594 hints.ai_flags = AI_NUMERICSERV;
596 ret = getaddrinfo(ctx->host, ctx->port, &hints, &ahead);
597 if (ret < 0)
598 panic("Cannot get address info!\n");
600 for (ai = ahead; ai != NULL && fd < 0; ai = ai->ai_next) {
601 if (!((ai->ai_family == PF_INET6 && ctx->proto == IPPROTO_IPV6) ||
602 (ai->ai_family == PF_INET && ctx->proto == IPPROTO_IP)))
603 continue;
605 fd = socket(ai->ai_family, SOCK_RAW, IPPROTO_RAW);
606 if (fd < 0)
607 continue;
609 memset(ss, 0, sizeof(*ss));
610 ret = device_address(ctx->dev, ai->ai_family, ss);
611 if (ret < 0)
612 panic("Cannot get own device address!\n");
614 ret = bind(fd, (struct sockaddr *) ss, sizeof(*ss));
615 if (ret < 0)
616 panic("Cannot bind socket!\n");
618 memset(sd, 0, sizeof(*sd));
619 memcpy(sd, ai->ai_addr, ai->ai_addrlen);
621 ctx->sd_len = ai->ai_addrlen;
622 ctx->dport = strtoul(ctx->port, NULL, 10);
624 ret = setsockopt(fd, ctx->proto, IP_HDRINCL, &one, sizeof(one));
625 if (ret < 0)
626 panic("Kernel does not support IP_HDRINCL!\n");
628 if (ai->ai_family == PF_INET6) {
629 struct sockaddr_in6 *sd6 = (struct sockaddr_in6 *) sd;
631 sd6->sin6_port = 0;
634 break;
637 freeaddrinfo(ahead);
639 if (fd < 0)
640 panic("Cannot create socket! Does remote "
641 "support IPv%d?!\n",
642 ctx->proto == IPPROTO_IP ? 4 : 6);
644 return fd;
647 static void inject_filter(struct ctx *ctx, int fd)
649 struct sock_fprog bpf_ops;
651 enable_kernel_bpf_jit_compiler();
653 memset(&bpf_ops, 0, sizeof(bpf_ops));
654 bpf_ops.filter = (struct sock_filter *) af_ops[ctx->proto].filter;
655 bpf_ops.len = af_ops[ctx->proto].flen;
657 bpf_attach_to_sock(fd, &bpf_ops);
660 static int __process_node(struct ctx *ctx, int fd, int fd_cap, int ttl,
661 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
662 const struct sockaddr_storage *ss,
663 const struct sockaddr_storage *sd, struct timeval *diff)
665 int pkt_id, ret, timeout;
666 struct pollfd pfd;
667 struct timeval start, end;
669 prepare_polling(fd_cap, &pfd);
671 memset(pkt_snd, 0, ctx->totlen);
672 pkt_id = af_ops[ctx->proto].assembler(pkt_snd, ctx->totlen, ttl,
673 inner_proto, ctx,
674 (const struct sockaddr *) sd,
675 (const struct sockaddr *) ss);
677 ret = sendto(fd, pkt_snd, ctx->totlen, 0, (struct sockaddr *) sd,
678 ctx->sd_len);
679 if (ret < 0)
680 panic("sendto failed: %s\n", strerror(errno));
682 bug_on(gettimeofday(&start, NULL));
684 timeout = (ctx->timeout > 0 ? ctx->timeout : 2) * 1000;
686 ret = poll(&pfd, 1, timeout);
687 if (ret > 0 && pfd.revents & POLLIN && sigint == 0) {
688 bug_on(gettimeofday(&end, NULL));
689 if (diff)
690 timersub(&end, &start, diff);
692 ret = recvfrom(fd_cap, pkt_rcv, ctx->rcvlen, 0, NULL, NULL);
693 if (ret < sizeof(struct ethhdr) + af_ops[ctx->proto].min_len_icmp)
694 return -EIO;
696 return af_ops[ctx->proto].check(pkt_rcv + sizeof(struct ethhdr),
697 ret - sizeof(struct ethhdr), ttl,
698 pkt_id, (const struct sockaddr *) ss);
699 } else {
700 return -EIO;
703 return 0;
706 static void timerdiv(const unsigned long divisor, const struct timeval *tv,
707 struct timeval *result)
709 uint64_t x = ((uint64_t) tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
711 result->tv_sec = x / 1000 / 1000;
712 result->tv_usec = x % (1000 * 1000);
715 static int timevalcmp(const void *t1, const void *t2)
717 if (timercmp((struct timeval *) t1, (struct timeval *) t2, <))
718 return -1;
719 if (timercmp((struct timeval *) t1, (struct timeval *) t2, >))
720 return 1;
722 return 0;
725 static int __process_time(struct ctx *ctx, int fd, int fd_cap, int ttl,
726 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
727 const struct sockaddr_storage *ss,
728 const struct sockaddr_storage *sd)
730 int good = 0, i, j = 0, ret = -EIO, idx, ret_good = -EIO;
731 struct timeval probes[9], *tmp, sum, res;
732 uint8_t *trash = xmalloc(ctx->rcvlen);
733 char *cwait[] = { "-", "\\", "|", "/" };
734 const char *proto_short[] = {
735 [IPPROTO_TCP] = "t",
736 [IPPROTO_ICMP] = "i",
737 [IPPROTO_ICMPV6] = "i",
740 memset(probes, 0, sizeof(probes));
741 for (i = 0; i < array_size(probes) && sigint == 0; ++i) {
742 ret = __process_node(ctx, fd, fd_cap, ttl, inner_proto,
743 pkt_snd, good == 0 ? pkt_rcv : trash,
744 ss, sd, &probes[i]);
745 if (ret > 0) {
746 if (good == 0)
747 ret_good = ret;
748 good++;
751 if (good == 0 && ctx->queries == i)
752 break;
754 usleep(50000);
756 printf("\r%2d: %s", ttl, cwait[j++]);
757 fflush(stdout);
758 if (j >= array_size(cwait))
759 j = 0;
762 if (good == 0) {
763 xfree(trash);
764 return -EIO;
767 tmp = xmalloc(sizeof(struct timeval) * good);
768 for (i = j = 0; i < array_size(probes); ++i) {
769 if (probes[i].tv_sec == 0 && probes[i].tv_usec == 0)
770 continue;
771 tmp[j].tv_sec = probes[i].tv_sec;
772 tmp[j].tv_usec = probes[i].tv_usec;
773 j++;
776 qsort(tmp, j, sizeof(struct timeval), timevalcmp);
778 printf("\r%2d: %s[", ttl, proto_short[inner_proto]);
779 idx = j / 2;
780 switch (j % 2) {
781 case 0:
782 timeradd(&tmp[idx], &tmp[idx - 1], &sum);
783 timerdiv(2, &sum, &res);
784 if (res.tv_sec > 0)
785 printf("%lu sec ", res.tv_sec);
786 printf("%7lu us", res.tv_usec);
787 break;
788 case 1:
789 if (tmp[idx].tv_sec > 0)
790 printf("%lu sec ", tmp[idx].tv_sec);
791 printf("%7lu us", tmp[idx].tv_usec);
792 break;
793 default:
794 bug();
796 printf("]");
798 xfree(tmp);
799 xfree(trash);
801 return ret_good;
804 static int __probe_remote(struct ctx *ctx, int fd, int fd_cap, int ttl,
805 uint8_t *pkt_snd, uint8_t *pkt_rcv,
806 const struct sockaddr_storage *ss,
807 const struct sockaddr_storage *sd,
808 int inner_proto)
810 int ret = -EIO, tries = ctx->queries;
812 while (tries-- > 0 && sigint == 0) {
813 ret = __process_time(ctx, fd, fd_cap, ttl, inner_proto,
814 pkt_snd, pkt_rcv, ss, sd);
815 if (ret < 0)
816 continue;
818 af_ops[ctx->proto].handler(pkt_rcv + sizeof(struct ethhdr),
819 ret - sizeof(struct ethhdr),
820 ctx->dns_resolv, ctx->latitude);
821 if (ctx->show) {
822 struct pkt_buff *pkt;
824 printf("\n");
825 pkt = pkt_alloc(pkt_rcv, ret);
826 hex_ascii(pkt);
827 tprintf_flush();
828 pkt_free(pkt);
831 break;
834 return ret;
837 static int __process_ttl(struct ctx *ctx, int fd, int fd_cap, int ttl,
838 uint8_t *pkt_snd, uint8_t *pkt_rcv,
839 const struct sockaddr_storage *ss,
840 const struct sockaddr_storage *sd)
842 int ret = -EIO, i;
843 const int inner_protos[] = {
844 IPPROTO_TCP,
845 IPPROTO_ICMP,
848 printf("%2d: ", ttl);
849 fflush(stdout);
851 for (i = 0; i < array_size(inner_protos) && sigint == 0; ++i) {
852 ret = __probe_remote(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv, ss, sd,
853 inner_protos[i]);
854 if (ret > 0)
855 break;
858 if (ret <= 0)
859 printf("\r%2d: ?[ no answer]", ttl);
860 if (ctx->show == 0)
861 printf("\n");
862 if (ctx->show && ret <= 0)
863 printf("\n\n");
865 fflush(stdout);
866 return 0;
869 static int main_trace(struct ctx *ctx)
871 int fd, fd_cap, ifindex, ttl;
872 struct ring dummy_ring;
873 struct sockaddr_storage ss, sd;
874 uint8_t *pkt_snd, *pkt_rcv;
876 fd = get_remote_fd(ctx, &ss, &sd);
877 fd_cap = pf_socket();
879 inject_filter(ctx, fd_cap);
881 ifindex = device_ifindex(ctx->dev);
882 bind_rx_ring(fd_cap, &dummy_ring, ifindex);
884 if (ctx->totlen < af_ops[ctx->proto].min_len_tcp) {
885 ctx->totlen = af_ops[ctx->proto].min_len_tcp;
886 if (ctx->payload)
887 ctx->totlen += strlen(ctx->payload);
890 ctx->rcvlen = device_mtu(ctx->dev) - sizeof(struct ethhdr);
891 if (ctx->totlen >= ctx->rcvlen)
892 panic("Packet len exceeds device MTU!\n");
894 pkt_snd = xmalloc(ctx->totlen);
895 pkt_rcv = xmalloc(ctx->rcvlen);
897 show_trace_info(ctx, &ss, &sd);
899 for (ttl = ctx->init_ttl; ttl <= ctx->max_ttl && sigint == 0; ++ttl)
900 __process_ttl(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv,
901 &ss, &sd);
903 xfree(pkt_snd);
904 xfree(pkt_rcv);
906 close(fd_cap);
907 close(fd);
909 return 0;
912 int main(int argc, char **argv)
914 int c, opt_index, ret;
915 struct ctx ctx;
917 setfsuid(getuid());
918 setfsgid(getgid());
920 srand(time(NULL));
922 memset(&ctx, 0, sizeof(ctx));
923 ctx.init_ttl = 1;
924 ctx.max_ttl = 30;
925 ctx.queries = 2;
926 ctx.timeout = 2;
927 ctx.proto = IPPROTO_IP;
928 ctx.payload = NULL;
929 ctx.dev = xstrdup("eth0");
930 ctx.port = xstrdup("80");
932 while ((c = getopt_long(argc, argv, short_options, long_options,
933 &opt_index)) != EOF) {
934 switch (c) {
935 case 'h':
936 help();
937 break;
938 case 'v':
939 version();
940 break;
941 case 'u':
942 update_geoip();
943 die();
944 break;
945 case 'H':
946 ctx.host = xstrdup(optarg);
947 break;
948 case 'p':
949 if (ctx.port)
950 xfree(ctx.port);
951 ctx.port = xstrdup(optarg);
952 break;
953 case 'n':
954 ctx.dns_resolv = 0;
955 break;
956 case '4':
957 ctx.proto = IPPROTO_IP;
958 break;
959 case '6':
960 ctx.proto = IPPROTO_IPV6;
961 break;
962 case 'Z':
963 ctx.show = 1;
964 break;
965 case 'N':
966 ctx.dns_resolv = 1;
967 break;
968 case 'f':
969 ctx.init_ttl = atoi(optarg);
970 if (ctx.init_ttl <= 0)
971 help();
972 break;
973 case 'm':
974 ctx.max_ttl = atoi(optarg);
975 if (ctx.max_ttl <= 0)
976 help();
977 break;
978 case 'i':
979 case 'd':
980 free(ctx.dev);
981 ctx.dev = xstrdup(optarg);
982 break;
983 case 'q':
984 ctx.queries = atoi(optarg);
985 if (ctx.queries <= 0)
986 help();
987 break;
988 case 'x':
989 ctx.timeout = atoi(optarg);
990 if (ctx.timeout <= 0)
991 help();
992 break;
993 case 'L':
994 ctx.latitude = 1;
995 break;
996 case 'S':
997 ctx.syn = 1;
998 break;
999 case 'A':
1000 ctx.ack = 1;
1001 break;
1002 case 'F':
1003 ctx.fin = 1;
1004 break;
1005 case 'U':
1006 ctx.urg = 1;
1007 break;
1008 case 'P':
1009 ctx.psh = 1;
1010 break;
1011 case 'R':
1012 ctx.rst = 1;
1013 break;
1014 case 'E':
1015 ctx.syn = 1;
1016 ctx.ecn = 1;
1017 break;
1018 case 't':
1019 ctx.tos = atoi(optarg);
1020 if (ctx.tos < 0)
1021 help();
1022 break;
1023 case 'G':
1024 ctx.nofrag = 1;
1025 break;
1026 case 'X':
1027 ctx.payload = xstrdup(optarg);
1028 break;
1029 case 'l':
1030 ctx.totlen = atoi(optarg);
1031 if (ctx.totlen <= 0)
1032 help();
1033 break;
1034 case '?':
1035 switch (optopt) {
1036 case 'H':
1037 case 'p':
1038 case 'f':
1039 case 'm':
1040 case 'i':
1041 case 'd':
1042 case 'q':
1043 case 'x':
1044 case 'X':
1045 case 't':
1046 case 'l':
1047 panic("Option -%c requires an argument!\n",
1048 optopt);
1049 default:
1050 if (isprint(optopt))
1051 printf("Unknown option character `0x%X\'!\n", optopt);
1052 die();
1054 default:
1055 break;
1059 if (argc < 3 || !ctx.host || !ctx.port || ctx.init_ttl > ctx.max_ttl ||
1060 ctx.init_ttl > MAXTTL || ctx.max_ttl > MAXTTL)
1061 help();
1063 if (!device_up_and_running(ctx.dev))
1064 panic("Networking device not up and running!\n");
1065 if (device_mtu(ctx.dev) <= ctx.totlen)
1066 panic("Packet larger than device MTU!\n");
1068 register_signal(SIGHUP, signal_handler);
1069 register_signal(SIGINT, signal_handler);
1071 tprintf_init();
1072 init_geoip(1);
1074 ret = main_trace(&ctx);
1076 destroy_geoip();
1077 tprintf_cleanup();
1079 free(ctx.dev);
1080 free(ctx.host);
1081 free(ctx.port);
1082 free(ctx.payload);
1084 return ret;