xe1phix

eBPF-Malicious-Activity-Monitor.sh

May 2nd, 2025
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 88.37 KB | Cybersecurity | 0 0
  1. #!/bin/bash
  2. # eBPF Malicious Activity Monitor
  3. #
  4. # This script uses eBPF to monitor system activities in real-time for detecting
  5. # suspicious behaviors that could indicate malware. It traces syscalls, file operations,
  6. # network connections, and process creation with minimal overhead.
  7. #
  8. # Options:
  9. # 1. Monitor suspicious file operations
  10. # 2. Monitor suspicious network activities
  11. # 3. Monitor process creation chains
  12. # 4. Monitor privilege escalation attempts
  13. # 5. Detect library injection
  14. # 6. Monitor system call anomalies
  15. # 7. Detect container escape attempts
  16. # 8. Monitor suspicious kernel module loading
  17. # 9. Track file execution flow
  18. # 10. Monitor suspicious memory access patterns
  19. # 11. Track command execution
  20. # 12. DNS monitoring for data exfiltration
  21. # 13. Detect abnormal process behavior
  22. # 14. Monitor data access patterns
  23. # 15. Generate activity report
  24. # 16. Exit
  25.  
  26. # Check for required tools
  27. check_required_tools() {
  28.     missing_tools=()
  29.    
  30.     command -v bpftrace >/dev/null 2>&1 || missing_tools+=("bpftrace")
  31.     command -v bpftool >/dev/null 2>&1 || missing_tools+=("bpftool")
  32.    
  33.     if [ ${#missing_tools[@]} -gt 0 ]; then
  34.         echo "The following required tools are missing:"
  35.         for tool in "${missing_tools[@]}"; do
  36.             echo "- $tool"
  37.         done
  38.         echo "Install bpftrace and bpftool packages first."
  39.         return 1
  40.     fi
  41.    
  42.     # Check kernel version, need 4.18+ for good eBPF support
  43.     kernel_version=$(uname -r | cut -d. -f1,2)
  44.     if (( $(echo "$kernel_version < 4.18" | bc -l) )); then
  45.         echo "Warning: Kernel version $kernel_version may have limited eBPF support."
  46.         echo "Recommended kernel version is 4.18 or higher."
  47.     fi
  48.    
  49.     return 0
  50. }
  51.  
  52. # Function to display menu
  53. show_menu() {
  54.     clear
  55.     echo "===== eBPF Malicious Activity Monitor ====="
  56.     echo "1. Monitor suspicious file operations"
  57.     echo "2. Monitor suspicious network activities"
  58.     echo "3. Monitor process creation chains"
  59.     echo "4. Monitor privilege escalation attempts"
  60.     echo "5. Detect library injection"
  61.     echo "6. Monitor system call anomalies"
  62.     echo "7. Detect container escape attempts"
  63.     echo "8. Monitor suspicious kernel module loading"
  64.     echo "9. Track file execution flow"
  65.     echo "10. Monitor suspicious memory access patterns"
  66.     echo "11. Track command execution"
  67.     echo "12. DNS monitoring for data exfiltration"
  68.     echo "13. Detect abnormal process behavior"
  69.     echo "14. Monitor data access patterns"
  70.     echo "15. Generate activity report"
  71.     echo "16. Exit"
  72.     echo "==========================================="
  73.     echo "Enter your choice [1-16]: "
  74. }
  75.  
  76. # Function to monitor suspicious file operations
  77. monitor_file_operations() {
  78.     echo "Monitoring suspicious file operations using eBPF. Press Ctrl+C to stop."
  79.    
  80.     # Create temporary BPF program
  81.     cat > /tmp/file_monitor.bt << 'EOF'
  82. #!/usr/bin/env bpftrace
  83. #include <linux/fs.h>
  84. #include <linux/path.h>
  85.  
  86. // Sensitive directories to monitor
  87. BEGIN
  88. {
  89.     printf("Monitoring suspicious file operations...\n");
  90.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "FILE OPERATION");
  91. }
  92.  
  93. // Monitor file opens in sensitive locations
  94. tracepoint:syscalls:sys_enter_openat
  95. {
  96.     $filename = str(args->filename);
  97.    
  98.     // Check for access to sensitive files and directories
  99.     if (
  100.         strncmp($filename, "/etc/passwd", 11) == 0 ||
  101.         strncmp($filename, "/etc/shadow", 11) == 0 ||
  102.         strncmp($filename, "/etc/ssh", 8) == 0 ||
  103.         strncmp($filename, "/etc/sudoers", 12) == 0 ||
  104.         strncmp($filename, "/etc/crontab", 12) == 0 ||
  105.         strncmp($filename, "/etc/cron.d", 10) == 0 ||
  106.         strncmp($filename, "/var/run/utmp", 13) == 0 ||
  107.         strncmp($filename, "/var/log", 8) == 0 ||
  108.         strncmp($filename, "/proc", 5) == 0 ||
  109.         strncmp($filename, "/dev/mem", 8) == 0 ||
  110.         strncmp($filename, "/boot", 5) == 0 ||
  111.         strncmp($filename, "/lib/modules", 12) == 0 ||
  112.         strncmp($filename, "/root", 5) == 0
  113.     )
  114.     {
  115.         time("%H:%M:%S.%f ");
  116.         printf("%-16s %-10d %-8d OPEN %s (flags: %d)\n",
  117.             comm, pid, uid, $filename, args->flags);
  118.     }
  119.    
  120.     // Check for access to hidden files/directories in /tmp, /var/tmp, or /dev/shm
  121.     if (
  122.         (strncmp($filename, "/tmp/", 5) == 0 ||
  123.          strncmp($filename, "/var/tmp/", 9) == 0 ||
  124.          strncmp($filename, "/dev/shm/", 9) == 0) &&
  125.         strncmp(basename($filename), ".", 1) == 0
  126.     )
  127.     {
  128.         time("%H:%M:%S.%f ");
  129.         printf("%-16s %-10d %-8d OPEN HIDDEN FILE %s (flags: %d)\n",
  130.             comm, pid, uid, $filename, args->flags);
  131.     }
  132. }
  133.  
  134. // Monitor file modifications (write) in sensitive locations
  135. tracepoint:syscalls:sys_enter_write
  136. {
  137.     $fd = args->fd;
  138.     $count = args->count;
  139.    
  140.     // Only track writes that might be significant (avoid small writes)
  141.     if ($count > 10) {
  142.         @writes[pid, comm] = $fd;
  143.     }
  144. }
  145.  
  146. // Monitor file creation
  147. tracepoint:syscalls:sys_enter_creat,
  148. tracepoint:syscalls:sys_enter_mkdir
  149. {
  150.     $filename = str(args->filename);
  151.    
  152.     // Check for creation in sensitive locations
  153.     if (
  154.         strncmp($filename, "/etc/", 5) == 0 ||
  155.         strncmp($filename, "/bin/", 5) == 0 ||
  156.         strncmp($filename, "/sbin/", 6) == 0 ||
  157.         strncmp($filename, "/lib/", 5) == 0 ||
  158.         strncmp($filename, "/lib64/", 7) == 0 ||
  159.         strncmp($filename, "/usr/bin/", 9) == 0 ||
  160.         strncmp($filename, "/usr/sbin/", 10) == 0 ||
  161.         strncmp($filename, "/boot/", 6) == 0
  162.     )
  163.     {
  164.         time("%H:%M:%S.%f ");
  165.         printf("%-16s %-10d %-8d CREATE %s\n",
  166.             comm, pid, uid, $filename);
  167.     }
  168.    
  169.     // Check for suspicious file creation (hidden files or suspicious extensions)
  170.     if (
  171.         (strncmp(basename($filename), ".", 1) == 0) ||
  172.         (strncmp($filename + strlen($filename) - 3, ".so", 3) == 0) ||
  173.         (strncmp($filename + strlen($filename) - 2, ".o", 2) == 0) ||
  174.         (strncmp($filename + strlen($filename) - 3, ".ko", 3) == 0)
  175.     )
  176.     {
  177.         time("%H:%M:%S.%f ");
  178.         printf("%-16s %-10d %-8d SUSPICIOUS CREATE %s\n",
  179.             comm, pid, uid, $filename);
  180.     }
  181. }
  182.  
  183. // Monitor chmod
  184. tracepoint:syscalls:sys_enter_chmod,
  185. tracepoint:syscalls:sys_enter_fchmod
  186. {
  187.     $mode = args->mode;
  188.    
  189.     // Monitor suspicious permissions (setuid/setgid, world-writable)
  190.     if (($mode & 06000) || ($mode & 0002)) {
  191.         time("%H:%M:%S.%f ");
  192.         if (probe == "tracepoint:syscalls:sys_enter_chmod") {
  193.             printf("%-16s %-10d %-8d CHMOD %s mode:%o\n",
  194.                 comm, pid, uid, str(args->filename), $mode);
  195.         } else {
  196.             printf("%-16s %-10d %-8d FCHMOD fd:%d mode:%o\n",
  197.                 comm, pid, uid, args->fd, $mode);
  198.         }
  199.     }
  200. }
  201.  
  202. // Monitor file deletion
  203. tracepoint:syscalls:sys_enter_unlink,
  204. tracepoint:syscalls:sys_enter_unlinkat,
  205. tracepoint:syscalls:sys_enter_rmdir
  206. {
  207.     $filename = probe == "tracepoint:syscalls:sys_enter_unlink" ?
  208.                 str(args->pathname) :
  209.                 (probe == "tracepoint:syscalls:sys_enter_rmdir" ?
  210.                  str(args->pathname) :
  211.                  str(args->pathname));
  212.    
  213.     // Check for deletion of sensitive logs or config files
  214.     if (
  215.         strncmp($filename, "/var/log", 8) == 0 ||
  216.         strncmp($filename, "/etc/", 5) == 0 ||
  217.         strncmp($filename, "/root/.bash_history", 19) == 0 ||
  218.         strncmp($filename, "/home/", 6) == 0
  219.     )
  220.     {
  221.         time("%H:%M:%S.%f ");
  222.         printf("%-16s %-10d %-8d DELETE %s\n",
  223.             comm, pid, uid, $filename);
  224.     }
  225. }
  226.  
  227. END
  228. {
  229.     printf("Suspicious file monitoring stopped.\n");
  230. }
  231. EOF
  232.    
  233.     # Run the BPF program
  234.     sudo bpftrace /tmp/file_monitor.bt
  235.    
  236.     # Clean up
  237.     rm -f /tmp/file_monitor.bt
  238. }
  239.  
  240. # Function to monitor suspicious network activities
  241. monitor_network_activities() {
  242.     echo "Monitoring suspicious network activities using eBPF. Press Ctrl+C to stop."
  243.    
  244.     # Create temporary BPF program
  245.     cat > /tmp/network_monitor.bt << 'EOF'
  246. #!/usr/bin/env bpftrace
  247. #include <linux/socket.h>
  248. #include <net/sock.h>
  249.  
  250. BEGIN
  251. {
  252.     printf("Monitoring suspicious network activities...\n");
  253.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "NETWORK ACTIVITY");
  254.    
  255.     // Initialize common suspicious ports table
  256.     @suspicious_ports[21] = "FTP";
  257.     @suspicious_ports[22] = "SSH";
  258.     @suspicious_ports[23] = "Telnet";
  259.     @suspicious_ports[25] = "SMTP";
  260.     @suspicious_ports[445] = "SMB";
  261.     @suspicious_ports[1080] = "SOCKS";
  262.     @suspicious_ports[1433] = "MSSQL";
  263.     @suspicious_ports[1434] = "MSSQL";
  264.     @suspicious_ports[3306] = "MySQL";
  265.     @suspicious_ports[3389] = "RDP";
  266.     @suspicious_ports[4444] = "Metasploit";
  267.     @suspicious_ports[5432] = "PostgreSQL";
  268.     @suspicious_ports[5900] = "VNC";
  269.     @suspicious_ports[5901] = "VNC";
  270.     @suspicious_ports[6379] = "Redis";
  271.     @suspicious_ports[8080] = "HTTP Alt";
  272.     @suspicious_ports[9050] = "Tor";
  273.     @suspicious_ports[9051] = "Tor";
  274. }
  275.  
  276. // Track outgoing connections
  277. tracepoint:syscalls:sys_enter_connect
  278. {
  279.     $sa = (struct sockaddr *)args->uservaddr;
  280.     if ($sa->sa_family == AF_INET || $sa->sa_family == AF_INET6) {
  281.         @connect_attempts[pid, comm] = 1;
  282.     }
  283. }
  284.  
  285. // Detect successful outbound connections
  286. tracepoint:syscalls:sys_exit_connect
  287. /args->ret >= 0 && @connect_attempts[pid, comm]/
  288. {
  289.     delete(@connect_attempts[pid, comm]);
  290.     $sockaddr = (struct sockaddr_in *)curtask->mm->arg_start;
  291.     $dport = ($sockaddr->sin_port >> 8) | (($sockaddr->sin_port << 8) & 0xff00);
  292.     $daddr = ntop($sockaddr->sin_addr.s_addr);
  293.    
  294.     // Check for suspicious destination ports
  295.     $port_info = @suspicious_ports[$dport];
  296.     if ($port_info != 0) {
  297.         time("%H:%M:%S.%f ");
  298.         printf("%-16s %-10d %-8d CONNECT %s:%d [%s]\n",
  299.                comm, pid, uid, $daddr, $dport, str($port_info));
  300.     }
  301.    
  302.     // Log all connections to non-standard web ports
  303.     if ($dport != 80 && $dport != 443 && $dport < 1024) {
  304.         time("%H:%M:%S.%f ");
  305.         printf("%-16s %-10d %-8d CONNECT %s:%d [Non-standard port]\n",
  306.                comm, pid, uid, $daddr, $dport);
  307.     }
  308.    
  309.     // Track high-volume connections
  310.     @connections[comm, pid, $dport] = count();
  311.     if (@connections[comm, pid, $dport] > 10) {
  312.         time("%H:%M:%S.%f ");
  313.         printf("%-16s %-10d %-8d HIGH VOLUME CONNECTIONS to port %d (%d connections)\n",
  314.                comm, pid, uid, $dport, @connections[comm, pid, $dport]);
  315.     }
  316. }
  317.  
  318. // Track listening sockets
  319. tracepoint:syscalls:sys_enter_bind
  320. {
  321.     $sa = (struct sockaddr *)args->umyaddr;
  322.     if ($sa->sa_family == AF_INET || $sa->sa_family == AF_INET6) {
  323.         $sockaddr = (struct sockaddr_in *)$sa;
  324.         $port = ($sockaddr->sin_port >> 8) | (($sockaddr->sin_port << 8) & 0xff00);
  325.         // Check if non-root user is binding to privileged port
  326.         if ($port < 1024 && uid != 0) {
  327.             time("%H:%M:%S.%f ");
  328.             printf("%-16s %-10d %-8d BIND TO PRIVILEGED PORT %d [Non-root user]\n",
  329.                   comm, pid, uid, $port);
  330.         }
  331.        
  332.         // Monitor non-standard ports
  333.         if ($port > 10000) {
  334.             time("%H:%M:%S.%f ");
  335.             printf("%-16s %-10d %-8d BIND TO HIGH PORT %d\n",
  336.                   comm, pid, uid, $port);
  337.         }
  338.     }
  339. }
  340.  
  341. // Monitor raw socket creation (often used for packet sniffing)
  342. tracepoint:syscalls:sys_enter_socket
  343. /args->type == SOCK_RAW/
  344. {
  345.     time("%H:%M:%S.%f ");
  346.     printf("%-16s %-10d %-8d RAW SOCKET CREATION [Possible sniffing]\n",
  347.            comm, pid, uid);
  348. }
  349.  
  350. // Monitor DNS queries for potential data exfiltration
  351. tracepoint:syscalls:sys_enter_sendto,
  352. tracepoint:syscalls:sys_enter_sendmsg
  353. /comm == "dig" || comm == "nslookup" || comm == "host" || comm == "ping" || comm == "drill"/
  354. {
  355.     time("%H:%M:%S.%f ");
  356.     printf("%-16s %-10d %-8d DNS QUERY\n",
  357.            comm, pid, uid);
  358. }
  359.  
  360. // Monitor suspicious data uploads (large writes to network sockets)
  361. tracepoint:syscalls:sys_enter_sendto,
  362. tracepoint:syscalls:sys_enter_sendmsg,
  363. tracepoint:syscalls:sys_enter_write
  364. {
  365.     $fd = args->fd;
  366.     $info = nsid == 0 ? "" : "->";
  367.    
  368.     // Check if fd is a socket and data size is large
  369.     if (args->count > 102400) { // 100KB threshold
  370.         time("%H:%M:%S.%f ");
  371.         printf("%-16s %-10d %-8d LARGE DATA TRANSFER %d bytes\n",
  372.                comm, pid, uid, args->count);
  373.     }
  374. }
  375.  
  376. END
  377. {
  378.     clear(@suspicious_ports);
  379.     clear(@connect_attempts);
  380.     clear(@connections);
  381.     printf("Network monitoring stopped.\n");
  382. }
  383. EOF
  384.    
  385.     # Run the BPF program
  386.     sudo bpftrace /tmp/network_monitor.bt
  387.    
  388.     # Clean up
  389.     rm -f /tmp/network_monitor.bt
  390. }
  391.  
  392. # Function to monitor process creation chains
  393. monitor_process_chains() {
  394.     echo "Monitoring process creation chains using eBPF. Press Ctrl+C to stop."
  395.    
  396.     # Create temporary BPF program
  397.     cat > /tmp/process_monitor.bt << 'EOF'
  398. #!/usr/bin/env bpftrace
  399. #include <linux/sched.h>
  400.  
  401. BEGIN
  402. {
  403.     printf("Monitoring process creation chains...\n");
  404.     printf("%-24s %-10s %-16s %-16s %-8s %s\n", "TIME", "PID", "PARENT", "PROCESS", "UID", "COMMAND");
  405. }
  406.  
  407. // Trace process creation (execve)
  408. tracepoint:syscalls:sys_enter_execve
  409. {
  410.     $filename = str(args->filename);
  411.     $parent_pid = curtask->parent->pid;
  412.     $parent_comm = curtask->parent->comm;
  413.    
  414.     time("%H:%M:%S.%f ");
  415.     printf("%-10d %-16s %-16s %-8d %s",
  416.            pid, comm, $parent_comm, uid, $filename);
  417.    
  418.     // Print first 3 arguments if available
  419.     $argptr = args->argv;
  420.     if ($argptr) {
  421.         $arg = str(*(char **)$argptr);
  422.         if ($arg) {
  423.             printf(" %s", $arg);
  424.            
  425.             $argptr += 8;
  426.             $arg = str(*(char **)$argptr);
  427.             if ($arg) {
  428.                 printf(" %s", $arg);
  429.                
  430.                 $argptr += 8;
  431.                 $arg = str(*(char **)$argptr);
  432.                 if ($arg) {
  433.                     printf(" %s", $arg);
  434.                 }
  435.             }
  436.         }
  437.     }
  438.    
  439.     printf("\n");
  440.    
  441.     // Track process ancestry chain for detection
  442.     @ancestry[pid] = $parent_pid;
  443.    
  444.     // Track shell spawning shells (possible lateral movement or privilege escalation)
  445.     if (($parent_comm == "bash" || $parent_comm == "sh" || $parent_comm == "dash" ||
  446.          $parent_comm == "zsh" || $parent_comm == "ksh" || $parent_comm == "fish") &&
  447.         (comm == "bash" || comm == "sh" || comm == "dash" ||
  448.          comm == "zsh" || comm == "ksh" || comm == "fish")) {
  449.         printf("WARNING: Shell spawning shell detected! %s (%d) -> %s (%d)\n",
  450.                $parent_comm, $parent_pid, comm, pid);
  451.     }
  452.    
  453.     // Track suspicious process chains (web server -> shell)
  454.     if (($parent_comm == "apache2" || $parent_comm == "nginx" || $parent_comm == "httpd") &&
  455.         (comm == "bash" || comm == "sh" || comm == "dash" || comm == "perl" ||
  456.          comm == "python" || comm == "php" || comm == "ruby")) {
  457.         printf("WARNING: Web server spawning shell! %s (%d) -> %s (%d)\n",
  458.                $parent_comm, $parent_pid, comm, pid);
  459.     }
  460.    
  461.     // Track suspicious tool execution
  462.     if (comm == "nc" || comm == "netcat" || comm == "ncat" || comm == "socat" ||
  463.         comm == "wireshark" || comm == "tcpdump" || comm == "nmap" ||
  464.         comm == "ssh-keygen" || comm == "hydra" || comm == "john" ||
  465.         comm == "hashcat" || comm == "mimikatz") {
  466.         printf("WARNING: Suspicious tool execution: %s\n", comm);
  467.     }
  468.    
  469.     // Track suspicious command line parameters
  470.     if (strstr(str(args->argv[0]), "base64") != 0 ||
  471.         strstr(str(args->argv[0]), "-e /dev/tcp/") != 0 ||
  472.         strstr(str(args->argv[0]), "wget") != 0 ||
  473.         strstr(str(args->argv[0]), "curl") != 0 ||
  474.         strstr(str(args->argv[0]), "nc -e") != 0 ||
  475.         strstr(str(args->argv[0]), "bash -i") != 0 ||
  476.         strstr(str(args->argv[0]), "bash -c") != 0) {
  477.         printf("WARNING: Suspicious command parameters detected: %s\n", str(args->argv[0]));
  478.     }
  479. }
  480.  
  481. // Detect short-lived processes (potential for "living off the land" attacks)
  482. tracepoint:sched:sched_process_exit
  483. {
  484.     $start_time = curtask->start_time / 1000000000;
  485.     $current_time = nsecs / 1000000000;
  486.     $duration = $current_time - $start_time;
  487.    
  488.     // Only alert for processes that run for less than a second
  489.     // and are not common short-lived commands
  490.     if ($duration < 1 &&
  491.         comm != "ls" && comm != "id" && comm != "ps" &&
  492.         comm != "cat" && comm != "grep" && comm != "date" &&
  493.         comm != "uname" && comm != "echo" && comm != "which") {
  494.         time("%H:%M:%S.%f ");
  495.         printf("SHORT LIVED PROCESS: %-16s (PID: %-6d, Duration: %.3f seconds)\n",
  496.                comm, pid, $duration);
  497.     }
  498. }
  499.  
  500. END
  501. {
  502.     clear(@ancestry);
  503.     printf("Process creation monitoring stopped.\n");
  504. }
  505. EOF
  506.    
  507.     # Run the BPF program
  508.     sudo bpftrace /tmp/process_monitor.bt
  509.    
  510.     # Clean up
  511.     rm -f /tmp/process_monitor.bt
  512. }
  513.  
  514. # Function to monitor privilege escalation attempts
  515. monitor_privilege_escalation() {
  516.     echo "Monitoring privilege escalation attempts using eBPF. Press Ctrl+C to stop."
  517.    
  518.     # Create temporary BPF program
  519.     cat > /tmp/privesc_monitor.bt << 'EOF'
  520. #!/usr/bin/env bpftrace
  521. #include <linux/sched.h>
  522.  
  523. BEGIN
  524. {
  525.     printf("Monitoring privilege escalation attempts...\n");
  526.     printf("%-24s %-16s %-10s %-8s %-8s %s\n", "TIME", "COMM", "PID", "UID", "EUID", "ACTIVITY");
  527. }
  528.  
  529. // Monitor privilege changes
  530. tracepoint:syscalls:sys_enter_setuid,
  531. tracepoint:syscalls:sys_enter_setreuid,
  532. tracepoint:syscalls:sys_enter_setresuid,
  533. tracepoint:syscalls:sys_enter_setfsuid
  534. {
  535.     time("%H:%M:%S.%f ");
  536.     printf("%-16s %-10d %-8d %-8d SET*UID SYSCALL\n",
  537.            comm, pid, uid, euid);
  538. }
  539.  
  540. // Monitor sudo/su executions
  541. tracepoint:syscalls:sys_enter_execve
  542. /(strncmp(str(args->filename), "/usr/bin/sudo", 13) == 0) ||
  543.  (strncmp(str(args->filename), "/bin/sudo", 9) == 0) ||
  544.  (strncmp(str(args->filename), "/usr/bin/su", 11) == 0) ||
  545.  (strncmp(str(args->filename), "/bin/su", 7) == 0) ||
  546.  (strncmp(str(args->filename), "/usr/bin/pkexec", 15) == 0) ||
  547.  (strncmp(str(args->filename), "/usr/bin/gksudo", 15) == 0)/
  548. {
  549.     time("%H:%M:%S.%f ");
  550.     printf("%-16s %-10d %-8d %-8d PRIVILEGE ESCALATION TOOL: %s",
  551.            comm, pid, uid, euid, str(args->filename));
  552.    
  553.     // Print first argument if available
  554.     $argptr = args->argv + 8; // Skip the command name
  555.     $arg = str(*(char **)$argptr);
  556.     if ($arg) {
  557.         printf(" %s", $arg);
  558.     }
  559.    
  560.     printf("\n");
  561. }
  562.  
  563. // Monitor capabilities changes
  564. tracepoint:syscalls:sys_enter_capset
  565. {
  566.     time("%H:%M:%S.%f ");
  567.     printf("%-16s %-10d %-8d %-8d CAPABILITIES CHANGE\n",
  568.            comm, pid, uid, euid);
  569. }
  570.  
  571. // Monitor SUID/SGID file executions
  572. tracepoint:syscalls:sys_enter_execve
  573. {
  574.     $filestat = curtask->fs->pwd->d_path;
  575.    
  576.     if (curtask->status < 0x10000000) { // Has SUID/SGID
  577.         time("%H:%M:%S.%f ");
  578.         printf("%-16s %-10d %-8d %-8d SUID/SGID EXECUTION: %s\n",
  579.                comm, pid, uid, euid, str(args->filename));
  580.     }
  581.    
  582.     // Check euid change during execution
  583.     if (uid != euid) {
  584.         time("%H:%M:%S.%f ");
  585.         printf("%-16s %-10d %-8d %-8d EFFECTIVE UID CHANGE during execution\n",
  586.                comm, pid, uid, euid);
  587.     }
  588. }
  589.  
  590. // Track file permission changes to set SUID/SGID
  591. tracepoint:syscalls:sys_enter_chmod,
  592. tracepoint:syscalls:sys_enter_fchmod,
  593. tracepoint:syscalls:sys_enter_fchmodat
  594. {
  595.     $mode = args->mode;
  596.    
  597.     // Check for SUID/SGID bit setting
  598.     if ($mode & 06000) {
  599.         time("%H:%M:%S.%f ");
  600.         if (probe == "tracepoint:syscalls:sys_enter_chmod") {
  601.             printf("%-16s %-10d %-8d %-8d ADDING SUID/SGID TO FILE: %s (mode:%o)\n",
  602.                    comm, pid, uid, euid, str(args->filename), $mode);
  603.         } else if (probe == "tracepoint:syscalls:sys_enter_fchmodat") {
  604.             printf("%-16s %-10d %-8d %-8d ADDING SUID/SGID TO FILE AT: %s (mode:%o)\n",
  605.                    comm, pid, uid, euid, str(args->filename), $mode);
  606.         } else {
  607.             printf("%-16s %-10d %-8d %-8d ADDING SUID/SGID TO FD: %d (mode:%o)\n",
  608.                    comm, pid, uid, euid, args->fd, $mode);
  609.         }
  610.     }
  611. }
  612.  
  613. // Monitor kernel module parameters for privilege escalation
  614. kprobe:security_kernel_module_request
  615. {
  616.     time("%H:%M:%S.%f ");
  617.     printf("%-16s %-10d %-8d %-8d KERNEL MODULE REQUEST\n",
  618.            comm, pid, uid, euid);
  619. }
  620.  
  621. // Monitor processes trying to read sensitive credential files
  622. tracepoint:syscalls:sys_enter_openat
  623. /(strncmp(str(args->filename), "/etc/passwd", 11) == 0) ||
  624.  (strncmp(str(args->filename), "/etc/shadow", 11) == 0) ||
  625.  (strncmp(str(args->filename), "/etc/sudoers", 12) == 0) ||
  626.  (strncmp(str(args->filename), "/etc/group", 10) == 0) ||
  627.  (strncmp(str(args->filename), "/proc/self/mem", 14) == 0)/
  628. {
  629.     time("%H:%M:%S.%f ");
  630.     printf("%-16s %-10d %-8d %-8d ACCESS TO SENSITIVE CREDENTIAL FILE: %s\n",
  631.            comm, pid, uid, euid, str(args->filename));
  632. }
  633.  
  634. END
  635. {
  636.     printf("Privilege escalation monitoring stopped.\n");
  637. }
  638. EOF
  639.    
  640.     # Run the BPF program
  641.     sudo bpftrace /tmp/privesc_monitor.bt
  642.    
  643.     # Clean up
  644.     rm -f /tmp/privesc_monitor.bt
  645. }
  646.  
  647. # Function to detect library injection
  648. detect_library_injection() {
  649.     echo "Detecting library injection using eBPF. Press Ctrl+C to stop."
  650.    
  651.     # Create temporary BPF program
  652.     cat > /tmp/library_injection.bt << 'EOF'
  653. #!/usr/bin/env bpftrace
  654. #include <linux/sched.h>
  655. #include <linux/fs.h>
  656.  
  657. BEGIN
  658. {
  659.     printf("Monitoring for library injection...\n");
  660.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  661. }
  662.  
  663. // Monitor dlopen calls
  664. uprobe:/usr/lib*/libdl.so*:dlopen
  665. {
  666.     $library_path = str(arg0);
  667.    
  668.     time("%H:%M:%S.%f ");
  669.     printf("%-16s %-10d %-8d DLOPEN: %s\n",
  670.            comm, pid, uid, $library_path);
  671.    
  672.     // Track suspicious library paths
  673.     if (strncmp($library_path, "/tmp/", 5) == 0 ||
  674.         strncmp($library_path, "/dev/shm/", 9) == 0 ||
  675.         strncmp($library_path, "/var/tmp/", 9) == 0 ||
  676.         strncmp($library_path, "/proc/", 6) == 0 ||
  677.         strncmp($library_path, "./", 2) == 0) {
  678.         printf("WARNING: Loading library from suspicious location: %s\n", $library_path);
  679.     }
  680.    
  681.     // Track libraries being loaded by unusual processes
  682.     if (comm != "java" && comm != "python" &&
  683.         comm != "perl" && comm != "ruby" &&
  684.         comm != "php" && comm != "node" &&
  685.         comm != "systemd" && comm != "firefox" &&
  686.         comm != "chrome" && comm != "apache2" &&
  687.         comm != "nginx") {
  688.         @unusual_loaders[comm, $library_path] = count();
  689.     }
  690. }
  691.  
  692. // Monitor mmap with PROT_EXEC
  693. tracepoint:syscalls:sys_enter_mmap
  694. /args->prot & 0x4/    // PROT_EXEC
  695. {
  696.     time("%H:%M:%S.%f ");
  697.     printf("%-16s %-10d %-8d MMAP WITH EXEC PERMISSION: size=%lu\n",
  698.            comm, pid, uid, args->len);
  699.    
  700.     // Track processes creating executable memory
  701.     @exec_mmap[comm, pid] = count();
  702.    
  703.     // Alert if a process creates many executable memory regions
  704.     if (@exec_mmap[comm, pid] > 10) {
  705.         printf("WARNING: Process creating many executable memory regions: %s (PID: %d)\n",
  706.                comm, pid);
  707.     }
  708. }
  709.  
  710. // Monitor mprotect calls that add execute permission
  711. tracepoint:syscalls:sys_enter_mprotect
  712. /args->prot & 0x4/    // PROT_EXEC
  713. {
  714.     time("%H:%M:%S.%f ");
  715.     printf("%-16s %-10d %-8d MPROTECT ADDING EXEC PERMISSION: addr=%lx size=%lu\n",
  716.            comm, pid, uid, args->addr, args->len);
  717.    
  718.     // Track processes modifying memory to be executable
  719.     @exec_mprotect[comm, pid] = count();
  720.    
  721.     // Alert if a process modifies permissions to executable many times
  722.     if (@exec_mprotect[comm, pid] > 5) {
  723.         printf("WARNING: Process frequently modifying memory to executable: %s (PID: %d)\n",
  724.                comm, pid);
  725.     }
  726. }
  727.  
  728. // Monitor process ptrace attach (could be used for code injection)
  729. tracepoint:syscalls:sys_enter_ptrace
  730. /args->request == 16/    // PTRACE_ATTACH
  731. {
  732.     time("%H:%M:%S.%f ");
  733.     printf("%-16s %-10d %-8d PTRACE ATTACH to PID %d\n",
  734.            comm, pid, uid, args->pid);
  735.    
  736.     printf("WARNING: Process using ptrace to attach to another process. Possible injection attempt.\n");
  737. }
  738.  
  739. // Monitor LD_PRELOAD environment variable in execve
  740. tracepoint:syscalls:sys_enter_execve
  741. {
  742.     $envp = args->envp;
  743.    
  744.     // Check environment variables for LD_PRELOAD
  745.     while ($envp != 0 && $envp != NULL) {
  746.         $env = str(*(char **)$envp);
  747.         if ($env != 0 && $env != NULL) {
  748.             if (strncmp($env, "LD_PRELOAD=", 11) == 0) {
  749.                 time("%H:%M:%S.%f ");
  750.                 printf("%-16s %-10d %-8d LD_PRELOAD DETECTED: %s\n",
  751.                        comm, pid, uid, $env);
  752.                 printf("WARNING: Process using LD_PRELOAD. Possible library injection.\n");
  753.             }
  754.         }
  755.         $envp += 8;  // Move to the next env var (64-bit pointer size)
  756.     }
  757. }
  758.  
  759. // Track creation of shared objects in suspicious locations
  760. tracepoint:syscalls:sys_enter_openat
  761. /(args->flags & 0x40) || (args->flags & 0x241)/    // O_CREAT or combination of O_WRONLY|O_CREAT|O_TRUNC
  762. {
  763.     $filename = str(args->filename);
  764.    
  765.     if (strstr($filename, ".so") != 0) {
  766.         time("%H:%M:%S.%f ");
  767.         printf("%-16s %-10d %-8d CREATING SHARED OBJECT: %s\n",
  768.                comm, pid, uid, $filename);
  769.        
  770.         if (strncmp($filename, "/tmp/", 5) == 0 ||
  771.             strncmp($filename, "/dev/shm/", 9) == 0 ||
  772.             strncmp($filename, "/var/tmp/", 9) == 0) {
  773.             printf("WARNING: Creating shared object in suspicious location.\n");
  774.         }
  775.     }
  776. }
  777.  
  778. // Report unusual combinations
  779. interval:s:10
  780. {
  781.     printf("\n=== Unusual Library Loading Summary (10-sec interval) ===\n");
  782.     print(@unusual_loaders);
  783.     clear(@unusual_loaders);
  784.    
  785.     printf("\n=== Executable Memory Activity Summary (10-sec interval) ===\n");
  786.     printf("Processes creating many executable memory regions:\n");
  787.     print(@exec_mmap);
  788.     clear(@exec_mmap);
  789.    
  790.     printf("Processes modifying memory to be executable:\n");
  791.     print(@exec_mprotect);
  792.     clear(@exec_mprotect);
  793.     printf("=======================================================\n\n");
  794. }
  795.  
  796. END
  797. {
  798.     clear(@unusual_loaders);
  799.     clear(@exec_mmap);
  800.     clear(@exec_mprotect);
  801.     printf("Library injection monitoring stopped.\n");
  802. }
  803. EOF
  804.    
  805.     # Run the BPF program
  806.     sudo bpftrace /tmp/library_injection.bt
  807.    
  808.     # Clean up
  809.     rm -f /tmp/library_injection.bt
  810. }
  811.  
  812. # Function to monitor system call anomalies
  813. monitor_syscall_anomalies() {
  814.     echo "Monitoring system call anomalies using eBPF. Press Ctrl+C to stop."
  815.    
  816.     # Create temporary BPF program
  817.     cat > /tmp/syscall_monitor.bt << 'EOF'
  818. #!/usr/bin/env bpftrace
  819. #include <linux/sched.h>
  820.  
  821. BEGIN
  822. {
  823.     printf("Monitoring system call anomalies...\n");
  824.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "SYSCALL");
  825.    
  826.     // Initialize rare syscall list
  827.     @rare_syscalls[270] = "rare"; // pivot_root
  828.     @rare_syscalls[124] = "rare"; // adjtimex
  829.     @rare_syscalls[148] = "rare"; // uselib
  830.     @rare_syscalls[203] = "rare"; // swapon
  831.     @rare_syscalls[156] = "rare"; // swapoff
  832.     @rare_syscalls[157] = "rare"; // sysctl
  833.     @rare_syscalls[135] = "rare"; // sysfs
  834.     @rare_syscalls[142] = "rare"; // quotactl
  835.     @rare_syscalls[186] = "rare"; // ioperm
  836.     @rare_syscalls[153] = "rare"; // iopl
  837.     @rare_syscalls[94] = "rare";  // lstat
  838.     @rare_syscalls[80] = "rare";  // chroot
  839. }
  840.  
  841. // Track process system call patterns
  842. tracepoint:raw_syscalls:sys_enter
  843. {
  844.     $syscall = args->id;
  845.    
  846.     // Increment syscall count for the process
  847.     @process_syscalls[pid, comm, $syscall] = count();
  848.    
  849.     // Detect rare or suspicious syscalls
  850.     if (@rare_syscalls[$syscall]) {
  851.         time("%H:%M:%S.%f ");
  852.         printf("%-16s %-10d %-8d RARE SYSCALL: %d\n",
  853.                comm, pid, uid, $syscall);
  854.     }
  855.    
  856.     // Detect suspicious sequences
  857.     // First, store the current syscall
  858.     @last_syscall[pid] = $syscall;
  859. }
  860.  
  861. // Track process system call exit
  862. tracepoint:raw_syscalls:sys_exit
  863. {
  864.     $syscall = @last_syscall[pid];
  865.     $ret = args->ret;
  866.    
  867.     // Track failed sensitive syscalls
  868.     if ($ret < 0 &&
  869.         ($syscall == 59 ||   // execve
  870.          $syscall == 62 ||   // kill
  871.          $syscall == 57 ||   // fork
  872.          $syscall == 56 ||   // clone
  873.          $syscall == 105 ||  // setuid
  874.          $syscall == 106 ||  // setgid
  875.          $syscall == 2  ||   // open
  876.          $syscall == 257 ||  // openat
  877.          $syscall == 80)) {  // chroot
  878.        
  879.         time("%H:%M:%S.%f ");
  880.         printf("%-16s %-10d %-8d FAILED SENSITIVE SYSCALL: %d (ret: %d)\n",
  881.                comm, pid, uid, $syscall, $ret);
  882.        
  883.         // Increment failed sensitive syscall count
  884.         @failed_sensitive[pid, comm, $syscall] = count();
  885.        
  886.         // Alert on multiple failures (potential brute force)
  887.         if (@failed_sensitive[pid, comm, $syscall] > 3) {
  888.             printf("WARNING: Multiple failed sensitive syscalls - possible brute force: %s (PID: %d)\n",
  889.                    comm, pid);
  890.         }
  891.     }
  892. }
  893.  
  894. // Detect processes with unusual syscall patterns
  895. interval:s:10
  896. {
  897.     printf("\n=== Syscall Pattern Analysis (10-sec interval) ===\n");
  898.    
  899.     // Rare combinations of syscalls that could indicate unusual behavior
  900.     $open_count = @process_syscalls[pid, comm, 2] + @process_syscalls[pid, comm, 257]; // open/openat
  901.     $exec_count = @process_syscalls[pid, comm, 59]; // execve
  902.     $socket_count = @process_syscalls[pid, comm, 41] + @process_syscalls[pid, comm, 42] +
  903.                   @process_syscalls[pid, comm, 43] + @process_syscalls[pid, comm, 44] +
  904.                   @process_syscalls[pid, comm, 45]; // socket ops
  905.    
  906.     // Check for unusual patterns
  907.     if ($open_count > 100 && $exec_count > 5) {
  908.         printf("WARNING: Process with high file access and execution: %s (PID: %d)\n",
  909.                comm, pid);
  910.     }
  911.    
  912.     if ($socket_count > 20 && $open_count > 50) {
  913.         printf("WARNING: Process with high network and file activity: %s (PID: %d)\n",
  914.                comm, pid);
  915.     }
  916.    
  917.     printf("Top 10 processes by syscall volume:\n");
  918.     print(@process_syscall_volume);
  919.    
  920.     printf("Failed sensitive syscalls:\n");
  921.     print(@failed_sensitive);
  922.     clear(@failed_sensitive);
  923.    
  924.     printf("==================================================\n\n");
  925. }
  926.  
  927. END
  928. {
  929.     clear(@rare_syscalls);
  930.     clear(@process_syscalls);
  931.     clear(@last_syscall);
  932.     clear(@failed_sensitive);
  933.     printf("System call anomaly monitoring stopped.\n");
  934. }
  935. EOF
  936.    
  937.     # Run the BPF program
  938.     sudo bpftrace /tmp/syscall_monitor.bt
  939.    
  940.     # Clean up
  941.     rm -f /tmp/syscall_monitor.bt
  942. }
  943.  
  944. # Function to detect container escape attempts
  945. detect_container_escape() {
  946.     echo "Detecting container escape attempts using eBPF. Press Ctrl+C to stop."
  947.    
  948.     # Create temporary BPF program
  949.     cat > /tmp/container_escape.bt << 'EOF'
  950. #!/usr/bin/env bpftrace
  951. #include <linux/sched.h>
  952. #include <linux/nsproxy.h>
  953. #include <linux/mount.h>
  954.  
  955. BEGIN
  956. {
  957.     printf("Monitoring for container escape attempts...\n");
  958.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  959. }
  960.  
  961. // Track mount namespace changes
  962. tracepoint:syscalls:sys_enter_mount
  963. {
  964.     time("%H:%M:%S.%f ");
  965.     printf("%-16s %-10d %-8d MOUNT: %s -> %s (flags: %d)\n",
  966.            comm, pid, uid, str(args->source), str(args->target), args->flags);
  967.    
  968.     // Detect mounting host devices or sensitive host directories
  969.     if (strncmp(str(args->source), "/dev/", 5) == 0 ||
  970.         strncmp(str(args->source), "/proc/", 6) == 0 ||
  971.         strncmp(str(args->source), "/sys/", 5) == 0) {
  972.         printf("WARNING: Possible container escape attempt - mounting host device: %s\n",
  973.                str(args->source));
  974.     }
  975. }
  976.  
  977. // Track unshare/clone with namespace changes
  978. tracepoint:syscalls:sys_enter_unshare,
  979. tracepoint:syscalls:sys_enter_clone
  980. {
  981.     $flags = args->flags;
  982.    
  983.     // CLONE_NEWNS, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWPID, CLONE_NEWNET, CLONE_NEWUSER
  984.     if ($flags & 0x00020000 || $flags & 0x04000000 || $flags & 0x08000000 ||
  985.         $flags & 0x20000000 || $flags & 0x40000000 || $flags & 0x10000000) {
  986.         time("%H:%M:%S.%f ");
  987.         printf("%-16s %-10d %-8d NAMESPACE CHANGE: flags=0x%lx\n",
  988.                comm, pid, uid, $flags);
  989.     }
  990. }
  991.  
  992. // Track setns syscall (changing namespaces)
  993. tracepoint:syscalls:sys_enter_setns
  994. {
  995.     time("%H:%M:%S.%f ");
  996.     printf("%-16s %-10d %-8d SETNS: fd=%d, type=0x%x\n",
  997.            comm, pid, uid, args->fd, args->type);
  998.     printf("WARNING: Process changing namespace. Possible container escape attempt.\n");
  999. }
  1000.  
  1001. // Track pivot_root (often used in container escapes)
  1002. tracepoint:syscalls:sys_enter_pivot_root
  1003. {
  1004.     time("%H:%M:%S.%f ");
  1005.     printf("%-16s %-10d %-8d PIVOT_ROOT: new=%s, old=%s\n",
  1006.            comm, pid, uid, str(args->new_root), str(args->put_old));
  1007.     printf("WARNING: pivot_root syscall detected. Possible container escape attempt.\n");
  1008. }
  1009.  
  1010. // Track container breakout tools
  1011. tracepoint:syscalls:sys_enter_execve
  1012. {
  1013.     $filename = str(args->filename);
  1014.    
  1015.     if (strncmp($filename, "/proc/self/exe", 14) == 0 ||
  1016.         strstr($filename, "docker") ||
  1017.         strstr($filename, "runc") ||
  1018.         strstr($filename, "containerd") ||
  1019.         strstr($filename, "ctr")) {
  1020.         time("%H:%M:%S.%f ");
  1021.         printf("%-16s %-10d %-8d CONTAINER TOOL EXECUTION: %s\n",
  1022.                comm, pid, uid, $filename);
  1023.     }
  1024.    
  1025.     // Check for programs that are often used in container escapes
  1026.     if (strstr($filename, "nsenter") ||
  1027.         strstr($filename, "unshare") ||
  1028.         strstr($filename, "capsh")) {
  1029.         time("%H:%M:%S.%f ");
  1030.         printf("%-16s %-10d %-8d SUSPICIOUS CONTAINER TOOL: %s\n",
  1031.                comm, pid, uid, $filename);
  1032.         printf("WARNING: Process using tools commonly associated with container escapes.\n");
  1033.     }
  1034. }
  1035.  
  1036. // Track attempts to access container engine socket
  1037. tracepoint:syscalls:sys_enter_connect
  1038. {
  1039.     $sockaddr = (struct sockaddr_un *)args->uservaddr;
  1040.    
  1041.     if ($sockaddr->sa_family == AF_UNIX) {
  1042.         $path = str($sockaddr->sun_path);
  1043.         if (strstr($path, "/var/run/docker.sock") ||
  1044.             strstr($path, "/run/docker.sock") ||
  1045.             strstr($path, "/run/containerd/") ||
  1046.             strstr($path, "/var/run/crio/")) {
  1047.             time("%H:%M:%S.%f ");
  1048.             printf("%-16s %-10d %-8d CONTAINER SOCKET ACCESS: %s\n",
  1049.                    comm, pid, uid, $path);
  1050.             printf("WARNING: Process attempting to access container engine socket.\n");
  1051.         }
  1052.     }
  1053. }
  1054.  
  1055. // Track accesses to cgroup files which could be used for container escapes
  1056. tracepoint:syscalls:sys_enter_openat
  1057. {
  1058.     $filename = str(args->filename);
  1059.    
  1060.     if (strncmp($filename, "/proc/self/cgroup", 17) == 0 ||
  1061.         strncmp($filename, "/proc/self/mountinfo", 20) == 0 ||
  1062.         strncmp($filename, "/proc/*/cgroup", 14) == 0 ||
  1063.         strncmp($filename, "/sys/fs/cgroup/", 15) == 0) {
  1064.         time("%H:%M:%S.%f ");
  1065.         printf("%-16s %-10d %-8d CGROUP ACCESS: %s\n",
  1066.                comm, pid, uid, $filename);
  1067.     }
  1068. }
  1069.  
  1070. // Track capability changes which could indicate privilege escalation within container
  1071. tracepoint:syscalls:sys_enter_capset
  1072. {
  1073.     time("%H:%M:%S.%f ");
  1074.     printf("%-16s %-10d %-8d CAPABILITY CHANGE\n", comm, pid, uid);
  1075.    
  1076.     if (uid != 0) {
  1077.         printf("WARNING: Non-root user attempting to change capabilities.\n");
  1078.     }
  1079. }
  1080.  
  1081. // Track ptrace operations that could be used for container escapes
  1082. tracepoint:syscalls:sys_enter_ptrace
  1083. {
  1084.     time("%H:%M:%S.%f ");
  1085.     printf("%-16s %-10d %-8d PTRACE: request=%ld, pid=%d\n",
  1086.            comm, pid, uid, args->request, args->pid);
  1087.    
  1088.     if (args->request == 12 || args->request == 13) { // PTRACE_GETREGS, PTRACE_SETREGS
  1089.         printf("WARNING: Process attempting to read/modify registers of another process.\n");
  1090.     }
  1091. }
  1092.  
  1093. END
  1094. {
  1095.     printf("Container escape monitoring stopped.\n");
  1096. }
  1097. EOF
  1098.    
  1099.     # Run the BPF program
  1100.     sudo bpftrace /tmp/container_escape.bt
  1101.    
  1102.     # Clean up
  1103.     rm -f /tmp/container_escape.bt
  1104. }
  1105.  
  1106. # Function to monitor suspicious kernel module loading
  1107. monitor_kernel_modules() {
  1108.     echo "Monitoring suspicious kernel module loading using eBPF. Press Ctrl+C to stop."
  1109.    
  1110.     # Create temporary BPF program
  1111.     cat > /tmp/module_monitor.bt << 'EOF'
  1112. #!/usr/bin/env bpftrace
  1113. #include <linux/sched.h>
  1114. #include <linux/module.h>
  1115.  
  1116. BEGIN
  1117. {
  1118.     printf("Monitoring suspicious kernel module loading...\n");
  1119.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  1120. }
  1121.  
  1122. // Track init_module and finit_module syscalls
  1123. tracepoint:syscalls:sys_enter_init_module
  1124. {
  1125.     time("%H:%M:%S.%f ");
  1126.     printf("%-16s %-10d %-8d LOAD KERNEL MODULE: size=%lu\n",
  1127.            comm, pid, uid, args->len);
  1128.    
  1129.     // Non-root users shouldn't be loading modules
  1130.     if (uid != 0) {
  1131.         printf("WARNING: Non-root user attempting to load kernel module!\n");
  1132.     }
  1133. }
  1134.  
  1135. tracepoint:syscalls:sys_enter_finit_module
  1136. {
  1137.     time("%H:%M:%S.%f ");
  1138.     printf("%-16s %-10d %-8d LOAD KERNEL MODULE via fd: %d flags: %s\n",
  1139.            comm, pid, uid, args->fd, str(args->uargs));
  1140.    
  1141.     // Non-root users shouldn't be loading modules
  1142.     if (uid != 0) {
  1143.         printf("WARNING: Non-root user attempting to load kernel module!\n");
  1144.     }
  1145. }
  1146.  
  1147. // Track module deletion
  1148. tracepoint:syscalls:sys_enter_delete_module
  1149. {
  1150.     time("%H:%M:%S.%f ");
  1151.     printf("%-16s %-10d %-8d DELETE KERNEL MODULE: %s flags: %d\n",
  1152.            comm, pid, uid, str(args->name), args->flags);
  1153.    
  1154.     // Non-root users shouldn't be deleting modules
  1155.     if (uid != 0) {
  1156.         printf("WARNING: Non-root user attempting to delete kernel module!\n");
  1157.     }
  1158. }
  1159.  
  1160. // Track kmod executions (often used to load modules)
  1161. tracepoint:syscalls:sys_enter_execve
  1162. /(strncmp(str(args->filename), "/sbin/insmod", 13) == 0) ||
  1163.  (strncmp(str(args->filename), "/sbin/modprobe", 15) == 0) ||
  1164.  (strncmp(str(args->filename), "/bin/kmod", 10) == 0)/
  1165. {
  1166.     time("%H:%M:%S.%f ");
  1167.     printf("%-16s %-10d %-8d KERNEL MODULE TOOL: %s",
  1168.            comm, pid, uid, str(args->filename));
  1169.    
  1170.     // Print first argument if available
  1171.     $argptr = args->argv + 8; // Skip the command name
  1172.     $arg = str(*(char **)$argptr);
  1173.     if ($arg) {
  1174.         printf(" %s", $arg);
  1175.     }
  1176.    
  1177.     printf("\n");
  1178.    
  1179.     // Check for module names that might be suspicious
  1180.     if (strstr($arg, "hide") ||
  1181.         strstr($arg, "rootkit") ||
  1182.         strstr($arg, "intercept") ||
  1183.         strstr($arg, "hook") ||
  1184.         strstr($arg, "stealth")) {
  1185.         printf("WARNING: Loading module with suspicious name: %s\n", $arg);
  1186.     }
  1187. }
  1188.  
  1189. // Track accesses to the module-related files and directories
  1190. tracepoint:syscalls:sys_enter_openat
  1191. /(strncmp(str(args->filename), "/lib/modules/", 13) == 0) ||
  1192.  (strncmp(str(args->filename), "/sys/module/", 12) == 0)/
  1193. {
  1194.     time("%H:%M:%S.%f ");
  1195.     printf("%-16s %-10d %-8d MODULE FILE ACCESS: %s\n",
  1196.            comm, pid, uid, str(args->filename));
  1197. }
  1198.  
  1199. // Monitor direct /dev/mem and /dev/kmem access (could be used for module injection)
  1200. tracepoint:syscalls:sys_enter_open,
  1201. tracepoint:syscalls:sys_enter_openat
  1202. /(strncmp(str(args->filename), "/dev/mem", 8) == 0) ||
  1203.  (strncmp(str(args->filename), "/dev/kmem", 9) == 0) ||
  1204.  (strncmp(str(args->filename), "/dev/port", 9) == 0)/
  1205. {
  1206.     time("%H:%M:%S.%f ");
  1207.     printf("%-16s %-10d %-8d DIRECT MEMORY ACCESS: %s\n",
  1208.            comm, pid, uid, str(args->filename));
  1209.     printf("WARNING: Process attempting direct memory access. Possible module injection technique.\n");
  1210. }
  1211.  
  1212. // Track suspicious file creation in module directories
  1213. tracepoint:syscalls:sys_enter_creat,
  1214. tracepoint:syscalls:sys_enter_open,
  1215. tracepoint:syscalls:sys_enter_openat
  1216. /((args->flags & 0x40) || (args->flags & 0x241)) && // O_CREAT or O_WRONLY|O_CREAT|O_TRUNC
  1217.  (strncmp(str(args->filename), "/lib/modules/", 13) == 0)/
  1218. {
  1219.     time("%H:%M:%S.%f ");
  1220.     printf("%-16s %-10d %-8d CREATING FILE IN MODULE DIRECTORY: %s\n",
  1221.            comm, pid, uid, str(args->filename));
  1222.     printf("WARNING: Creating file in kernel module directory.\n");
  1223. }
  1224.  
  1225. // Track access to kernel symbols (often used by rootkits)
  1226. tracepoint:syscalls:sys_enter_open,
  1227. tracepoint:syscalls:sys_enter_openat
  1228. /(strncmp(str(args->filename), "/proc/kallsyms", 14) == 0) ||
  1229.  (strncmp(str(args->filename), "/boot/System.map", 16) == 0)/
  1230. {
  1231.     time("%H:%M:%S.%f ");
  1232.     printf("%-16s %-10d %-8d KERNEL SYMBOL ACCESS: %s\n",
  1233.            comm, pid, uid, str(args->filename));
  1234. }
  1235.  
  1236. // Monitor for module related sysctls
  1237. tracepoint:syscalls:sys_enter_sysctl
  1238. {
  1239.     $name = args->name;
  1240.     if ($name != 0 && $name != NULL) {
  1241.         if (strncmp(str($name), "kernel.modules_disabled", 23) == 0 ||
  1242.             strncmp(str($name), "kernel.tainted", 15) == 0) {
  1243.             time("%H:%M:%S.%f ");
  1244.             printf("%-16s %-10d %-8d MODULE SYSCTL ACCESS: %s\n",
  1245.                    comm, pid, uid, str($name));
  1246.         }
  1247.     }
  1248. }
  1249.  
  1250. END
  1251. {
  1252.     printf("Kernel module monitoring stopped.\n");
  1253. }
  1254. EOF
  1255.    
  1256.     # Run the BPF program
  1257.     sudo bpftrace /tmp/module_monitor.bt
  1258.    
  1259.     # Clean up
  1260.     rm -f /tmp/module_monitor.bt
  1261. }
  1262.  
  1263. # Function to track file execution flow
  1264. track_file_execution() {
  1265.     echo "Tracking file execution flow using eBPF. Press Ctrl+C to stop."
  1266.    
  1267.     # Create temporary BPF program
  1268.     cat > /tmp/execution_flow.bt << 'EOF'
  1269. #!/usr/bin/env bpftrace
  1270. #include <linux/sched.h>
  1271. #include <linux/fs.h>
  1272.  
  1273. BEGIN
  1274. {
  1275.     printf("Tracking file execution flow...\n");
  1276.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  1277. }
  1278.  
  1279. // Track execve syscalls for program execution
  1280. tracepoint:syscalls:sys_enter_execve
  1281. {
  1282.     $filename = str(args->filename);
  1283.     $parent_pid = curtask->parent->pid;
  1284.     $parent_comm = curtask->parent->comm;
  1285.    
  1286.     time("%H:%M:%S.%f ");
  1287.     printf("%-16s %-10d %-8d EXEC: %s (Parent: %s [%d])\n",
  1288.            comm, pid, uid, $filename, $parent_comm, $parent_pid);
  1289.    
  1290.     // Track execution chain
  1291.     @exec_chain[pid] = $parent_pid;
  1292.     @exec_program[pid] = $filename;
  1293.    
  1294.     // Check for suspicious execution patterns
  1295.    
  1296.     // Web server executing shells
  1297.     if (($parent_comm == "apache" || $parent_comm == "apache2" ||
  1298.          $parent_comm == "httpd" || $parent_comm == "nginx" ||
  1299.          $parent_comm == "php-fpm" || $parent_comm == "uwsgi") &&
  1300.         (strstr($filename, "/bin/sh") || strstr($filename, "/bin/bash") ||
  1301.          strstr($filename, "/bin/dash") || strstr($filename, "/usr/bin/perl") ||
  1302.          strstr($filename, "/usr/bin/python"))) {
  1303.         printf("WARNING: Web server executing shell - possible web compromise!\n");
  1304.     }
  1305.    
  1306.     // Database server executing shells
  1307.     if (($parent_comm == "mysqld" || $parent_comm == "postgres" ||
  1308.          $parent_comm == "oracle" || $parent_comm == "mongodb") &&
  1309.         (strstr($filename, "/bin/sh") || strstr($filename, "/bin/bash") ||
  1310.          strstr($filename, "/bin/dash"))) {
  1311.         printf("WARNING: Database server executing shell - possible SQL injection!\n");
  1312.     }
  1313.    
  1314.     // Suspicious execution from temporary directories
  1315.     if (strncmp($filename, "/tmp/", 5) == 0 ||
  1316.         strncmp($filename, "/var/tmp/", 9) == 0 ||
  1317.         strncmp($filename, "/dev/shm/", 9) == 0) {
  1318.         printf("WARNING: Executing file from temporary directory: %s\n", $filename);
  1319.     }
  1320.    
  1321.     // Suspicious command line tools
  1322.     if (strstr($filename, "/usr/bin/curl") ||
  1323.         strstr($filename, "/usr/bin/wget") ||
  1324.         strstr($filename, "/usr/bin/nc") ||
  1325.         strstr($filename, "/bin/nc") ||
  1326.         strstr($filename, "/usr/bin/netcat") ||
  1327.         strstr($filename, "/usr/bin/ncat")) {
  1328.         // Print first 3 arguments if available
  1329.         printf("Command arguments: ");
  1330.         $argptr = args->argv;
  1331.         if ($argptr) {
  1332.             $argptr += 8; // Skip the command name
  1333.             for ($i = 0; $i < 3; $i++) {
  1334.                 $arg = str(*(char **)$argptr);
  1335.                 if ($arg) {
  1336.                     printf("%s ", $arg);
  1337.                     $argptr += 8;
  1338.                 } else {
  1339.                     break;
  1340.                 }
  1341.             }
  1342.             printf("\n");
  1343.         }
  1344.     }
  1345. }
  1346.  
  1347. // Track execution of scripts
  1348. tracepoint:syscalls:sys_enter_execve
  1349. /(strstr(str(args->filename), ".sh") ||
  1350.   strstr(str(args->filename), ".py") ||
  1351.   strstr(str(args->filename), ".pl") ||
  1352.   strstr(str(args->filename), ".rb") ||
  1353.   strstr(str(args->filename), ".php"))/
  1354. {
  1355.     $filename = str(args->filename);
  1356.    
  1357.     time("%H:%M:%S.%f ");
  1358.     printf("%-16s %-10d %-8d SCRIPT EXEC: %s\n",
  1359.            comm, pid, uid, $filename);
  1360.    
  1361.     // Open and read the beginning of the script to detect shebang
  1362.     // This is a simplification; in real eBPF code, you would need
  1363.     // a more complex approach to read file contents
  1364. }
  1365.  
  1366. // Track chmod +x operations (making files executable)
  1367. tracepoint:syscalls:sys_enter_chmod
  1368. {
  1369.     $filename = str(args->filename);
  1370.     $mode = args->mode;
  1371.    
  1372.     // Check if executable bits are being set
  1373.     if ($mode & 0111) {
  1374.         time("%H:%M:%S.%f ");
  1375.         printf("%-16s %-10d %-8d CHMOD +x: %s (mode: %o)\n",
  1376.                comm, pid, uid, $filename, $mode);
  1377.        
  1378.         // Check for suspicious locations
  1379.         if (strncmp($filename, "/tmp/", 5) == 0 ||
  1380.             strncmp($filename, "/var/tmp/", 9) == 0 ||
  1381.             strncmp($filename, "/dev/shm/", 9) == 0) {
  1382.             printf("WARNING: Making file executable in suspicious location: %s\n", $filename);
  1383.         }
  1384.     }
  1385. }
  1386.  
  1387. // Track execution exit and build execution chains
  1388. tracepoint:sched:sched_process_exit
  1389. /@exec_program[pid]/
  1390. {
  1391.     $parent_pid = @exec_chain[pid];
  1392.     $program = @exec_program[pid];
  1393.    
  1394.     // Track short-lived programs
  1395.     $duration = (nsecs - curtask->start_time) / 1000000; // ms
  1396.     if ($duration < 100) { // Less than 100ms
  1397.         time("%H:%M:%S.%f ");
  1398.         printf("%-16s %-10d %-8d SHORT-LIVED EXECUTION: %s (Duration: %d ms)\n",
  1399.                comm, pid, uid, $program, $duration);
  1400.     }
  1401.    
  1402.     // Clean up our tracking
  1403.     delete(@exec_chain[pid]);
  1404.     delete(@exec_program[pid]);
  1405. }
  1406.  
  1407. // Periodically report on execution chains
  1408. interval:s:30
  1409. {
  1410.     printf("\n=== Execution Chain Summary (30-sec interval) ===\n");
  1411.     printf("Active execution chains (PID -> Parent PID):\n");
  1412.     print(@exec_chain);
  1413.     printf("===============================================\n\n");
  1414. }
  1415.  
  1416. END
  1417. {
  1418.     clear(@exec_chain);
  1419.     clear(@exec_program);
  1420.     printf("Execution flow tracking stopped.\n");
  1421. }
  1422. EOF
  1423.    
  1424.     # Run the BPF program
  1425.     sudo bpftrace /tmp/execution_flow.bt
  1426.    
  1427.     # Clean up
  1428.     rm -f /tmp/execution_flow.bt
  1429. }
  1430.  
  1431. # Function to monitor suspicious memory access patterns
  1432. monitor_memory_patterns() {
  1433.     echo "Monitoring suspicious memory access patterns using eBPF. Press Ctrl+C to stop."
  1434.    
  1435.     # Create temporary BPF program
  1436.     cat > /tmp/memory_monitor.bt << 'EOF'
  1437. #!/usr/bin/env bpftrace
  1438. #include <linux/sched.h>
  1439.  
  1440. BEGIN
  1441. {
  1442.     printf("Monitoring suspicious memory access patterns...\n");
  1443.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  1444. }
  1445.  
  1446. // Track memory mapping operations with execute permission
  1447. tracepoint:syscalls:sys_enter_mmap
  1448. /args->prot & 0x4/    // PROT_EXEC
  1449. {
  1450.     time("%H:%M:%S.%f ");
  1451.     printf("%-16s %-10d %-8d MMAP WITH EXEC PERMISSION: size=%lu\n",
  1452.            comm, pid, uid, args->len);
  1453.    
  1454.     // Track anonymous executable mappings (no file descriptor)
  1455.     if (args->fd == -1) {
  1456.         printf("WARNING: Anonymous executable memory mapping - possible shellcode injection\n");
  1457.     }
  1458.    
  1459.     // Track processes creating many executable memory regions
  1460.     @exec_mmap[comm, pid] = count();
  1461. }
  1462.  
  1463. // Track memory protection changes that add execute permission
  1464. tracepoint:syscalls:sys_enter_mprotect
  1465. /args->prot & 0x4/    // PROT_EXEC
  1466. {
  1467.     time("%H:%M:%S.%f ");
  1468.     printf("%-16s %-10d %-8d MPROTECT ADDING EXEC PERMISSION: addr=%lx size=%lu\n",
  1469.            comm, pid, uid, args->addr, args->len);
  1470.    
  1471.     // Track processes modifying permissions to make memory executable
  1472.     @exec_mprotect[comm, pid] = count();
  1473.    
  1474.     // Alert on modifications of large memory regions
  1475.     if (args->len > 1048576) { // 1MB
  1476.         printf("WARNING: Large memory region made executable - possible code injection\n");
  1477.     }
  1478. }
  1479.  
  1480. // Track memory mapping from file descriptors (loading shared libraries)
  1481. tracepoint:syscalls:sys_enter_mmap
  1482. /args->fd >= 0/
  1483. {
  1484.     // We would track file mappings here
  1485.     // This would require correlating fd with file paths
  1486.     // Full implementation would need to track open() calls and store fd->path mapping
  1487. }
  1488.  
  1489. // Track process memory writing
  1490. tracepoint:syscalls:sys_enter_process_vm_writev
  1491. {
  1492.     time("%H:%M:%S.%f ");
  1493.     printf("%-16s %-10d %-8d PROCESS_VM_WRITEV: pid=%d\n",
  1494.            comm, pid, uid, args->pid);
  1495.     printf("WARNING: Process writing to another process memory - possible code injection\n");
  1496. }
  1497.  
  1498. // Track access to /proc/pid/mem (direct process memory access)
  1499. tracepoint:syscalls:sys_enter_open,
  1500. tracepoint:syscalls:sys_enter_openat
  1501. {
  1502.     $filename = str(args->filename);
  1503.    
  1504.     if (strstr($filename, "/proc/") && strstr($filename, "/mem")) {
  1505.         time("%H:%M:%S.%f ");
  1506.         printf("%-16s %-10d %-8d DIRECT PROCESS MEMORY ACCESS: %s\n",
  1507.                comm, pid, uid, $filename);
  1508.         printf("WARNING: Process accessing another process memory directly\n");
  1509.     }
  1510. }
  1511.  
  1512. // Track ptrace operations that could be used for memory manipulation
  1513. tracepoint:syscalls:sys_enter_ptrace
  1514. /args->request == 4 || args->request == 5/  // PTRACE_POKETEXT, PTRACE_POKEDATA
  1515. {
  1516.     time("%H:%M:%S.%f ");
  1517.     printf("%-16s %-10d %-8d PTRACE MEMORY WRITE: pid=%d\n",
  1518.            comm, pid, uid, args->pid);
  1519.     printf("WARNING: Process writing to another process memory via ptrace\n");
  1520. }
  1521.  
  1522. // Track suspicious msync patterns (flushing memory modifications to disk)
  1523. tracepoint:syscalls:sys_enter_msync
  1524. {
  1525.     time("%H:%M:%S.%f ");
  1526.     printf("%-16s %-10d %-8d MSYNC: addr=%lx len=%lu flags=%d\n",
  1527.            comm, pid, uid, args->start, args->len, args->flags);
  1528. }
  1529.  
  1530. // Track processes consuming high memory
  1531. tracepoint:syscalls:sys_enter_brk,
  1532. tracepoint:syscalls:sys_enter_mmap
  1533. {
  1534.     @mem_ops[pid, comm] = count();
  1535. }
  1536.  
  1537. // Report on memory patterns periodically
  1538. interval:s:10
  1539. {
  1540.     printf("\n=== Memory Access Pattern Summary (10-sec interval) ===\n");
  1541.    
  1542.     printf("Processes creating executable memory regions:\n");
  1543.     print(@exec_mmap);
  1544.    
  1545.     printf("\nProcesses modifying memory to be executable:\n");
  1546.     print(@exec_mprotect);
  1547.    
  1548.     printf("\nProcesses with high memory allocation activity:\n");
  1549.     print(@mem_ops);
  1550.    
  1551.     printf("======================================================\n\n");
  1552.    
  1553.     // Alert on processes with both high mmap and mprotect counts
  1554.     $mmap_threshold = 5;
  1555.     $mprotect_threshold = 3;
  1556.    
  1557.     if (@exec_mmap[comm, pid] > $mmap_threshold && @exec_mprotect[comm, pid] > $mprotect_threshold) {
  1558.         printf("ALERT: Process %s (%d) shows patterns consistent with shellcode injection!\n",
  1559.                comm, pid);
  1560.     }
  1561.    
  1562.     // Clear counters after reporting
  1563.     clear(@mem_ops);
  1564. }
  1565.  
  1566. END
  1567. {
  1568.     clear(@exec_mmap);
  1569.     clear(@exec_mprotect);
  1570.     clear(@mem_ops);
  1571.     printf("Memory pattern monitoring stopped.\n");
  1572. }
  1573. EOF
  1574.    
  1575.     # Run the BPF program
  1576.     sudo bpftrace /tmp/memory_monitor.bt
  1577.    
  1578.     # Clean up
  1579.     rm -f /tmp/memory_monitor.bt
  1580. }
  1581.  
  1582. # Function to track command execution
  1583. track_command_execution() {
  1584.     echo "Tracking command execution using eBPF. Press Ctrl+C to stop."
  1585.    
  1586.     # Create temporary BPF program
  1587.     cat > /tmp/command_monitor.bt << 'EOF'
  1588. #!/usr/bin/env bpftrace
  1589. #include <linux/sched.h>
  1590.  
  1591. BEGIN
  1592. {
  1593.     printf("Tracking command execution...\n");
  1594.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "COMMAND");
  1595. }
  1596.  
  1597. // Track execve syscalls for command execution
  1598. tracepoint:syscalls:sys_enter_execve
  1599. {
  1600.     $filename = str(args->filename);
  1601.     $parent_pid = curtask->parent->pid;
  1602.     $parent_comm = curtask->parent->comm;
  1603.    
  1604.     time("%H:%M:%S.%f ");
  1605.     printf("%-16s %-10d %-8d EXEC: %s",
  1606.            comm, pid, uid, $filename);
  1607.    
  1608.     // Print command line arguments
  1609.     $argptr = args->argv;
  1610.     printf(" ARGS: ");
  1611.     $count = 0;
  1612.     if ($argptr) {
  1613.         while ($count < 8) { // Limit to 8 arguments for display
  1614.             $arg = str(*(char **)$argptr);
  1615.             if ($arg != NULL && $arg != 0) {
  1616.                 printf("%s ", $arg);
  1617.                 $argptr += 8;
  1618.                 $count++;
  1619.             } else {
  1620.                 break;
  1621.             }
  1622.         }
  1623.     }
  1624.     printf("\n");
  1625.    
  1626.     // Track suspicious commands
  1627.    
  1628.     // Network commands
  1629.     if (strstr($filename, "/usr/bin/curl") ||
  1630.         strstr($filename, "/usr/bin/wget") ||
  1631.         strstr($filename, "/usr/bin/nc") ||
  1632.         strstr($filename, "/bin/nc") ||
  1633.         strstr($filename, "/usr/bin/netcat") ||
  1634.         strstr($filename, "/usr/bin/ssh") ||
  1635.         strstr($filename, "/usr/bin/sftp") ||
  1636.         strstr($filename, "/usr/bin/ftp") ||
  1637.         strstr($filename, "/usr/bin/scp")) {
  1638.         printf("NETWORK COMMAND DETECTED\n");
  1639.     }
  1640.    
  1641.     // Data encoding/compression commands
  1642.     if (strstr($filename, "/usr/bin/base64") ||
  1643.         strstr($filename, "/usr/bin/gzip") ||
  1644.         strstr($filename, "/usr/bin/bzip2") ||
  1645.         strstr($filename, "/usr/bin/xz") ||
  1646.         strstr($filename, "/usr/bin/tar") ||
  1647.         strstr($filename, "/usr/bin/zip") ||
  1648.         strstr($filename, "/usr/bin/7z")) {
  1649.         printf("DATA ENCODING/COMPRESSION COMMAND DETECTED\n");
  1650.     }
  1651.    
  1652.     // System information gathering commands
  1653.     if (strstr($filename, "/usr/bin/uname") ||
  1654.         strstr($filename, "/bin/hostname") ||
  1655.         strstr($filename, "/usr/bin/id") ||
  1656.         strstr($filename, "/usr/bin/whoami") ||
  1657.         strstr($filename, "/bin/ip") ||
  1658.         strstr($filename, "/bin/netstat") ||
  1659.         strstr($filename, "/usr/bin/ss") ||
  1660.         strstr($filename, "/usr/bin/ps") ||
  1661.         strstr($filename, "/usr/bin/top") ||
  1662.         strstr($filename, "/usr/bin/htop")) {
  1663.         printf("SYSTEM INFORMATION GATHERING COMMAND DETECTED\n");
  1664.     }
  1665.    
  1666.     // File access commands
  1667.     if (strstr($filename, "/bin/cat") ||
  1668.         strstr($filename, "/usr/bin/head") ||
  1669.         strstr($filename, "/usr/bin/tail") ||
  1670.         strstr($filename, "/usr/bin/less") ||
  1671.         strstr($filename, "/usr/bin/more") ||
  1672.         strstr($filename, "/bin/grep") ||
  1673.         strstr($filename, "/usr/bin/find") ||
  1674.         strstr($filename, "/usr/bin/locate")) {
  1675.         printf("FILE ACCESS COMMAND DETECTED\n");
  1676.        
  1677.         // Check if accessing sensitive files (via arguments)
  1678.         $argptr = args->argv + 8; // Skip the command name
  1679.         $arg = str(*(char **)$argptr);
  1680.         if ($arg) {
  1681.             if (strstr($arg, "/etc/passwd") ||
  1682.                 strstr($arg, "/etc/shadow") ||
  1683.                 strstr($arg, "/etc/ssh") ||
  1684.                 strstr($arg, "/home/") ||
  1685.                 strstr($arg, "/root/") ||
  1686.                 strstr($arg, "/.ssh/") ||
  1687.                 strstr($arg, "/var/log/")) {
  1688.                 printf("WARNING: Accessing sensitive files: %s %s\n", $filename, $arg);
  1689.             }
  1690.         }
  1691.     }
  1692.    
  1693.     // Crypto/key commands
  1694.     if (strstr($filename, "/usr/bin/ssh-keygen") ||
  1695.         strstr($filename, "/usr/bin/gpg") ||
  1696.         strstr($filename, "/usr/bin/openssl")) {
  1697.         printf("CRYPTO/KEY OPERATION COMMAND DETECTED\n");
  1698.     }
  1699.    
  1700.     // Suspicious shell one-liners (using perl, python, ruby, etc. for one-liners)
  1701.     if ((strstr($filename, "/usr/bin/perl") ||
  1702.          strstr($filename, "/usr/bin/python") ||
  1703.          strstr($filename, "/usr/bin/ruby") ||
  1704.          strstr($filename, "/usr/bin/php")) &&
  1705.         (strstr(str(args->argv[1]), "-e") ||
  1706.          strstr(str(args->argv[1]), "-c"))) {
  1707.         printf("WARNING: Potential malicious one-liner detected!\n");
  1708.     }
  1709.    
  1710.     // Check if bash/sh is executing commands from standard input/pipe
  1711.     if ((strstr($filename, "/bin/bash") ||
  1712.          strstr($filename, "/bin/sh") ||
  1713.          strstr($filename, "/bin/dash")) &&
  1714.         (strstr(str(args->argv[1]), "-c"))) {
  1715.         printf("BASH/SH EXECUTING COMMAND STRING\n");
  1716.     }
  1717. }
  1718.  
  1719. // Track bash command history
  1720. kprobe:add_history
  1721. {
  1722.     time("%H:%M:%S.%f ");
  1723.     $cmd = str(arg0);
  1724.     printf("%-16s %-10d %-8d BASH HISTORY: %s\n",
  1725.            comm, pid, uid, $cmd);
  1726.    
  1727.     // Check for suspicious commands in bash history
  1728.     if (strstr($cmd, "wget ") ||
  1729.         strstr($cmd, "curl ") ||
  1730.         strstr($cmd, "nc ") ||
  1731.         strstr($cmd, "netcat ") ||
  1732.         strstr($cmd, "chmod +x") ||
  1733.         strstr($cmd, "base64 ") ||
  1734.         strstr($cmd, "python -c") ||
  1735.         strstr($cmd, "perl -e") ||
  1736.         strstr($cmd, "ruby -e") ||
  1737.         strstr($cmd, "php -r") ||
  1738.         strstr($cmd, ">/dev/tcp/") ||
  1739.         strstr($cmd, "mkfifo") ||
  1740.         strstr($cmd, "/dev/null 2>&1")) {
  1741.         printf("WARNING: Suspicious command in bash history: %s\n", $cmd);
  1742.     }
  1743. }
  1744.  
  1745. // Track command execution chains
  1746. tracepoint:syscalls:sys_enter_execve
  1747. {
  1748.     // Build command execution chain
  1749.     $parent_pid = curtask->parent->pid;
  1750.     $parent_comm = curtask->parent->comm;
  1751.    
  1752.     // Update command chain for this PID
  1753.     @cmd_chain[pid] = $parent_pid;
  1754.     @cmd_name[pid] = $filename;
  1755.    
  1756.     // Check for suspicious chains/patterns
  1757.     $grandparent_pid = @cmd_chain[$parent_pid];
  1758.     $grandparent_comm = comm; // This is a simplification; we'd need to track this separately
  1759.    
  1760.     // Detect web server -> shell -> download/network tool chain
  1761.     if (($grandparent_comm == "apache2" || $grandparent_comm == "nginx" || $grandparent_comm == "php-fpm") &&
  1762.         ($parent_comm == "sh" || $parent_comm == "bash" || $parent_comm == "dash") &&
  1763.         (strstr($filename, "wget") || strstr($filename, "curl") || strstr($filename, "nc"))) {
  1764.         printf("WARNING: Possible webshell detected! Command chain: %s -> %s -> %s\n",
  1765.                $grandparent_comm, $parent_comm, comm);
  1766.     }
  1767. }
  1768.  
  1769. // Report on command executions periodically
  1770. interval:s:30
  1771. {
  1772.     printf("\n=== Command Execution Summary (30-sec interval) ===\n");
  1773.     printf("Most active command sources:\n");
  1774.     print(@cmd_source);
  1775.     clear(@cmd_source);
  1776.     printf("================================================\n\n");
  1777. }
  1778.  
  1779. END
  1780. {
  1781.     clear(@cmd_chain);
  1782.     clear(@cmd_name);
  1783.     clear(@cmd_source);
  1784.     printf("Command execution tracking stopped.\n");
  1785. }
  1786. EOF
  1787.    
  1788.     # Run the BPF program
  1789.     sudo bpftrace /tmp/command_monitor.bt
  1790.    
  1791.     # Clean up
  1792.     rm -f /tmp/command_monitor.bt
  1793. }
  1794.  
  1795. # Function to monitor DNS for data exfiltration
  1796. monitor_dns_exfiltration() {
  1797.     echo "Monitoring DNS for data exfiltration using eBPF. Press Ctrl+C to stop."
  1798.    
  1799.     # Create temporary BPF program
  1800.     cat > /tmp/dns_monitor.bt << 'EOF'
  1801. #!/usr/bin/env bpftrace
  1802. #include <linux/sched.h>
  1803. #include <net/sock.h>
  1804. #include <linux/udp.h>
  1805. #include <linux/ip.h>
  1806.  
  1807. BEGIN
  1808. {
  1809.     printf("Monitoring DNS for data exfiltration...\n");
  1810.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "DNS ACTIVITY");
  1811. }
  1812.  
  1813. // Track system calls for DNS queries
  1814. tracepoint:syscalls:sys_enter_sendto,
  1815. tracepoint:syscalls:sys_enter_sendmsg
  1816. /args->fd >= 0/
  1817. {
  1818.     @dns_send[pid, comm] = args->count;
  1819. }
  1820.  
  1821. // Track DNS outbound traffic by process (UDP port 53)
  1822. tracepoint:syscalls:sys_exit_sendto,
  1823. tracepoint:syscalls:sys_exit_sendmsg
  1824. /@dns_send[pid, comm]/
  1825. {
  1826.     $count = @dns_send[pid, comm];
  1827.     delete(@dns_send[pid, comm]);
  1828.    
  1829.     // Check for large DNS packets (potential data exfiltration)
  1830.     if ($count > 100) {
  1831.         time("%H:%M:%S.%f ");
  1832.         printf("%-16s %-10d %-8d DNS QUERY: size=%d bytes\n",
  1833.                comm, pid, uid, $count);
  1834.        
  1835.         // Track DNS traffic volume per process
  1836.         @dns_traffic[comm, pid] += $count;
  1837.        
  1838.         // Check for high-volume traffic which may indicate tunneling/exfiltration
  1839.         if (@dns_traffic[comm, pid] > 10000) { // 10KB threshold
  1840.             printf("WARNING: High DNS traffic volume detected from %s (PID: %d) - possible exfiltration\n",
  1841.                    comm, pid);
  1842.         }
  1843.     }
  1844. }
  1845.  
  1846. // Track DNS-related executables
  1847. tracepoint:syscalls:sys_enter_execve
  1848. /(strstr(str(args->filename), "dig") ||
  1849.   strstr(str(args->filename), "nslookup") ||
  1850.   strstr(str(args->filename), "host") ||
  1851.   strstr(str(args->filename), "drill") ||
  1852.   strstr(str(args->filename), "dnsmasq") ||
  1853.   strstr(str(args->filename), "drill") ||
  1854.   strstr(str(args->filename), "delv"))/
  1855. {
  1856.     time("%H:%M:%S.%f ");
  1857.     printf("%-16s %-10d %-8d DNS TOOL: %s",
  1858.            comm, pid, uid, str(args->filename));
  1859.    
  1860.     // Print command arguments if available
  1861.     $argptr = args->argv;
  1862.     printf(" ARGS: ");
  1863.     $count = 0;
  1864.     if ($argptr) {
  1865.         while ($count < 4) { // Limit to 4 arguments for display
  1866.             $arg = str(*(char **)$argptr);
  1867.             if ($arg != NULL && $arg != 0) {
  1868.                 printf("%s ", $arg);
  1869.                 $argptr += 8;
  1870.                 $count++;
  1871.             } else {
  1872.                 break;
  1873.             }
  1874.         }
  1875.     }
  1876.     printf("\n");
  1877.    
  1878.     // Check for suspicious DNS queries (very long or with unusual patterns)
  1879.     $argptr = args->argv + 8; // Skip the command name
  1880.     $arg = str(*(char **)$argptr);
  1881.     if ($arg) {
  1882.         $arg_len = strlen($arg);
  1883.         if ($arg_len > 50) { // Unusually long domain name
  1884.             printf("WARNING: Unusually long DNS query: %s\n", $arg);
  1885.         }
  1886.        
  1887.         // Check for many subdomains (potential for DNS tunneling)
  1888.         $dot_count = 0;
  1889.         for (int i = 0; i < $arg_len; i++) {
  1890.             if ($arg[i] == '.') {
  1891.                 $dot_count++;
  1892.             }
  1893.         }
  1894.        
  1895.         if ($dot_count > 5) { // More than 5 subdomains is unusual
  1896.             printf("WARNING: Query with many subdomains (possible tunneling): %s\n", $arg);
  1897.         }
  1898.        
  1899.         // Check for hex/base64-like encoding in domain names
  1900.         $hex_chars = 0;
  1901.         $alnum_chars = 0;
  1902.         for (int i = 0; i < $arg_len; i++) {
  1903.             if (($arg[i] >= '0' && $arg[i] <= '9') ||
  1904.                 ($arg[i] >= 'a' && $arg[i] <= 'f') ||
  1905.                 ($arg[i] >= 'A' && $arg[i] <= 'F')) {
  1906.                 $hex_chars++;
  1907.             }
  1908.             if (($arg[i] >= '0' && $arg[i] <= '9') ||
  1909.                 ($arg[i] >= 'a' && $arg[i] <= 'z') ||
  1910.                 ($arg[i] >= 'A' && $arg[i] <= 'Z')) {
  1911.                 $alnum_chars++;
  1912.             }
  1913.         }
  1914.        
  1915.         if ($hex_chars > 0.8 * $alnum_chars && $arg_len > 20) {
  1916.             printf("WARNING: Query with hex-like encoding (possible exfiltration): %s\n", $arg);
  1917.         }
  1918.     }
  1919. }
  1920.  
  1921. // Track DNS resolution attempts via /etc/resolv.conf access
  1922. tracepoint:syscalls:sys_enter_open,
  1923. tracepoint:syscalls:sys_enter_openat
  1924. /(strstr(str(args->filename), "/etc/resolv.conf") ||
  1925.   strstr(str(args->filename), "/etc/hosts"))/
  1926. {
  1927.     time("%H:%M:%S.%f ");
  1928.     printf("%-16s %-10d %-8d DNS CONFIG ACCESS: %s\n",
  1929.            comm, pid, uid, str(args->filename));
  1930. }
  1931.  
  1932. // Report on DNS exfiltration indicators periodically
  1933. interval:s:30
  1934. {
  1935.     printf("\n=== DNS Exfiltration Indicators (30-sec interval) ===\n");
  1936.     printf("Processes with high DNS traffic volume:\n");
  1937.     print(@dns_traffic);
  1938.     printf("=====================================================\n\n");
  1939.    
  1940.     // Reset counters
  1941.     clear(@dns_traffic);
  1942. }
  1943.  
  1944. END
  1945. {
  1946.     clear(@dns_send);
  1947.     clear(@dns_traffic);
  1948.     printf("DNS exfiltration monitoring stopped.\n");
  1949. }
  1950. EOF
  1951.    
  1952.     # Run the BPF program
  1953.     sudo bpftrace /tmp/dns_monitor.bt
  1954.    
  1955.     # Clean up
  1956.     rm -f /tmp/dns_monitor.bt
  1957. }
  1958.  
  1959. # Function to detect abnormal process behavior
  1960. detect_abnormal_process() {
  1961.     echo "Detecting abnormal process behavior using eBPF. Press Ctrl+C to stop."
  1962.    
  1963.     # Create temporary BPF program
  1964.     cat > /tmp/abnormal_process.bt << 'EOF'
  1965. #!/usr/bin/env bpftrace
  1966. #include <linux/sched.h>
  1967.  
  1968. BEGIN
  1969. {
  1970.     printf("Detecting abnormal process behavior...\n");
  1971.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  1972. }
  1973.  
  1974. // Track process creation
  1975. tracepoint:syscalls:sys_enter_execve
  1976. {
  1977.     time("%H:%M:%S.%f ");
  1978.     printf("%-16s %-10d %-8d PROCESS STARTED: %s\n",
  1979.            comm, pid, uid, str(args->filename));
  1980.    
  1981.     // Record process start time
  1982.     @proc_start_time[pid] = nsecs;
  1983.    
  1984.     // Track process lineage
  1985.     $parent_pid = curtask->parent->pid;
  1986.     $parent_comm = curtask->parent->comm;
  1987.     @proc_parent[pid] = $parent_pid;
  1988.     @proc_cmd[pid] = str(args->filename);
  1989. }
  1990.  
  1991. // Track process exit
  1992. tracepoint:sched:sched_process_exit
  1993. /@proc_start_time[pid]/
  1994. {
  1995.     $duration = (nsecs - @proc_start_time[pid]) / 1000000000; // seconds
  1996.     $parent_pid = @proc_parent[pid];
  1997.     $cmd = @proc_cmd[pid];
  1998.    
  1999.     time("%H:%M:%S.%f ");
  2000.     printf("%-16s %-10d %-8d PROCESS EXITED: Duration=%d seconds\n",
  2001.            comm, pid, uid, $duration);
  2002.    
  2003.     // Detect short-lived processes
  2004.     if ($duration < 1 && comm != "ps" && comm != "ls" &&
  2005.         comm != "grep" && comm != "cat" && comm != "id") {
  2006.         printf("UNUSUAL: Short-lived process: %s (%d)\n", comm, pid);
  2007.     }
  2008.    
  2009.     // Detect abnormally long running processes that should be short-lived
  2010.     if ($duration > 600 && // 10 minutes
  2011.         (comm == "cat" || comm == "ls" || comm == "cp" ||
  2012.          comm == "mv" || comm == "dd" || comm == "grep")) {
  2013.         printf("UNUSUAL: Long-running utility process: %s (%d)\n", comm, pid);
  2014.     }
  2015.    
  2016.     // Clean up tracking data
  2017.     delete(@proc_start_time[pid]);
  2018.     delete(@proc_parent[pid]);
  2019.     delete(@proc_cmd[pid]);
  2020. }
  2021.  
  2022. // Track execution of processes from unusual directories
  2023. tracepoint:syscalls:sys_enter_execve
  2024. /(strncmp(str(args->filename), "/tmp/", 5) == 0 ||
  2025.   strncmp(str(args->filename), "/var/tmp/", 9) == 0 ||
  2026.   strncmp(str(args->filename), "/dev/shm/", 9) == 0 ||
  2027.   strncmp(str(args->filename), "/home/", 6) == 0)/
  2028. {
  2029.     printf("UNUSUAL: Executing from non-standard location: %s\n", str(args->filename));
  2030. }
  2031.  
  2032. // Track CPU-intensive processes
  2033. tracepoint:sched:sched_stat_runtime
  2034. /args->runtime > 1000000000/ // 100ms
  2035. {
  2036.     @cpu_usage[pid, comm] += args->runtime;
  2037. }
  2038.  
  2039. // Track memory usage changes
  2040. tracepoint:syscalls:sys_enter_mmap
  2041. {
  2042.     @mem_alloc[pid, comm] += args->len;
  2043. }
  2044.  
  2045. // Track file access patterns
  2046. tracepoint:syscalls:sys_enter_openat
  2047. {
  2048.     @file_opens[pid, comm] = count();
  2049. }
  2050.  
  2051. // Track network activity
  2052. tracepoint:syscalls:sys_enter_connect,
  2053. tracepoint:syscalls:sys_enter_sendto,
  2054. tracepoint:syscalls:sys_enter_sendmsg
  2055. {
  2056.     @network_activity[pid, comm] = count();
  2057. }
  2058.  
  2059. // Detect abnormal patterns periodically
  2060. interval:s:30
  2061. {
  2062.     printf("\n=== Abnormal Process Behavior Analysis (30-sec interval) ===\n");
  2063.    
  2064.     // Identify CPU-intensive processes
  2065.     printf("Top CPU-intensive processes:\n");
  2066.     print(@cpu_usage);
  2067.    
  2068.     // Identify processes with high memory allocation
  2069.     printf("\nTop memory-allocating processes:\n");
  2070.     print(@mem_alloc);
  2071.    
  2072.     // Identify processes with high file activity
  2073.     printf("\nTop file-accessing processes:\n");
  2074.     print(@file_opens);
  2075.    
  2076.     // Identify processes with high network activity
  2077.     printf("\nTop network-active processes:\n");
  2078.     print(@network_activity);
  2079.    
  2080.     // Correlate activity across dimensions to identify abnormal behavior
  2081.     printf("\nProcesses with unusual behavior patterns:\n");
  2082.    
  2083.     // Detect processes with both high CPU and network activity (possible cryptominer)
  2084.     if (@cpu_usage[pid, comm] > 10000000000 && @network_activity[pid, comm] > 20) {
  2085.         printf("SUSPICIOUS: %s (PID: %d) has high CPU and network activity - possible cryptominer\n",
  2086.                comm, pid);
  2087.     }
  2088.    
  2089.     // Detect processes with high file and network activity (possible data exfiltration)
  2090.     if (@file_opens[pid, comm] > 100 && @network_activity[pid, comm] > 20) {
  2091.         printf("SUSPICIOUS: %s (PID: %d) has high file and network activity - possible data exfiltration\n",
  2092.                comm, pid);
  2093.     }
  2094.    
  2095.     printf("============================================================\n\n");
  2096.    
  2097.     // Reset counters
  2098.     clear(@cpu_usage);
  2099.     clear(@mem_alloc);
  2100.     clear(@file_opens);
  2101.     clear(@network_activity);
  2102. }
  2103.  
  2104. END
  2105. {
  2106.     clear(@proc_start_time);
  2107.     clear(@proc_parent);
  2108.     clear(@proc_cmd);
  2109.     clear(@cpu_usage);
  2110.     clear(@mem_alloc);
  2111.     clear(@file_opens);
  2112.     clear(@network_activity);
  2113.     printf("Abnormal process behavior detection stopped.\n");
  2114. }
  2115. EOF
  2116.    
  2117.     # Run the BPF program
  2118.     sudo bpftrace /tmp/abnormal_process.bt
  2119.    
  2120.     # Clean up
  2121.     rm -f /tmp/abnormal_process.bt
  2122. }
  2123.  
  2124. # Function to monitor data access patterns
  2125. monitor_data_patterns() {
  2126.     echo "Monitoring data access patterns using eBPF. Press Ctrl+C to stop."
  2127.    
  2128.     # Create temporary BPF program
  2129.     cat > /tmp/data_monitor.bt << 'EOF'
  2130. #!/usr/bin/env bpftrace
  2131. #include <linux/sched.h>
  2132. #include <linux/fs.h>
  2133.  
  2134. BEGIN
  2135. {
  2136.     printf("Monitoring data access patterns...\n");
  2137.     printf("%-24s %-16s %-10s %-8s %s\n", "TIME", "COMM", "PID", "UID", "ACTIVITY");
  2138. }
  2139.  
  2140. // Track file open operations
  2141. tracepoint:syscalls:sys_enter_open,
  2142. tracepoint:syscalls:sys_enter_openat
  2143. {
  2144.     $filename = probe == "tracepoint:syscalls:sys_enter_open" ?
  2145.                 str(args->filename) : str(args->filename);
  2146.    
  2147.     // Track file opens by category
  2148.     if (strncmp($filename, "/etc/", 5) == 0) {
  2149.         @file_access[pid, comm, "config"] = count();
  2150.     }
  2151.     else if (strncmp($filename, "/var/log/", 9) == 0) {
  2152.         @file_access[pid, comm, "logs"] = count();
  2153.        
  2154.         time("%H:%M:%S.%f ");
  2155.         printf("%-16s %-10d %-8d LOG ACCESS: %s\n",
  2156.                comm, pid, uid, $filename);
  2157.     }
  2158.     else if (strncmp($filename, "/home/", 6) == 0 || strncmp($filename, "/root/", 6) == 0) {
  2159.         @file_access[pid, comm, "home"] = count();
  2160.        
  2161.         // Check for access to sensitive user files
  2162.         if (strstr($filename, ".ssh/") ||
  2163.             strstr($filename, ".aws/") ||
  2164.             strstr($filename, ".config/") ||
  2165.             strstr($filename, ".bash_history") ||
  2166.             strstr($filename, ".profile") ||
  2167.             strstr($filename, ".bashrc")) {
  2168.             time("%H:%M:%S.%f ");
  2169.             printf("%-16s %-10d %-8d SENSITIVE USER FILE: %s\n",
  2170.                    comm, pid, uid, $filename);
  2171.            
  2172.             printf("WARNING: Access to sensitive user configuration/credential file detected\n");
  2173.         }
  2174.     }
  2175.     else if (strncmp($filename, "/var/lib/", 9) == 0 || strncmp($filename, "/var/db/", 8) == 0) {
  2176.         @file_access[pid, comm, "database"] = count();
  2177.     }
  2178.     else if (strncmp($filename, "/proc/", 6) == 0 || strncmp($filename, "/sys/", 5) == 0) {
  2179.         @file_access[pid, comm, "proc_sys"] = count();
  2180.     }
  2181. }
  2182.  
  2183. // Track file reads
  2184. tracepoint:syscalls:sys_enter_read
  2185. {
  2186.     $fd = args->fd;
  2187.     $count = args->count;
  2188.    
  2189.     // Track large reads
  2190.     if ($count > 1048576) { // 1MB
  2191.         time("%H:%M:%S.%f ");
  2192.         printf("%-16s %-10d %-8d LARGE READ: fd=%d size=%lu\n",
  2193.                comm, pid, uid, $fd, $count);
  2194.        
  2195.         @large_reads[pid, comm] = count();
  2196.     }
  2197.    
  2198.     // Track total bytes read
  2199.     @bytes_read[pid, comm] += $count;
  2200. }
  2201.  
  2202. // Track file writes
  2203. tracepoint:syscalls:sys_enter_write
  2204. {
  2205.     $fd = args->fd;
  2206.     $count = args->count;
  2207.    
  2208.     // Track large writes
  2209.     if ($count > 1048576) { // 1MB
  2210.         time("%H:%M:%S.%f ");
  2211.         printf("%-16s %-10d %-8d LARGE WRITE: fd=%d size=%lu\n",
  2212.                comm, pid, uid, $fd, $count);
  2213.        
  2214.         @large_writes[pid, comm] = count();
  2215.     }
  2216.    
  2217.     // Track total bytes written
  2218.     @bytes_written[pid, comm] += $count;
  2219. }
  2220.  
  2221. // Track directory scanning (readdir, etc)
  2222. tracepoint:syscalls:sys_enter_getdents,
  2223. tracepoint:syscalls:sys_enter_getdents64
  2224. {
  2225.     time("%H:%M:%S.%f ");
  2226.     printf("%-16s %-10d %-8d SCANNING DIRECTORY: fd=%d\n",
  2227.            comm, pid, uid, args->fd);
  2228.    
  2229.     @dir_scans[pid, comm] = count();
  2230. }
  2231.  
  2232. // Track file scanning behavior (many opens)
  2233. tracepoint:syscalls:sys_exit_open,
  2234. tracepoint:syscalls:sys_exit_openat
  2235. /args->ret >= 0/
  2236. {
  2237.     @file_opens[pid, comm] = count();
  2238.    
  2239.     // Alert on process with many file opens
  2240.     if (@file_opens[pid, comm] > 100) {
  2241.         time("%H:%M:%S.%f ");
  2242.         printf("%-16s %-10d %-8d HIGH-VOLUME FILE ACCESS: %d files\n",
  2243.                comm, pid, uid, @file_opens[pid, comm]);
  2244.        
  2245.         printf("WARNING: Process scanning many files, possible data mining/exfiltration\n");
  2246.     }
  2247. }
  2248.  
  2249. // Track specific access patterns
  2250. tracepoint:syscalls:sys_enter_rename,
  2251. tracepoint:syscalls:sys_enter_renameat,
  2252. tracepoint:syscalls:sys_enter_renameat2
  2253. {
  2254.     time("%H:%M:%S.%f ");
  2255.     if (probe == "tracepoint:syscalls:sys_enter_rename") {
  2256.         printf("%-16s %-10d %-8d RENAME: %s -> %s\n",
  2257.                comm, pid, uid, str(args->oldname), str(args->newname));
  2258.     } else {
  2259.         printf("%-16s %-10d %-8d RENAME: (at) fd=%d %s -> fd=%d %s\n",
  2260.                comm, pid, uid, args->olddfd, str(args->oldname),
  2261.                args->newdfd, str(args->newname));
  2262.     }
  2263.    
  2264.     // Detect file extension changes that might indicate ransomware
  2265.     $oldname = probe == "tracepoint:syscalls:sys_enter_rename" ?
  2266.               str(args->oldname) : str(args->oldname);
  2267.     $newname = probe == "tracepoint:syscalls:sys_enter_rename" ?
  2268.               str(args->newname) : str(args->newname);
  2269.    
  2270.     $old_len = strlen($oldname);
  2271.     $new_len = strlen($newname);
  2272.    
  2273.     // Check for ransomware-like extension appending
  2274.     if ($new_len > $old_len + 3 &&
  2275.         ($newname[$new_len - 4] == '.' || $newname[$new_len - 5] == '.') &&
  2276.         ($oldname[$old_len - 4] == '.' || $oldname[$old_len - 5] == '.')) {
  2277.         printf("WARNING: Possible ransomware behavior - changing file extensions\n");
  2278.     }
  2279.    
  2280.     @renames[pid, comm] = count();
  2281. }
  2282.  
  2283. // Track sequential file operations (possible encryption/ransomware)
  2284. tracepoint:syscalls:sys_exit_open,
  2285. tracepoint:syscalls:sys_exit_openat
  2286. /args->ret >= 0/
  2287. {
  2288.     // Increment sequential file open counter
  2289.     @sequential_access[pid, comm, args->ret] = nsecs;
  2290. }
  2291.  
  2292. tracepoint:syscalls:sys_enter_close
  2293. /@sequential_access[pid, comm, args->fd]/
  2294. {
  2295.     $time_diff = nsecs - @sequential_access[pid, comm, args->fd];
  2296.     delete(@sequential_access[pid, comm, args->fd]);
  2297.    
  2298.     // Check if it was a quick open-close sequence
  2299.     if ($time_diff < 1000000000) { // 1 second
  2300.         @quick_file_ops[pid, comm] = count();
  2301.     }
  2302.    
  2303.     // Alert on many quick file operations (potential ransomware/bulk encryption)
  2304.     if (@quick_file_ops[pid, comm] > 50) {
  2305.         time("%H:%M:%S.%f ");
  2306.         printf("%-16s %-10d %-8d RAPID FILE OPERATIONS: %d files\n",
  2307.                comm, pid, uid, @quick_file_ops[pid, comm]);
  2308.        
  2309.         printf("WARNING: Process rapidly accessing many files - possible ransomware/encryption\n");
  2310.     }
  2311. }
  2312.  
  2313. // Analyze data access patterns periodically
  2314. interval:s:30
  2315. {
  2316.     printf("\n=== Data Access Pattern Analysis (30-sec interval) ===\n");
  2317.    
  2318.     // File access by category
  2319.     printf("File access by category:\n");
  2320.     print(@file_access);
  2321.    
  2322.     // Large data transfers
  2323.     printf("\nProcesses performing large reads:\n");
  2324.     print(@large_reads);
  2325.    
  2326.     printf("\nProcesses performing large writes:\n");
  2327.     print(@large_writes);
  2328.    
  2329.     // High volume access
  2330.     printf("\nDirectory scanning operations:\n");
  2331.     print(@dir_scans);
  2332.    
  2333.     // Byte volume transfers
  2334.     printf("\nTotal bytes read by process:\n");
  2335.     print(@bytes_read);
  2336.    
  2337.     printf("\nTotal bytes written by process:\n");
  2338.     print(@bytes_written);
  2339.    
  2340.     // Detect suspicious patterns
  2341.    
  2342.     // Data exfiltration pattern: high read volume with network activity
  2343.     if (@bytes_read[pid, comm] > 10485760 && @network_activity[pid, comm] > 10) { // 10MB read + network
  2344.         printf("\nWARNING: Possible data exfiltration - process reading large amounts of data and using network: %s (PID: %d)\n",
  2345.                comm, pid);
  2346.     }
  2347.    
  2348.     // Ransomware pattern: high read volume, high write volume, many file operations
  2349.     if (@bytes_read[pid, comm] > 10485760 && @bytes_written[pid, comm] > 10485760 &&
  2350.         @quick_file_ops[pid, comm] > 30) {
  2351.         printf("\nWARNING: Possible ransomware - process with high read/write volume and many quick file operations: %s (PID: %d)\n",
  2352.                comm, pid);
  2353.     }
  2354.    
  2355.     // Reset counters for next interval
  2356.     clear(@file_access);
  2357.     clear(@large_reads);
  2358.     clear(@large_writes);
  2359.     clear(@dir_scans);
  2360.     clear(@bytes_read);
  2361.     clear(@bytes_written);
  2362.     clear(@quick_file_ops);
  2363.    
  2364.     printf("=======================================================\n\n");
  2365. }
  2366.  
  2367. END
  2368. {
  2369.     clear(@file_access);
  2370.     clear(@large_reads);
  2371.     clear(@large_writes);
  2372.     clear(@dir_scans);
  2373.     clear(@file_opens);
  2374.     clear(@bytes_read);
  2375.     clear(@bytes_written);
  2376.     clear(@renames);
  2377.     clear(@sequential_access);
  2378.     clear(@quick_file_ops);
  2379.     clear(@network_activity);
  2380.     printf("Data access pattern monitoring stopped.\n");
  2381. }
  2382. EOF
  2383.    
  2384.     # Run the BPF program
  2385.     sudo bpftrace /tmp/data_monitor.bt
  2386.    
  2387.     # Clean up
  2388.     rm -f /tmp/data_monitor.bt
  2389. }
  2390.  
  2391. # Function to generate activity report
  2392. generate_activity_report() {
  2393.     echo "Generating eBPF activity report. This will run multiple eBPF monitoring tools for a short time."
  2394.    
  2395.     # Create report directory
  2396.     report_dir="ebpf_report_$(date +%Y%m%d_%H%M%S)"
  2397.     mkdir -p "$report_dir"
  2398.    
  2399.     echo "eBPF Malicious Activity Report - $(date)" > "$report_dir/report.txt"
  2400.     echo "=====================================" >> "$report_dir/report.txt"
  2401.    
  2402.     # Run a series of short eBPF monitoring sessions
  2403.     echo "Running file operations monitoring..."
  2404.     # Create temporary BPF program for file operations
  2405.     cat > /tmp/report_file_monitor.bt << 'EOF'
  2406. #!/usr/bin/env bpftrace
  2407. #include <linux/fs.h>
  2408.  
  2409. BEGIN
  2410. {
  2411.     printf("Monitoring suspicious file operations...\n");
  2412. }
  2413.  
  2414. // Monitor file opens in sensitive locations
  2415. tracepoint:syscalls:sys_enter_openat
  2416. {
  2417.     $filename = str(args->filename);
  2418.    
  2419.     // Check for access to sensitive files and directories
  2420.     if (
  2421.         strncmp($filename, "/etc/passwd", 11) == 0 ||
  2422.         strncmp($filename, "/etc/shadow", 11) == 0 ||
  2423.         strncmp($filename, "/etc/ssh", 8) == 0 ||
  2424.         strncmp($filename, "/etc/sudoers", 12) == 0 ||
  2425.         strncmp($filename, "/etc/crontab", 12) == 0 ||
  2426.         strncmp($filename, "/var/log", 8) == 0
  2427.     )
  2428.     {
  2429.         printf("SENSITIVE FILE: PID %d (%s, UID %d) opened %s\n",
  2430.             pid, comm, uid, $filename);
  2431.     }
  2432.    
  2433.     // Check for access to hidden files/directories
  2434.     if (
  2435.         (strncmp($filename, "/tmp/", 5) == 0 ||
  2436.          strncmp($filename, "/var/tmp/", 9) == 0 ||
  2437.          strncmp($filename, "/dev/shm/", 9) == 0) &&
  2438.         strncmp(basename($filename), ".", 1) == 0
  2439.     )
  2440.     {
  2441.         printf("HIDDEN FILE: PID %d (%s, UID %d) accessed %s\n",
  2442.             pid, comm, uid, $filename);
  2443.     }
  2444. }
  2445. EOF
  2446.  
  2447.     # Run for 10 seconds
  2448.     timeout 10 sudo bpftrace /tmp/report_file_monitor.bt > "$report_dir/file_operations.txt" 2>&1
  2449.    
  2450.     echo -e "\n== File Operations ==" >> "$report_dir/report.txt"
  2451.     if grep -q "SENSITIVE FILE\|HIDDEN FILE" "$report_dir/file_operations.txt"; then
  2452.         echo "Suspicious file operations detected:" >> "$report_dir/report.txt"
  2453.         grep "SENSITIVE FILE\|HIDDEN FILE" "$report_dir/file_operations.txt" >> "$report_dir/report.txt"
  2454.     else
  2455.         echo "No suspicious file operations detected." >> "$report_dir/report.txt"
  2456.     fi
  2457.    
  2458.     # Run process monitoring
  2459.     echo "Running process monitoring..."
  2460.     # Create temporary BPF program for process monitoring
  2461.     cat > /tmp/report_process_monitor.bt << 'EOF'
  2462. #!/usr/bin/env bpftrace
  2463. #include <linux/sched.h>
  2464.  
  2465. BEGIN
  2466. {
  2467.     printf("Monitoring process creation...\n");
  2468. }
  2469.  
  2470. // Trace process creation (execve)
  2471. tracepoint:syscalls:sys_enter_execve
  2472. {
  2473.     $filename = str(args->filename);
  2474.     $parent_pid = curtask->parent->pid;
  2475.     $parent_comm = curtask->parent->comm;
  2476.    
  2477.     printf("PROCESS: %s (PID %d, PPID %d [%s]) executed %s\n",
  2478.            comm, pid, $parent_pid, $parent_comm, $filename);
  2479.    
  2480.     // Track shell spawning shells (possible lateral movement or privilege escalation)
  2481.     if (($parent_comm == "bash" || $parent_comm == "sh" || $parent_comm == "dash") &&
  2482.         (comm == "bash" || comm == "sh" || comm == "dash")) {
  2483.         printf("WARNING: Shell spawning shell detected! %s (%d) -> %s (%d)\n",
  2484.                $parent_comm, $parent_pid, comm, pid);
  2485.     }
  2486.    
  2487.     // Track suspicious process chains (web server -> shell)
  2488.     if (($parent_comm == "apache2" || $parent_comm == "nginx" || $parent_comm == "httpd") &&
  2489.         (comm == "bash" || comm == "sh" || comm == "dash" || comm == "perl" ||
  2490.          comm == "python" || comm == "php" || comm == "ruby")) {
  2491.         printf("WARNING: Web server spawning shell! %s (%d) -> %s (%d)\n",
  2492.                $parent_comm, $parent_pid, comm, pid);
  2493.     }
  2494. }
  2495. EOF
  2496.  
  2497.     # Run for 10 seconds
  2498.     timeout 10 sudo bpftrace /tmp/report_process_monitor.bt > "$report_dir/process_creation.txt" 2>&1
  2499.    
  2500.     echo -e "\n== Process Creation ==" >> "$report_dir/report.txt"
  2501.     if grep -q "WARNING" "$report_dir/process_creation.txt"; then
  2502.         echo "Suspicious process creation detected:" >> "$report_dir/report.txt"
  2503.         grep "WARNING" "$report_dir/process_creation.txt" >> "$report_dir/report.txt"
  2504.     else
  2505.         echo "No suspicious process creation detected." >> "$report_dir/report.txt"
  2506.     fi
  2507.    
  2508.     # Run network monitoring
  2509.     echo "Running network monitoring..."
  2510.     # Create temporary BPF program for network monitoring
  2511.     cat > /tmp/report_network_monitor.bt << 'EOF'
  2512. #!/usr/bin/env bpftrace
  2513. #include <linux/socket.h>
  2514. #include <net/sock.h>
  2515.  
  2516. BEGIN
  2517. {
  2518.     printf("Monitoring network activities...\n");
  2519.    
  2520.     // Initialize common suspicious ports table
  2521.     @suspicious_ports[21] = "FTP";
  2522.     @suspicious_ports[22] = "SSH";
  2523.     @suspicious_ports[23] = "Telnet";
  2524.     @suspicious_ports[25] = "SMTP";
  2525.     @suspicious_ports[1080] = "SOCKS";
  2526.     @suspicious_ports[3389] = "RDP";
  2527.     @suspicious_ports[4444] = "Metasploit";
  2528.     @suspicious_ports[5900] = "VNC";
  2529.     @suspicious_ports[8080] = "HTTP Alt";
  2530.     @suspicious_ports[9050] = "Tor";
  2531. }
  2532.  
  2533. // Track outgoing connections
  2534. tracepoint:syscalls:sys_enter_connect
  2535. {
  2536.     $sa = (struct sockaddr *)args->uservaddr;
  2537.     if ($sa->sa_family == AF_INET || $sa->sa_family == AF_INET6) {
  2538.         @connect_attempts[pid, comm] = 1;
  2539.     }
  2540. }
  2541.  
  2542. // Detect successful outbound connections
  2543. tracepoint:syscalls:sys_exit_connect
  2544. /args->ret >= 0 && @connect_attempts[pid, comm]/
  2545. {
  2546.     delete(@connect_attempts[pid, comm]);
  2547.     $sockaddr = (struct sockaddr_in *)curtask->mm->arg_start;
  2548.     $dport = ($sockaddr->sin_port >> 8) | (($sockaddr->sin_port << 8) & 0xff00);
  2549.     $daddr = ntop($sockaddr->sin_addr.s_addr);
  2550.    
  2551.     // Check for suspicious destination ports
  2552.     $port_info = @suspicious_ports[$dport];
  2553.     if ($port_info != 0) {
  2554.         printf("SUSPICIOUS CONNECTION: %s (PID %d, UID %d) connected to %s:%d [%s]\n",
  2555.                comm, pid, uid, $daddr, $dport, str($port_info));
  2556.     }
  2557.    
  2558.     // Log all connections to non-standard web ports
  2559.     if ($dport != 80 && $dport != 443 && $dport < 1024) {
  2560.         printf("NON-STANDARD PORT: %s (PID %d, UID %d) connected to %s:%d\n",
  2561.                comm, pid, uid, $daddr, $dport);
  2562.     }
  2563. }
  2564. EOF
  2565.  
  2566.     # Run for 10 seconds
  2567.     timeout 10 sudo bpftrace /tmp/report_network_monitor.bt > "$report_dir/network_activity.txt" 2>&1
  2568.    
  2569.     echo -e "\n== Network Activity ==" >> "$report_dir/report.txt"
  2570.     if grep -q "SUSPICIOUS CONNECTION\|NON-STANDARD PORT" "$report_dir/network_activity.txt"; then
  2571.         echo "Suspicious network activity detected:" >> "$report_dir/report.txt"
  2572.         grep "SUSPICIOUS CONNECTION\|NON-STANDARD PORT" "$report_dir/network_activity.txt" >> "$report_dir/report.txt"
  2573.     else
  2574.         echo "No suspicious network activity detected." >> "$report_dir/report.txt"
  2575.     fi
  2576.    
  2577.     # Add system summary information
  2578.     echo -e "\n== System Information ==" >> "$report_dir/report.txt"
  2579.     echo "Kernel version: $(uname -r)" >> "$report_dir/report.txt"
  2580.     echo "Hostname: $(hostname)" >> "$report_dir/report.txt"
  2581.     echo "Date: $(date)" >> "$report_dir/report.txt"
  2582.    
  2583.     # List running processes
  2584.     echo -e "\n== Running Processes ==" >> "$report_dir/report.txt"
  2585.     ps -eo pid,ppid,user,stat,pcpu,pmem,comm | head -20 >> "$report_dir/report.txt"
  2586.    
  2587.     # List network connections
  2588.     echo -e "\n== Network Connections ==" >> "$report_dir/report.txt"
  2589.     netstat -tupn | head -20 >> "$report_dir/report.txt"
  2590.    
  2591.     # List loaded kernel modules
  2592.     echo -e "\n== Loaded Kernel Modules ==" >> "$report_dir/report.txt"
  2593.     lsmod | head -20 >> "$report_dir/report.txt"
  2594.    
  2595.     # Create summary section
  2596.     echo -e "\n== Security Assessment ==" >> "$report_dir/report.txt"
  2597.    
  2598.     # Count suspicious events
  2599.     file_issues=$(grep -c "SENSITIVE FILE\|HIDDEN FILE" "$report_dir/file_operations.txt")
  2600.     process_issues=$(grep -c "WARNING" "$report_dir/process_creation.txt")
  2601.     network_issues=$(grep -c "SUSPICIOUS CONNECTION\|NON-STANDARD PORT" "$report_dir/network_activity.txt")
  2602.    
  2603.     total_issues=$((file_issues + process_issues + network_issues))
  2604.    
  2605.     echo "Total suspicious events detected: $total_issues" >> "$report_dir/report.txt"
  2606.     echo "- File operations: $file_issues" >> "$report_dir/report.txt"
  2607.     echo "- Process creation: $process_issues" >> "$report_dir/report.txt"
  2608.     echo "- Network activity: $network_issues" >> "$report_dir/report.txt"
  2609.    
  2610.     # Give overall assessment
  2611.     if [ $total_issues -gt 5 ]; then
  2612.         echo -e "\nHIGH RISK: Multiple suspicious activities detected." >> "$report_dir/report.txt"
  2613.         echo "Recommendation: Investigate system for possible compromise." >> "$report_dir/report.txt"
  2614.     elif [ $total_issues -gt 0 ]; then
  2615.         echo -e "\nMEDIUM RISK: Some suspicious activities detected." >> "$report_dir/report.txt"
  2616.         echo "Recommendation: Monitor system activity and investigate further." >> "$report_dir/report.txt"
  2617.     else
  2618.         echo -e "\nLOW RISK: No suspicious activities detected." >> "$report_dir/report.txt"
  2619.         echo "Recommendation: Continue regular monitoring." >> "$report_dir/report.txt"
  2620.     fi
  2621.    
  2622.     # Clean up temporary files
  2623.     rm -f /tmp/report_file_monitor.bt /tmp/report_process_monitor.bt /tmp/report_network_monitor.bt
  2624.    
  2625.     echo "Activity report generated and saved to: $report_dir/report.txt"
  2626. }
  2627.  
  2628. # Main function
  2629. main() {
  2630.     # Check for required tools
  2631.     if ! check_required_tools; then
  2632.         echo "Please install required tools before continuing."
  2633.         exit 1
  2634.     fi
  2635.    
  2636.     # Check if running as root
  2637.     if [ "$(id -u)" != "0" ]; then
  2638.         echo "This script must be run as root or with sudo."
  2639.         exit 1
  2640.     fi
  2641.    
  2642.     while true; do
  2643.         show_menu
  2644.         read choice
  2645.        
  2646.         case $choice in
  2647.             1) monitor_file_operations ;;
  2648.             2) monitor_network_activities ;;
  2649.             3) monitor_process_chains ;;
  2650.             4) monitor_privilege_escalation ;;
  2651.             5) detect_library_injection ;;
  2652.             6) monitor_syscall_anomalies ;;
  2653.             7) detect_container_escape ;;
  2654.             8) monitor_kernel_modules ;;
  2655.             9) track_file_execution ;;
  2656.             10) monitor_memory_patterns ;;
  2657.             11) track_command_execution ;;
  2658.             12) monitor_dns_exfiltration ;;
  2659.             13) detect_abnormal_process ;;
  2660.             14) monitor_data_patterns ;;
  2661.             15) generate_activity_report ;;
  2662.             16) echo "Exiting..."; exit 0 ;;
  2663.             *) echo "Invalid option. Press Enter to continue..."; read ;;
  2664.         esac
  2665.        
  2666.         echo
  2667.         echo "Operation completed. Press Enter to continue..."
  2668.         read
  2669.     done
  2670. }
  2671.  
  2672. # Start the script
  2673. main
  2674.    
  2675.        
  2676.        
Tags: eBPF
Add Comment
Please, Sign In to add comment