connect6_prog.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (c) 2018 Facebook
  3. #include <string.h>
  4. #include <linux/stddef.h>
  5. #include <linux/bpf.h>
  6. #include <linux/in.h>
  7. #include <linux/in6.h>
  8. #include <sys/socket.h>
  9. #include "bpf_helpers.h"
  10. #include "bpf_endian.h"
  11. #define SRC_REWRITE_IP6_0 0
  12. #define SRC_REWRITE_IP6_1 0
  13. #define SRC_REWRITE_IP6_2 0
  14. #define SRC_REWRITE_IP6_3 6
  15. #define DST_REWRITE_IP6_0 0
  16. #define DST_REWRITE_IP6_1 0
  17. #define DST_REWRITE_IP6_2 0
  18. #define DST_REWRITE_IP6_3 1
  19. #define DST_REWRITE_PORT6 6666
  20. int _version SEC("version") = 1;
  21. SEC("cgroup/connect6")
  22. int connect_v6_prog(struct bpf_sock_addr *ctx)
  23. {
  24. struct sockaddr_in6 sa;
  25. /* Rewrite destination. */
  26. ctx->user_ip6[0] = bpf_htonl(DST_REWRITE_IP6_0);
  27. ctx->user_ip6[1] = bpf_htonl(DST_REWRITE_IP6_1);
  28. ctx->user_ip6[2] = bpf_htonl(DST_REWRITE_IP6_2);
  29. ctx->user_ip6[3] = bpf_htonl(DST_REWRITE_IP6_3);
  30. ctx->user_port = bpf_htons(DST_REWRITE_PORT6);
  31. if (ctx->type == SOCK_DGRAM || ctx->type == SOCK_STREAM) {
  32. /* Rewrite source. */
  33. memset(&sa, 0, sizeof(sa));
  34. sa.sin6_family = AF_INET6;
  35. sa.sin6_port = bpf_htons(0);
  36. sa.sin6_addr.s6_addr32[0] = bpf_htonl(SRC_REWRITE_IP6_0);
  37. sa.sin6_addr.s6_addr32[1] = bpf_htonl(SRC_REWRITE_IP6_1);
  38. sa.sin6_addr.s6_addr32[2] = bpf_htonl(SRC_REWRITE_IP6_2);
  39. sa.sin6_addr.s6_addr32[3] = bpf_htonl(SRC_REWRITE_IP6_3);
  40. if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
  41. return 0;
  42. }
  43. return 1;
  44. }
  45. char _license[] SEC("license") = "GPL";