socket_cookie_prog.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (c) 2018 Facebook
  3. #include <linux/bpf.h>
  4. #include <sys/socket.h>
  5. #include "bpf_helpers.h"
  6. #include "bpf_endian.h"
  7. struct bpf_map_def SEC("maps") socket_cookies = {
  8. .type = BPF_MAP_TYPE_HASH,
  9. .key_size = sizeof(__u64),
  10. .value_size = sizeof(__u32),
  11. .max_entries = 1 << 8,
  12. };
  13. SEC("cgroup/connect6")
  14. int set_cookie(struct bpf_sock_addr *ctx)
  15. {
  16. __u32 cookie_value = 0xFF;
  17. __u64 cookie_key;
  18. if (ctx->family != AF_INET6 || ctx->user_family != AF_INET6)
  19. return 1;
  20. cookie_key = bpf_get_socket_cookie(ctx);
  21. if (bpf_map_update_elem(&socket_cookies, &cookie_key, &cookie_value, 0))
  22. return 0;
  23. return 1;
  24. }
  25. SEC("sockops")
  26. int update_cookie(struct bpf_sock_ops *ctx)
  27. {
  28. __u32 new_cookie_value;
  29. __u32 *cookie_value;
  30. __u64 cookie_key;
  31. if (ctx->family != AF_INET6)
  32. return 1;
  33. if (ctx->op != BPF_SOCK_OPS_TCP_CONNECT_CB)
  34. return 1;
  35. cookie_key = bpf_get_socket_cookie(ctx);
  36. cookie_value = bpf_map_lookup_elem(&socket_cookies, &cookie_key);
  37. if (!cookie_value)
  38. return 1;
  39. new_cookie_value = (ctx->local_port << 8) | *cookie_value;
  40. bpf_map_update_elem(&socket_cookies, &cookie_key, &new_cookie_value, 0);
  41. return 1;
  42. }
  43. int _version SEC("version") = 1;
  44. char _license[] SEC("license") = "GPL";