sendmsg6_prog.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (c) 2018 Facebook
  3. #include <linux/stddef.h>
  4. #include <linux/bpf.h>
  5. #include <sys/socket.h>
  6. #include "bpf_helpers.h"
  7. #include "bpf_endian.h"
  8. #define SRC_REWRITE_IP6_0 0
  9. #define SRC_REWRITE_IP6_1 0
  10. #define SRC_REWRITE_IP6_2 0
  11. #define SRC_REWRITE_IP6_3 6
  12. #define DST_REWRITE_IP6_0 0
  13. #define DST_REWRITE_IP6_1 0
  14. #define DST_REWRITE_IP6_2 0
  15. #define DST_REWRITE_IP6_3 1
  16. #define DST_REWRITE_PORT6 6666
  17. int _version SEC("version") = 1;
  18. SEC("cgroup/sendmsg6")
  19. int sendmsg_v6_prog(struct bpf_sock_addr *ctx)
  20. {
  21. if (ctx->type != SOCK_DGRAM)
  22. return 0;
  23. /* Rewrite source. */
  24. if (ctx->msg_src_ip6[3] == bpf_htonl(1) ||
  25. ctx->msg_src_ip6[3] == bpf_htonl(0)) {
  26. ctx->msg_src_ip6[0] = bpf_htonl(SRC_REWRITE_IP6_0);
  27. ctx->msg_src_ip6[1] = bpf_htonl(SRC_REWRITE_IP6_1);
  28. ctx->msg_src_ip6[2] = bpf_htonl(SRC_REWRITE_IP6_2);
  29. ctx->msg_src_ip6[3] = bpf_htonl(SRC_REWRITE_IP6_3);
  30. } else {
  31. /* Unexpected source. Reject sendmsg. */
  32. return 0;
  33. }
  34. /* Rewrite destination. */
  35. if (ctx->user_ip6[0] == bpf_htonl(0xFACEB00C)) {
  36. ctx->user_ip6[0] = bpf_htonl(DST_REWRITE_IP6_0);
  37. ctx->user_ip6[1] = bpf_htonl(DST_REWRITE_IP6_1);
  38. ctx->user_ip6[2] = bpf_htonl(DST_REWRITE_IP6_2);
  39. ctx->user_ip6[3] = bpf_htonl(DST_REWRITE_IP6_3);
  40. ctx->user_port = bpf_htons(DST_REWRITE_PORT6);
  41. } else {
  42. /* Unexpected destination. Reject sendmsg. */
  43. return 0;
  44. }
  45. return 1;
  46. }
  47. char _license[] SEC("license") = "GPL";