/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept 'ovl_dentry_is_whiteout' function which is called by
 *    'ovl_create_or_link'.
 *
 * Notes:
 *  - We are maintianing Red-Black tree of pid's for Exploit Detection feature.
 *    When process calls 'ovl_create_or_link', we need to correctly handle
 *    this situation and adjust 'off' flag
 *
 * Caveats:
 *  - Originally, 'ovl_create_or_link' function was hooked.
 *    Due the fact it is declared with 'static' keyword, it may be inlined.
 *
 * Timeline:
 *  - Modified: 27.VII.2022
 *  - Created:  28.III.2019
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

#include "../../../../../../p_lkrg_main.h"

#if P_OVL_OVERRIDE_SYNC_MODE

char p_ovl_override_sync_kretprobe_state = 0;

static struct kretprobe p_ovl_override_sync_kretprobe = {
    .kp.symbol_name = P_OVL_OVERRIDE_SYNC_FUNC,
    .handler = p_ovl_override_sync_ret,
    .entry_handler = p_ovl_override_sync_entry,
    .data_size = sizeof(struct p_ovl_override_sync_data),
};


void p_reinit_ovl_override_sync_kretprobe(void) {

   memset(&p_ovl_override_sync_kretprobe,0x0,sizeof(struct kretprobe));
   p_ovl_override_sync_kretprobe.kp.symbol_name = P_OVL_OVERRIDE_SYNC_FUNC;
   p_ovl_override_sync_kretprobe.handler = p_ovl_override_sync_ret;
   p_ovl_override_sync_kretprobe.entry_handler = p_ovl_override_sync_entry;
   p_ovl_override_sync_kretprobe.data_size = sizeof(struct p_ovl_override_sync_data);
   p_ovl_override_sync_kretprobe.maxactive = p_get_kprobe_maxactive();
}

int p_ovl_override_sync_entry(struct kretprobe_instance *p_ri, struct pt_regs *p_regs) {

   return 0;
}


notrace int p_ovl_override_sync_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   if (p_is_ed_task(current)) {
      // Update process
      p_tasks_write_lock(&p_flags);
      if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
         if (p_verify_ovl_override_sync(p_tmp)) {
#ifdef P_LKRG_TASK_OFF_DEBUG
            p_debug_off_flag_override_on(p_tmp, 30, p_regs);
#endif
            p_set_ed_process_override_on(p_tmp);
         }
      }
      p_ed_validate_current();
      p_ed_enforce_pcfi(current, p_tmp, p_regs);
      p_tasks_write_unlock(&p_flags);
   }

   return 0;
}


GENERATE_INSTALL_FUNC(ovl_override_sync)
#endif
