/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept setgid syscall
 *
 * Notes:
 *  - None
 *
 * Caveats:
 *  - None
 *
 * Timeline:
 *  - Created: 09.IX.2017
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

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


char p_sys_setgid_kretprobe_state = 0;

static struct kretprobe p_sys_setgid_kretprobe = {
    .kp.symbol_name = P_GET_SET_ID_NAME(setgid),
    .handler = p_sys_setgid_ret,
    .entry_handler = p_sys_setgid_entry,
    .data_size = sizeof(struct p_sys_setgid_data),
};


int p_sys_setgid_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, 45);
#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_setgid_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_debug_kprobe_log(
          "Setgid 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, 46);
#endif
      p_set_ed_process_on(p_tmp);
   }
   p_tasks_write_unlock(&p_flags);

//   p_ed_enforce_validation();

   return 0;
}


GENERATE_INSTALL_FUNC(sys_setgid)
