sendmsg4_prog.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 SRC1_IP4 0xAC100001U /* 172.16.0.1 */
  9. #define SRC2_IP4 0x00000000U
  10. #define SRC_REWRITE_IP4 0x7f000004U
  11. #define DST_IP4 0xC0A801FEU /* 192.168.1.254 */
  12. #define DST_REWRITE_IP4 0x7f000001U
  13. #define DST_PORT 4040
  14. #define DST_REWRITE_PORT4 4444
  15. int _version SEC("version") = 1;
  16. SEC("cgroup/sendmsg4")
  17. int sendmsg_v4_prog(struct bpf_sock_addr *ctx)
  18. {
  19. if (ctx->type != SOCK_DGRAM)
  20. return 0;
  21. /* Rewrite source. */
  22. if (ctx->msg_src_ip4 == bpf_htonl(SRC1_IP4) ||
  23. ctx->msg_src_ip4 == bpf_htonl(SRC2_IP4)) {
  24. ctx->msg_src_ip4 = bpf_htonl(SRC_REWRITE_IP4);
  25. } else {
  26. /* Unexpected source. Reject sendmsg. */
  27. return 0;
  28. }
  29. /* Rewrite destination. */
  30. if ((ctx->user_ip4 >> 24) == (bpf_htonl(DST_IP4) >> 24) &&
  31. ctx->user_port == bpf_htons(DST_PORT)) {
  32. ctx->user_ip4 = bpf_htonl(DST_REWRITE_IP4);
  33. ctx->user_port = bpf_htons(DST_REWRITE_PORT4);
  34. } else {
  35. /* Unexpected source. Reject sendmsg. */
  36. return 0;
  37. }
  38. return 1;
  39. }
  40. char _license[] SEC("license") = "GPL";