helpers.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //! This module contains kernel helper functions that may be exposed to specific BPF
  2. //! program types. These helpers can be used to perform common tasks, query and operate on
  3. //! data exposed by the kernel, and perform some operations that would normally be denied
  4. //! by the BPF verifier.
  5. //!
  6. //! Here, we provide some higher-level wrappers around the underlying kernel helpers, but
  7. //! also expose bindings to the underlying helpers as a fall-back in case of a missing
  8. //! implementation.
  9. use core::mem::{self, MaybeUninit};
  10. pub use aya_bpf_bindings::helpers as gen;
  11. #[doc(hidden)]
  12. pub use gen::*;
  13. use crate::cty::{c_char, c_long, c_void};
  14. /// Read bytes stored at `src` and store them as a `T`.
  15. ///
  16. /// Generally speaking, the more specific [`bpf_probe_read_user`] and
  17. /// [`bpf_probe_read_kernel`] should be preferred over this function.
  18. ///
  19. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  20. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  21. ///
  22. /// # Examples
  23. ///
  24. /// ```no_run
  25. /// # #![allow(dead_code)]
  26. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read};
  27. /// # fn try_test() -> Result<(), c_long> {
  28. /// # let kernel_ptr: *const c_int = 0 as _;
  29. /// let my_int: c_int = unsafe { bpf_probe_read(kernel_ptr)? };
  30. ///
  31. /// // Do something with my_int
  32. /// # Ok::<(), c_long>(())
  33. /// # }
  34. /// ```
  35. ///
  36. /// # Errors
  37. ///
  38. /// On failure, this function returns a negative value wrapped in an `Err`.
  39. #[inline]
  40. pub unsafe fn bpf_probe_read<T>(src: *const T) -> Result<T, c_long> {
  41. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  42. let ret = gen::bpf_probe_read(
  43. v.as_mut_ptr() as *mut c_void,
  44. mem::size_of::<T>() as u32,
  45. src as *const c_void,
  46. );
  47. if ret < 0 {
  48. return Err(ret);
  49. }
  50. Ok(v.assume_init())
  51. }
  52. /// Read bytes from the pointer `src` into the provided destination buffer.
  53. ///
  54. /// Generally speaking, the more specific [`bpf_probe_read_user_buf`] and
  55. /// [`bpf_probe_read_kernel_buf`] should be preferred over this function.
  56. ///
  57. /// # Examples
  58. ///
  59. /// ```no_run
  60. /// # #![allow(dead_code)]
  61. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_buf};
  62. /// # fn try_test() -> Result<(), c_long> {
  63. /// # let ptr: *const u8 = 0 as _;
  64. /// let mut buf = [0u8; 16];
  65. /// unsafe { bpf_probe_read_buf(ptr, &mut buf)? };
  66. ///
  67. /// # Ok::<(), c_long>(())
  68. /// # }
  69. /// ```
  70. ///
  71. /// # Errors
  72. ///
  73. /// On failure, this function returns a negative value wrapped in an `Err`.
  74. #[inline]
  75. pub unsafe fn bpf_probe_read_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  76. let ret = gen::bpf_probe_read(
  77. dst.as_mut_ptr() as *mut c_void,
  78. dst.len() as u32,
  79. src as *const c_void,
  80. );
  81. if ret < 0 {
  82. return Err(ret);
  83. }
  84. Ok(())
  85. }
  86. /// Read bytes stored at the _user space_ pointer `src` and store them as a `T`.
  87. ///
  88. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  89. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  90. ///
  91. /// # Examples
  92. ///
  93. /// ```no_run
  94. /// # #![allow(dead_code)]
  95. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user};
  96. /// # fn try_test() -> Result<(), c_long> {
  97. /// # let user_ptr: *const c_int = 0 as _;
  98. /// let my_int: c_int = unsafe { bpf_probe_read_user(user_ptr)? };
  99. ///
  100. /// // Do something with my_int
  101. /// # Ok::<(), c_long>(())
  102. /// # }
  103. /// ```
  104. ///
  105. /// # Errors
  106. ///
  107. /// On failure, this function returns a negative value wrapped in an `Err`.
  108. #[inline]
  109. pub unsafe fn bpf_probe_read_user<T>(src: *const T) -> Result<T, c_long> {
  110. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  111. let ret = gen::bpf_probe_read_user(
  112. v.as_mut_ptr() as *mut c_void,
  113. mem::size_of::<T>() as u32,
  114. src as *const c_void,
  115. );
  116. if ret < 0 {
  117. return Err(ret);
  118. }
  119. Ok(v.assume_init())
  120. }
  121. /// Read bytes from the _user space_ pointer `src` into the provided destination
  122. /// buffer.
  123. ///
  124. /// # Examples
  125. ///
  126. /// ```no_run
  127. /// # #![allow(dead_code)]
  128. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user_buf};
  129. /// # fn try_test() -> Result<(), c_long> {
  130. /// # let user_ptr: *const u8 = 0 as _;
  131. /// let mut buf = [0u8; 16];
  132. /// unsafe { bpf_probe_read_user_buf(user_ptr, &mut buf)? };
  133. ///
  134. /// # Ok::<(), c_long>(())
  135. /// # }
  136. /// ```
  137. ///
  138. /// # Errors
  139. ///
  140. /// On failure, this function returns a negative value wrapped in an `Err`.
  141. #[inline]
  142. pub unsafe fn bpf_probe_read_user_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  143. let ret = gen::bpf_probe_read_user(
  144. dst.as_mut_ptr() as *mut c_void,
  145. dst.len() as u32,
  146. src as *const c_void,
  147. );
  148. if ret < 0 {
  149. return Err(ret);
  150. }
  151. Ok(())
  152. }
  153. /// Read bytes stored at the _kernel space_ pointer `src` and store them as a `T`.
  154. ///
  155. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the kernel space address
  156. /// `src`. See `bpf_probe_read_user` for reading user space memory.
  157. ///
  158. /// # Examples
  159. ///
  160. /// ```no_run
  161. /// # #![allow(dead_code)]
  162. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel};
  163. /// # fn try_test() -> Result<(), c_long> {
  164. /// # let kernel_ptr: *const c_int = 0 as _;
  165. /// let my_int: c_int = unsafe { bpf_probe_read_kernel(kernel_ptr)? };
  166. ///
  167. /// // Do something with my_int
  168. /// # Ok::<(), c_long>(())
  169. /// # }
  170. /// ```
  171. ///
  172. /// # Errors
  173. ///
  174. /// On failure, this function returns a negative value wrapped in an `Err`.
  175. #[inline]
  176. pub unsafe fn bpf_probe_read_kernel<T>(src: *const T) -> Result<T, c_long> {
  177. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  178. let ret = gen::bpf_probe_read_kernel(
  179. v.as_mut_ptr() as *mut c_void,
  180. mem::size_of::<T>() as u32,
  181. src as *const c_void,
  182. );
  183. if ret < 0 {
  184. return Err(ret);
  185. }
  186. Ok(v.assume_init())
  187. }
  188. /// Read bytes from the _kernel space_ pointer `src` into the provided destination
  189. /// buffer.
  190. ///
  191. /// # Examples
  192. ///
  193. /// ```no_run
  194. /// # #![allow(dead_code)]
  195. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel_buf};
  196. /// # fn try_test() -> Result<(), c_long> {
  197. /// # let kernel_ptr: *const u8 = 0 as _;
  198. /// let mut buf = [0u8; 16];
  199. /// unsafe { bpf_probe_read_kernel_buf(kernel_ptr, &mut buf)? };
  200. ///
  201. /// # Ok::<(), c_long>(())
  202. /// # }
  203. /// ```
  204. ///
  205. /// # Errors
  206. ///
  207. /// On failure, this function returns a negative value wrapped in an `Err`.
  208. #[inline]
  209. pub unsafe fn bpf_probe_read_kernel_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  210. let ret = gen::bpf_probe_read_kernel(
  211. dst.as_mut_ptr() as *mut c_void,
  212. dst.len() as u32,
  213. src as *const c_void,
  214. );
  215. if ret < 0 {
  216. return Err(ret);
  217. }
  218. Ok(())
  219. }
  220. /// Read a null-terminated string stored at `src` into `dest`.
  221. ///
  222. /// Generally speaking, the more specific [`bpf_probe_read_user_str`] and
  223. /// [`bpf_probe_read_kernel_str`] should be preferred over this function.
  224. ///
  225. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  226. /// be truncated to the size of `dest`.
  227. ///
  228. /// # Examples
  229. ///
  230. /// ```no_run
  231. /// # #![allow(dead_code)]
  232. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_str};
  233. /// # fn try_test() -> Result<(), c_long> {
  234. /// # let kernel_ptr: *const u8 = 0 as _;
  235. /// let mut my_str = [0u8; 16];
  236. /// let num_read = unsafe { bpf_probe_read_str(kernel_ptr, &mut my_str)? };
  237. ///
  238. /// // Do something with num_read and my_str
  239. /// # Ok::<(), c_long>(())
  240. /// # }
  241. /// ```
  242. ///
  243. /// # Errors
  244. ///
  245. /// On failure, this function returns Err(-1).
  246. #[inline]
  247. pub unsafe fn bpf_probe_read_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  248. let len = gen::bpf_probe_read_str(
  249. dest.as_mut_ptr() as *mut c_void,
  250. dest.len() as u32,
  251. src as *const c_void,
  252. );
  253. if len < 0 {
  254. return Err(-1);
  255. }
  256. let mut len = len as usize;
  257. if len > dest.len() {
  258. // this can never happen, it's needed to tell the verifier that len is
  259. // bounded
  260. len = dest.len();
  261. }
  262. Ok(len as usize)
  263. }
  264. /// Read a null-terminated string from _user space_ stored at `src` into `dest`.
  265. ///
  266. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  267. /// be truncated to the size of `dest`.
  268. ///
  269. /// # Examples
  270. ///
  271. /// ```no_run
  272. /// # #![allow(dead_code)]
  273. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str};
  274. /// # fn try_test() -> Result<(), c_long> {
  275. /// # let user_ptr: *const u8 = 0 as _;
  276. /// let mut my_str = [0u8; 16];
  277. /// let num_read = unsafe { bpf_probe_read_user_str(user_ptr, &mut my_str)? };
  278. ///
  279. /// // Do something with num_read and my_str
  280. /// # Ok::<(), c_long>(())
  281. /// # }
  282. /// ```
  283. ///
  284. /// # Errors
  285. ///
  286. /// On failure, this function returns Err(-1).
  287. #[inline]
  288. pub unsafe fn bpf_probe_read_user_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  289. let len = gen::bpf_probe_read_user_str(
  290. dest.as_mut_ptr() as *mut c_void,
  291. dest.len() as u32,
  292. src as *const c_void,
  293. );
  294. if len < 0 {
  295. return Err(-1);
  296. }
  297. let mut len = len as usize;
  298. if len > dest.len() {
  299. // this can never happen, it's needed to tell the verifier that len is
  300. // bounded
  301. len = dest.len();
  302. }
  303. Ok(len as usize)
  304. }
  305. /// Read a null-terminated string from _kernel space_ stored at `src` into `dest`.
  306. ///
  307. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  308. /// be truncated to the size of `dest`.
  309. ///
  310. /// # Examples
  311. ///
  312. /// ```no_run
  313. /// # #![allow(dead_code)]
  314. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str};
  315. /// # fn try_test() -> Result<(), c_long> {
  316. /// # let kernel_ptr: *const u8 = 0 as _;
  317. /// let mut my_str = [0u8; 16];
  318. /// let num_read = unsafe { bpf_probe_read_kernel_str(kernel_ptr, &mut my_str)? };
  319. ///
  320. /// // Do something with num_read and my_str
  321. /// # Ok::<(), c_long>(())
  322. /// # }
  323. /// ```
  324. ///
  325. /// # Errors
  326. ///
  327. /// On failure, this function returns Err(-1).
  328. #[inline]
  329. pub unsafe fn bpf_probe_read_kernel_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  330. let len = gen::bpf_probe_read_kernel_str(
  331. dest.as_mut_ptr() as *mut c_void,
  332. dest.len() as u32,
  333. src as *const c_void,
  334. );
  335. if len < 0 {
  336. return Err(-1);
  337. }
  338. let mut len = len as usize;
  339. if len > dest.len() {
  340. // this can never happen, it's needed to tell the verifier that len is
  341. // bounded
  342. len = dest.len();
  343. }
  344. Ok(len as usize)
  345. }
  346. /// Write bytes to the _user space_ pointer `src` and store them as a `T`.
  347. ///
  348. /// # Examples
  349. ///
  350. /// ```no_run
  351. /// # #![allow(dead_code)]
  352. /// # use aya_bpf::{
  353. /// # cty::{c_int, c_long},
  354. /// # helpers::bpf_probe_write_user,
  355. /// # programs::ProbeContext,
  356. /// # };
  357. /// fn try_test(ctx: ProbeContext) -> Result<(), c_long> {
  358. /// let retp: *mut c_int = ctx.arg(0).ok_or(1)?;
  359. /// let val: i32 = 1;
  360. /// // Write the value to the userspace pointer.
  361. /// unsafe { bpf_probe_write_user(retp, &val as *const i32)? };
  362. ///
  363. /// Ok::<(), c_long>(())
  364. /// }
  365. /// ```
  366. ///
  367. /// # Errors
  368. ///
  369. /// On failure, this function returns a negative value wrapped in an `Err`.
  370. #[allow(clippy::fn_to_numeric_cast_with_truncation)]
  371. #[inline]
  372. pub unsafe fn bpf_probe_write_user<T>(dst: *mut T, src: *const T) -> Result<(), c_long> {
  373. let ret = gen::bpf_probe_write_user(
  374. dst as *mut c_void,
  375. src as *const c_void,
  376. mem::size_of::<T>() as u32,
  377. );
  378. if ret < 0 {
  379. return Err(ret);
  380. }
  381. Ok(())
  382. }
  383. /// Read the `comm` field associated with the current task struct
  384. /// as a `[c_char; 16]`.
  385. ///
  386. /// # Examples
  387. ///
  388. /// ```no_run
  389. /// # #![allow(dead_code)]
  390. /// # use aya_bpf::helpers::bpf_get_current_comm;
  391. /// let comm = bpf_get_current_comm();
  392. ///
  393. /// // Do something with comm
  394. /// ```
  395. ///
  396. /// # Errors
  397. ///
  398. /// On failure, this function returns a negative value wrapped in an `Err`.
  399. #[inline]
  400. pub fn bpf_get_current_comm() -> Result<[c_char; 16], c_long> {
  401. let mut comm: [c_char; 16usize] = [0; 16];
  402. let ret = unsafe { gen::bpf_get_current_comm(&mut comm as *mut _ as *mut c_void, 16u32) };
  403. if ret == 0 {
  404. Ok(comm)
  405. } else {
  406. Err(ret)
  407. }
  408. }
  409. /// Read the process id and thread group id associated with the current task struct as
  410. /// a `u64`.
  411. ///
  412. /// In the return value, the upper 32 bits are the `tgid`, and the lower 32 bits are the
  413. /// `pid`. That is, the returned value is equal to: `(tgid << 32) | pid`. A caller may
  414. /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit
  415. /// shift and casting to a `u32`.
  416. ///
  417. /// Note that the naming conventions used in the kernel differ from user space. From the
  418. /// perspective of user space, `pid` may be thought of as the thread id, and `tgid` may be
  419. /// thought of as the process id. For single-threaded processes, these values are
  420. /// typically the same.
  421. ///
  422. /// # Examples
  423. ///
  424. /// ```no_run
  425. /// # #![allow(dead_code)]
  426. /// # use aya_bpf::helpers::bpf_get_current_pid_tgid;
  427. /// let tgid = (bpf_get_current_pid_tgid() >> 32) as u32;
  428. /// let pid = bpf_get_current_pid_tgid() as u32;
  429. ///
  430. /// // Do something with pid and tgid
  431. /// ```
  432. #[inline]
  433. pub fn bpf_get_current_pid_tgid() -> u64 {
  434. unsafe { gen::bpf_get_current_pid_tgid() }
  435. }
  436. /// Read the user id and group id associated with the current task struct as
  437. /// a `u64`.
  438. ///
  439. /// In the return value, the upper 32 bits are the `gid`, and the lower 32 bits are the
  440. /// `uid`. That is, the returned value is equal to: `(gid << 32) | uid`. A caller may
  441. /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit
  442. /// shift and casting to a `u32`.
  443. ///
  444. /// # Examples
  445. ///
  446. /// ```no_run
  447. /// # #![allow(dead_code)]
  448. /// # use aya_bpf::helpers::bpf_get_current_uid_gid;
  449. /// let gid = (bpf_get_current_uid_gid() >> 32) as u32;
  450. /// let uid = bpf_get_current_uid_gid() as u32;
  451. ///
  452. /// // Do something with uid and gid
  453. /// ```
  454. #[inline]
  455. pub fn bpf_get_current_uid_gid() -> u64 {
  456. unsafe { gen::bpf_get_current_uid_gid() }
  457. }