#!/bin/bash

# Title: Kernel Exploit Checker
# Description: Check for known kernel vulnerabilities and provide exploitation guidance
# Author: Jonas Resch

# Define kernel exploit database with CVE, affected versions, exploit URL and details
declare -A KERNEL_EXPLOITS
KERNEL_EXPLOITS["CVE-2021-4034"]="5.0.0,5.15.0,pkexec Local Privilege Escalation,https://github.com/arthepsy/CVE-2021-4034,High impact polkit vulnerability allowing any unprivileged user to gain root privileges"
KERNEL_EXPLOITS["CVE-2021-3156"]="3.0.0,5.11.0,Sudo Baron Samedit,https://github.com/worawit/CVE-2021-3156,Heap-based buffer overflow in sudo allowing any unprivileged user to gain root privileges"
KERNEL_EXPLOITS["CVE-2021-3560"]="3.0.0,5.13.0,polkit Authentication Bypass,https://github.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation,Race condition in polkit allowing local privilege escalation"
KERNEL_EXPLOITS["CVE-2021-22555"]="2.6.19,5.13.0,Netfilter Heap Out-of-Bounds Write,https://google.github.io/security-research/pocs/linux/cve-2021-22555/writeup.html,Critical vulnerability in Linux Netfilter"
KERNEL_EXPLOITS["CVE-2022-0847"]="5.8.0,5.16.11,Dirty Pipe,https://github.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit,Overwriting data in read-only files"
KERNEL_EXPLOITS["CVE-2022-2586"]="5.5.0,5.18.14,nft_object Use-After-Free,https://www.exploit-db.com/exploits/50896,Kernel privilege escalation via Netfilter"
KERNEL_EXPLOITS["CVE-2022-2588"]="5.5.0,5.18.14,nft_object Double-Free,https://www.openwall.com/lists/oss-security/2022/08/29/5,Kernel privilege escalation via Netfilter"
KERNEL_EXPLOITS["CVE-2019-13272"]="4.10.0,5.1.17,PTRACE_TRACEME,https://github.com/bcoles/kernel-exploits/tree/master/CVE-2019-13272,Local privilege escalation in Linux kernel"
KERNEL_EXPLOITS["CVE-2019-18634"]="1.8.2,1.8.31,Sudo pwfeedback Buffer Overflow,https://github.com/saleemrashid/sudo-cve-2019-18634,Buffer overflow in sudo's pwfeedback option"
KERNEL_EXPLOITS["CVE-2019-15666"]="<5.0.21,USB gadget,https://github.com/wapiflapi/expl/tree/master/cve-2019-15666,A vulnerability in usbfs"
KERNEL_EXPLOITS["CVE-2019-5736"]="N/A,N/A,runc container escape,https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/,Container escape affecting Docker/Kubernetes"
KERNEL_EXPLOITS["CVE-2017-16995"]="4.4.0,4.14.8,get_user/put_user,https://www.exploit-db.com/exploits/45010,eBPF verifier vulnerability"
KERNEL_EXPLOITS["CVE-2017-1000112"]="4.4.0,4.13.1,stack clash,https://github.com/xairy/kernel-exploits/tree/master/CVE-2017-1000112,Race condition with AF_PACKET sockets"
KERNEL_EXPLOITS["CVE-2023-0179"]="Versions before February 2023 fixed patch,netfilter,https://www.openwall.org/lists/oss-security/2023/01/26/7,A vulnerability in the netfilter subsystem"
KERNEL_EXPLOITS["CVE-2023-0386"]="<6.2,overlayfs,https://github.com/xkaneiki/CVE-2023-0386,Linux kernel privilege escalation"
KERNEL_EXPLOITS["CVE-2023-22809"]="1.9.0,1.9.12p1,Sudo bypass,https://github.com/n3m1dotsys/CVE-2023-22809-sudoedit-privesc,Sudo bypass vulnerability"
KERNEL_EXPLOITS["CVE-2023-4911"]="5.1,6.4,Looney Tunables,https://www.hackthebox.com/blog/CVE-2023-4911-Looney-tunables,Vulnerability in the glibc library"
KERNEL_EXPLOITS["CVE-2023-6546"]="Various,Various,gameport read/write ioctl,https://starlabs.sg/advisories/23/23-6546/,Local escalation through gameport module"

# Function to check the system's kernel version and compare with exploits
check_kernel_exploits() {
  print_subtitle "Kernel Exploit Detection"
  
  # Get kernel version
  kernel_version=$(uname -r)
  print_info "Current kernel version: $kernel_version"
  
  # Check if the kernel version is in a format we can parse
  if ! echo "$kernel_version" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+'; then
    print_warning "Unusual kernel version format, exploit detection might be less accurate"
  fi
  
  # Extract major, minor and patch version
  kernel_major=$(echo "$kernel_version" | cut -d. -f1)
  kernel_minor=$(echo "$kernel_version" | cut -d. -f2)
  kernel_patch=$(echo "$kernel_version" | cut -d. -f3 | cut -d- -f1)
  
  # Convert to comparable format
  kernel_num=$((kernel_major * 10000 + kernel_minor * 100 + kernel_patch))
  
  # Counter for found exploits
  found_exploits=0
  
  # Check each exploit
  print_info "Checking for known kernel vulnerabilities..."
  
  for cve in "${!KERNEL_EXPLOITS[@]}"; do
    # Split the exploit data
    IFS=',' read -r min_version max_version name exploit_url description <<< "${KERNEL_EXPLOITS[$cve]}"
    
    # Skip if not applicable to standard kernels
    if [[ "$min_version" == "N/A" ]]; then
      # Special case for container-specific exploits
      if [[ "$cve" == "CVE-2019-5736" ]] && ( [ -f /.dockerenv ] || grep -q "docker\|lxc" /proc/1/cgroup 2>/dev/null ); then
        print_critical "${RED}[!] $cve - $name${NC} (Container Escape)"
        print_critical "    ${RED}→ Affects: Docker/Kubernetes containers${NC}"
        print_critical "    ${RED}→ Description: $description${NC}"
        print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
        found_exploits=$((found_exploits + 1))
      fi
      continue
    fi
    
    # Parse min version
    min_major=$(echo "$min_version" | cut -d. -f1)
    min_minor=$(echo "$min_version" | cut -d. -f2)
    min_patch=$(echo "$min_version" | cut -d. -f3)
    min_num=$((min_major * 10000 + min_minor * 100 + min_patch))
    
    # Parse max version
    max_major=$(echo "$max_version" | cut -d. -f1)
    max_minor=$(echo "$max_version" | cut -d. -f2)
    max_patch=$(echo "$max_version" | cut -d. -f3)
    max_num=$((max_major * 10000 + max_minor * 100 + max_patch))
    
    # Check if kernel version is in vulnerable range
    if [ "$kernel_num" -ge "$min_num" ] && [ "$kernel_num" -le "$max_num" ]; then
      # Confirm by checking additional conditions
      
      # Check for Dirty Pipe specific conditions
      if [[ "$cve" == "CVE-2022-0847" ]]; then
        # Extra check for specific kernel configs
        if grep -q "CONFIG_PIPE=y" /boot/config-$(uname -r) 2>/dev/null; then
          print_critical "${RED}[!] $cve - $name${NC} (High Probability)"
          print_critical "    ${RED}→ Affects: Linux kernel $min_version-$max_version${NC}"
          print_critical "    ${RED}→ Description: $description${NC}"
          print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
          print_critical "    ${RED}→ POC Command: echo 'Dirty Pipe Test' | ./cve-2022-0847 /etc/passwd 1${NC}"
          found_exploits=$((found_exploits + 1))
        else
          print_warning "${YELLOW}[!] $cve - $name${NC} (Needs Verification)"
          print_warning "    ${YELLOW}→ Affects: Linux kernel $min_version-$max_version${NC}"
          print_warning "    ${YELLOW}→ Description: $description${NC}"
          print_warning "    ${YELLOW}→ Need to verify CONFIG_PIPE is enabled${NC}"
        fi
        continue
      fi
      
      # Check for Polkit specific conditions
      if [[ "$cve" == "CVE-2021-4034" ]] || [[ "$cve" == "CVE-2021-3560" ]]; then
        if command_exists pkexec || [ -f "/usr/bin/pkexec" ]; then
          pkexec_version=$(pkexec --version 2>/dev/null | head -n1)
          print_critical "${RED}[!] $cve - $name${NC} (High Probability)"
          print_critical "    ${RED}→ Affects: Polkit (pkexec: $pkexec_version)${NC}"
          print_critical "    ${RED}→ Description: $description${NC}"
          print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
          found_exploits=$((found_exploits + 1))
        else
          print_warning "${YELLOW}[!] $cve - $name${NC} (May Not Apply)"
          print_warning "    ${YELLOW}→ pkexec not found, vulnerability may not apply${NC}"
        fi
        continue
      fi
      
      # Check for Sudo specific vulnerabilities
      if [[ "$cve" == "CVE-2021-3156" ]] || [[ "$cve" == "CVE-2019-18634" ]] || [[ "$cve" == "CVE-2023-22809" ]]; then
        if command_exists sudo; then
          sudo_version=$(sudo -V 2>/dev/null | head -n1 | awk '{print $3}')
          
          if [[ "$cve" == "CVE-2021-3156" ]] && [[ "$sudo_version" < "1.9.5p2" ]]; then
            print_critical "${RED}[!] $cve - $name${NC} (Confirmed)"
            print_critical "    ${RED}→ Affects: sudo versions before 1.9.5p2 (found: $sudo_version)${NC}"
            print_critical "    ${RED}→ Description: $description${NC}"
            print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
            found_exploits=$((found_exploits + 1))
          elif [[ "$cve" == "CVE-2019-18634" ]] && [[ "$sudo_version" < "1.8.31" ]]; then
            # Check if pwfeedback is enabled
            if grep -q "pwfeedback" /etc/sudoers 2>/dev/null; then
              print_critical "${RED}[!] $cve - $name${NC} (Confirmed)"
              print_critical "    ${RED}→ Affects: sudo versions before 1.8.31 with pwfeedback enabled${NC}"
              print_critical "    ${RED}→ Description: $description${NC}"
              print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
              found_exploits=$((found_exploits + 1))
            else
              print_warning "${YELLOW}[!] $cve - $name${NC} (Vulnerable version but pwfeedback not enabled)"
            fi
          elif [[ "$cve" == "CVE-2023-22809" ]] && [[ "$sudo_version" < "1.9.12p1" ]]; then
            print_critical "${RED}[!] $cve - $name${NC} (Potential)"
            print_critical "    ${RED}→ Affects: sudo versions before 1.9.12p1 (found: $sudo_version)${NC}"
            print_critical "    ${RED}→ Description: $description${NC}"
            print_critical "    ${RED}→ Exploit: $exploit_url${NC}"
            found_exploits=$((found_exploits + 1))
          fi
        fi
        continue
      fi
      
      # Default case - just report the vulnerability
      print_warning "${YELLOW}[!] $cve - $name${NC} (Potential)"
      print_warning "    ${YELLOW}→ Affects: Linux kernel $min_version-$max_version${NC}"
      print_warning "    ${YELLOW}→ Description: $description${NC}"
      print_warning "    ${YELLOW}→ Exploit: $exploit_url${NC}"
      found_exploits=$((found_exploits + 1))
    fi
  done
  
  # Check for presence of exploit mitigation features
  print_info "Checking for kernel hardening features..."
  
  # Check for SMEP (Supervisor Mode Execution Prevention)
  smep_enabled=$(grep -i "smep" /proc/cpuinfo 2>/dev/null)
  if [ -n "$smep_enabled" ]; then
    print_success "SMEP (Supervisor Mode Execution Prevention) is enabled"
  else
    print_warning "SMEP doesn't appear to be enabled - kernel exploits may be easier"
  fi
  
  # Check for SMAP (Supervisor Mode Access Prevention)
  smap_enabled=$(grep -i "smap" /proc/cpuinfo 2>/dev/null)
  if [ -n "$smap_enabled" ]; then
    print_success "SMAP (Supervisor Mode Access Prevention) is enabled"
  else
    print_warning "SMAP doesn't appear to be enabled - kernel exploits may be easier"
  fi
  
  # Check for KAISER/KPTI (Kernel Page Table Isolation)
  kpti_enabled=$(grep -i "pti" /proc/cpuinfo 2>/dev/null)
  if [ -n "$kpti_enabled" ]; then
    print_success "KPTI (Kernel Page Table Isolation) is enabled"
  else
    print_warning "KPTI doesn't appear to be enabled - Meltdown attacks may be possible"
  fi
  
  # Report summary
  if [ "$found_exploits" -gt 0 ]; then
    print_critical "Found $found_exploits potential kernel vulnerabilities!"
  else
    print_success "No known kernel vulnerabilities detected."
  fi
}

# Add Linux Exploit Suggester integration
run_linux_exploit_suggester() {
  print_subtitle "Linux Exploit Suggester"
  
  print_info "Running Linux Exploit Suggester for comprehensive checks..."
  
  # Create temp directory
  temp_dir=$(create_temp_dir)
  
  # Try to download and run Linux Exploit Suggester
  if command_exists curl || command_exists wget; then
    les_url="https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh"
    
    if command_exists curl; then
      curl -s "$les_url" -o "$temp_dir/les.sh" 2>/dev/null
    else
      wget -q "$les_url" -O "$temp_dir/les.sh" 2>/dev/null
    fi
    
    if [ -f "$temp_dir/les.sh" ]; then
      chmod +x "$temp_dir/les.sh"
      print_info "Running Linux Exploit Suggester..."
      les_output=$("$temp_dir/les.sh" 2>/dev/null)
      
      # Extract and highlight CVEs
      if [ -n "$les_output" ]; then
        echo "$les_output" | grep -E "CVE-[0-9]+-[0-9]+" | grep -i "kernel" | sed -e "s/\(CVE-[0-9]\+-[0-9]\+\)/${RED}\1${NC}/g"
      else
        print_warning "Linux Exploit Suggester didn't return any results"
      fi
    else
      print_warning "Failed to download Linux Exploit Suggester"
    fi
    
    # Clean up
    rm -rf "$temp_dir"
  else
    print_warning "curl or wget is required to download Linux Exploit Suggester"
  fi
}

# Run integration with additional exploit detectors
run_additional_exploit_checks() {
  print_subtitle "Additional Kernel Checks"
  
  # Check for Dirty COW (CVE-2016-5195)
  if [ "$kernel_major" -eq 2 ] || ( [ "$kernel_major" -eq 3 ] && [ "$kernel_minor" -lt 19 ] ) || \
    ( [ "$kernel_major" -eq 4 ] && [ "$kernel_minor" -lt 9 ] ); then
    print_critical "${RED}[!] System is vulnerable to Dirty COW (CVE-2016-5195)!${NC}"
    print_critical "    ${RED}→ Affects: Linux kernel versions before 3.19.0 and 4.9.0${NC}"
    print_critical "    ${RED}→ Description: Race condition in mm/gup.c allowing local privilege escalation${NC}"
    print_critical "    ${RED}→ Exploit: https://github.com/firefart/dirtycow${NC}"
  fi
  
  # Check for BlueZ vulnerability (CVE-2021-3573)
  if command_exists bluetoothd; then
    bluez_version=$(bluetoothd -v 2>/dev/null)
    if [ -n "$bluez_version" ]; then
      if [[ "$bluez_version" < "5.63" ]]; then
        print_warning "${YELLOW}[!] BlueZ version $bluez_version may be vulnerable to CVE-2021-3573${NC}"
        print_warning "    ${YELLOW}→ Affects: BlueZ before 5.63${NC}"
        print_warning "    ${YELLOW}→ Description: NULL pointer dereference in the AVDTP implementation${NC}"
      fi
    fi
  fi
  
  # Check for eBPF vulnerabilities
  if [ -d "/sys/fs/bpf" ] || [ -d "/proc/sys/net/core/bpf_jit_enable" ]; then
    bpf_jit_enabled=$(cat /proc/sys/net/core/bpf_jit_enable 2>/dev/null)
    if [ "$bpf_jit_enabled" = "1" ]; then
      print_warning "${YELLOW}[!] BPF JIT compiler is enabled, this can be used for exploits${NC}"
      print_warning "    ${YELLOW}→ Check for CVE-2020-8835, CVE-2020-27194, and others${NC}"
    else
      print_success "BPF JIT compiler is disabled"
    fi
  fi
}

# Main function to run all kernel exploit checks
kernel_exploit_checks() {
  print_title "Kernel Vulnerabilities"
  
  # Run primary kernel exploit check
  check_kernel_exploits
  
  # Run Linux Exploit Suggester if in thorough mode
  if [ "$THOROUGH" ]; then
    run_linux_exploit_suggester
  fi
  
  # Run additional specialized exploit checks
  run_additional_exploit_checks
  
  # Wait for user if wait mode is enabled
  wait_for_user
} 