/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept 'generic_permission' function
 *
 * Notes:
 *  - Enforce Exploit Detection validation
 *
 * Caveats:
 *  - Originally, this file was placing hooks on 'may_open' function.
 *    Unfortunately, GCC (8+) might enable ISRA optimization when -Ox
 *    switch was used. During kernel compilation it is usually enabled,
 *    and as a side effect we have ISRA optimization as well
 *    (undesired for LKRG). ISRA performs interprocedural scalar
 *    replacement of aggregates, removal of unused parameters and
 *    replacement of parameters passed by reference by parameters passed
 *    by value. Since it's a very invasive modification ISRA changes
 *    symbol name of the functions which was modified.
 *    Alexander (Solar Designer) pointed out that in fact we could hook
 *    inode_permission() instead. This function is exported and
 *    additionally, we'll improve our coverage since it is called on more
 *    cases than 'may_open', including things such as permission checks
 *    on creating/removing of directories, (un)linking of files, and
 *    searching for files in directories with restricted permissions.
 *    LKRG hooks 'generic_permission' since this function is also exported
 *    and is called by inode_permission() after various checks have been
 *    made. It is also called in a few other specialized cases.
 *
 * Timeline:
 *  - Replace 'may_open' with 'generic_permission': 17.IX.2018
 *  - Created: 04.X.2017
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

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


char p_generic_permission_kretprobe_state = 0;

static struct kretprobe p_generic_permission_kretprobe = {
    .kp.symbol_name = "generic_permission",
    .handler = p_generic_permission_ret,
    .entry_handler = p_generic_permission_entry,
    .data_size = sizeof(struct p_generic_permission_data),
};

/*
 * x86-64 syscall ABI:
 *  *rax - syscall_number
 *    rdi - 1st argument
 *    rsi - 2nd argument
 *    rdx - 3rd argument
 *    rcx - 4th argument
 *
 *    r8  - 5th one
 *    r9  - 6th one
 */

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

   struct p_ed_process *p_tmp = NULL;
   unsigned long p_flags;

   p_ed_pcfi_cpu(1);

   if (p_is_ed_task(current)) {
      p_tasks_read_lock(&p_flags);
      if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
         p_ed_enforce_pcfi(current, p_tmp, p_regs);
         p_verify_addr_limit(p_tmp, current);
      }
      p_ed_validate_current();
      p_tasks_read_unlock(&p_flags);
   }

   return 0;
}


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

   return 0;
}


GENERATE_INSTALL_FUNC(generic_permission)
