SHARE
TWEET

Divert6.c

a guest May 17th, 2020 18 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <netinet/ip6.h>
  5. #include <netinet/tcp.h>
  6. #include <arpa/inet.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <err.h>
  10.  
  11. #define DIVERT_PORT 700
  12.  
  13. int
  14. main(int argc, char *argv[])
  15. {
  16.     int fd, s;
  17.     struct sockaddr_in6 sin;
  18.     socklen_t sin_len;
  19.  
  20.     fd = socket(AF_INET6, SOCK_RAW, IPPROTO_DIVERT);
  21.     if (fd == -1)
  22.         err(1, "socket");
  23.  
  24.     memset(&sin, 0, sizeof(sin));
  25.     sin.sin6_family = AF_INET6;
  26.     sin.sin6_port = htons(DIVERT_PORT);
  27.     sin.sin6_addr = in6addr_any;
  28.  
  29.     sin_len = sizeof(struct sockaddr_in6);
  30.  
  31.     s = bind(fd, (struct sockaddr *) &sin, sin_len);
  32.     if (s == -1)
  33.         err(1, "bind");
  34.  
  35.     for (;;) {
  36.         ssize_t n;
  37.         char packet[65535];
  38.         struct ip6_hdr *ip;
  39.         struct tcphdr *th;
  40.         int hlen;
  41.         char src[48], dst[48];
  42.  
  43.         memset(packet, 0, sizeof(packet));
  44.         n = recvfrom(fd, packet, sizeof(packet), 0,
  45.             (struct sockaddr *) &sin, &sin_len);
  46.         if (n == -1) {
  47.             warn("recvfrom");
  48.             continue;
  49.         }
  50.         if (n < sizeof(struct ip6_hdr)) {
  51.             warnx("packet is too short");
  52.             continue;
  53.         }
  54.  
  55.         ip = (struct ip6_hdr *) packet;
  56.         hlen = sizeof(struct ip6_hdr);
  57. //      if (hlen < sizeof(struct ip6_hdr) || ntohs(ip->ip_len) < hlen ||
  58. //          n < ntohs(ip->ip_len)) {
  59. //          warnx("invalid IPv6 packet");
  60. //          continue;
  61. //      }
  62.  
  63.         th = (struct tcphdr *) (packet + hlen);
  64.  
  65.         if (inet_ntop(AF_INET6, &ip->ip6_src, src,
  66.             sizeof(src)) == NULL)
  67.             (void)strlcpy(src, "?", sizeof(src));
  68.  
  69.         if (inet_ntop(AF_INET6, &ip->ip6_dst, dst,
  70.             sizeof(dst)) == NULL)
  71.             (void)strlcpy(dst, "?", sizeof(dst));
  72.  
  73.         printf("%s:%u -> %s:%u\n",
  74.             src,
  75.             ntohs(th->th_sport),
  76.             dst,
  77.             ntohs(th->th_dport)
  78.         );
  79.  
  80.         n = sendto(fd, packet, n, 0, (struct sockaddr *) &sin,
  81.             sin_len);
  82.         if (n == -1)
  83.             warn("sendto");
  84.     }
  85.  
  86.     return 0;
  87. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top