connect4_prog.c 976 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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_IP4 0x7f000004U
  12. #define DST_REWRITE_IP4 0x7f000001U
  13. #define DST_REWRITE_PORT4 4444
  14. int _version SEC("version") = 1;
  15. SEC("cgroup/connect4")
  16. int connect_v4_prog(struct bpf_sock_addr *ctx)
  17. {
  18. struct sockaddr_in sa;
  19. /* Rewrite destination. */
  20. ctx->user_ip4 = bpf_htonl(DST_REWRITE_IP4);
  21. ctx->user_port = bpf_htons(DST_REWRITE_PORT4);
  22. if (ctx->type == SOCK_DGRAM || ctx->type == SOCK_STREAM) {
  23. ///* Rewrite source. */
  24. memset(&sa, 0, sizeof(sa));
  25. sa.sin_family = AF_INET;
  26. sa.sin_port = bpf_htons(0);
  27. sa.sin_addr.s_addr = bpf_htonl(SRC_REWRITE_IP4);
  28. if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
  29. return 0;
  30. }
  31. return 1;
  32. }
  33. char _license[] SEC("license") = "GPL";