test_probe_write_user_kern.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. */
  7. #include <linux/skbuff.h>
  8. #include <linux/netdevice.h>
  9. #include <uapi/linux/bpf.h>
  10. #include <linux/version.h>
  11. #include "bpf_helpers.h"
  12. struct bpf_map_def SEC("maps") dnat_map = {
  13. .type = BPF_MAP_TYPE_HASH,
  14. .key_size = sizeof(struct sockaddr_in),
  15. .value_size = sizeof(struct sockaddr_in),
  16. .max_entries = 256,
  17. };
  18. /* kprobe is NOT a stable ABI
  19. * kernel functions can be removed, renamed or completely change semantics.
  20. * Number of arguments and their positions can change, etc.
  21. * In such case this bpf+kprobe example will no longer be meaningful
  22. *
  23. * This example sits on a syscall, and the syscall ABI is relatively stable
  24. * of course, across platforms, and over time, the ABI may change.
  25. */
  26. SEC("kprobe/sys_connect")
  27. int bpf_prog1(struct pt_regs *ctx)
  28. {
  29. struct sockaddr_in new_addr, orig_addr = {};
  30. struct sockaddr_in *mapped_addr;
  31. void *sockaddr_arg = (void *)PT_REGS_PARM2(ctx);
  32. int sockaddr_len = (int)PT_REGS_PARM3(ctx);
  33. if (sockaddr_len > sizeof(orig_addr))
  34. return 0;
  35. if (bpf_probe_read(&orig_addr, sizeof(orig_addr), sockaddr_arg) != 0)
  36. return 0;
  37. mapped_addr = bpf_map_lookup_elem(&dnat_map, &orig_addr);
  38. if (mapped_addr != NULL) {
  39. memcpy(&new_addr, mapped_addr, sizeof(new_addr));
  40. bpf_probe_write_user(sockaddr_arg, &new_addr,
  41. sizeof(new_addr));
  42. }
  43. return 0;
  44. }
  45. char _license[] SEC("license") = "GPL";
  46. u32 _version SEC("version") = LINUX_VERSION_CODE;