Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #!/usr/bin/python
  2. bpf_text = """
  3. #include <linux/ptrace.h>
  4. #include <linux/sched.h> /* For TASK_COMM_LEN */
  5.  
  6. #include <linux/icmp.h>
  7. #include <linux/netdevice.h>
  8.  
  9. struct probe_icmp_data_t
  10. {
  11. u64 timestamp_ns;
  12. u32 tgid;
  13. u32 pid;
  14. char comm[TASK_COMM_LEN];
  15. int v0;
  16. };
  17.  
  18. BPF_PERF_OUTPUT(probe_icmp_events);
  19.  
  20. static inline unsigned char *my_skb_transport_header(const struct sk_buff *skb)
  21. {
  22. return skb->head + skb->transport_header;
  23. }
  24.  
  25. static inline struct icmphdr *my_icmp_hdr(const struct sk_buff *skb)
  26. {
  27. return (struct icmphdr *)my_skb_transport_header(skb);
  28. }
  29.  
  30.  
  31. int probe_icmp(struct pt_regs *ctx, struct sk_buff *skb)
  32. {
  33. u64 __pid_tgid = bpf_get_current_pid_tgid();
  34. u32 __tgid = __pid_tgid >> 32;
  35. u32 __pid = __pid_tgid; // implicit cast to u32 for bottom half
  36.  
  37. struct probe_icmp_data_t __data = {0};
  38. __data.timestamp_ns = bpf_ktime_get_ns();
  39. __data.tgid = __tgid;
  40. __data.pid = __pid;
  41. bpf_get_current_comm(&__data.comm, sizeof(__data.comm));
  42.  
  43. __be16 seq;
  44. bpf_probe_read(&seq, sizeof(seq), &my_icmp_hdr(skb)->un.echo.sequence);
  45. __data.v0 = (int)seq;
  46.  
  47.  
  48. probe_icmp_events.perf_submit(ctx, &__data, sizeof(__data));
  49. return 0;
  50. }
  51.  
  52. """
  53.  
  54. from bcc import BPF
  55. import ctypes as ct
  56.  
  57. class Data_icmp(ct.Structure):
  58. _fields_ = [
  59. ("timestamp_ns", ct.c_ulonglong),
  60. ("tgid", ct.c_uint),
  61. ("pid", ct.c_uint),
  62. ("comm", ct.c_char * 16), # TASK_COMM_LEN
  63. ('v0', ct.c_uint),
  64. ]
  65.  
  66. b = BPF(text=bpf_text)
  67.  
  68. def print_icmp_event(cpu, data, size):
  69. #event = b["probe_icmp_events"].event(data)
  70. event = ct.cast(data, ct.POINTER(Data_icmp)).contents
  71. print("%-7d %-7d %-15s %s" %
  72. (event.tgid, event.pid,
  73. event.comm.decode('utf-8', 'replace'),
  74. event.v0))
  75.  
  76. b.attach_kprobe(event="icmp_echo", fn_name="probe_icmp")
  77.  
  78. b["probe_icmp_events"].open_perf_buffer(print_icmp_event)
  79. while 1:
  80. try:
  81. b.kprobe_poll()
  82. except KeyboardInterrupt:
  83. exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement