/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept setns syscall
 *
 * Notes:
 *  - Dump namespace metadata
 *
 * Caveats:
 *  - None
 *
 * Timeline:
 *  - Created: 29.I.2020
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

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


char p_sys_setns_kretprobe_state = 0;

static struct kretprobe p_sys_setns_kretprobe = {
    .kp.symbol_name = P_GET_SYSCALL_NAME(setns),
    .handler = p_sys_setns_ret,
    .entry_handler = p_sys_setns_entry,
    .data_size = sizeof(struct p_sys_setns_data),
};


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

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_ed_enforce_validation();

   p_tasks_write_lock(&p_flags);
   if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
#ifdef P_LKRG_TASK_OFF_DEBUG
      p_debug_off_flag_off(p_tmp, 47);
#endif
      // This process is on the ED list - set temporary 'disable' flag!
      p_set_ed_process_off(p_tmp);
   }
   p_tasks_write_unlock(&p_flags);

   return 0;
}


int p_sys_setns_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_debug_kprobe_log(
          "sys_setns returned value => %ld comm[%s] Pid:%d parent[%d]",
                       p_regs_get_ret(p_regs),current->comm,current->pid,current->real_parent->pid);

   // Update process
   p_tasks_write_lock(&p_flags);
   if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
      if (!p_regs_get_ret(p_regs)) {
         // This process is on the ED list - update information!
         p_update_ed_process(p_tmp, current, 0);
      }
#ifdef P_LKRG_TASK_OFF_DEBUG
      p_debug_off_flag_on(p_tmp, 48);
#endif
      p_set_ed_process_on(p_tmp);
   }
   p_tasks_write_unlock(&p_flags);

//   p_ed_enforce_validation();

   return 0;
}


GENERATE_INSTALL_FUNC(sys_setns)
