Skip to content

Commit

Permalink
more formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberbuff committed Dec 26, 2023
1 parent b84a4f6 commit 47be37d
Show file tree
Hide file tree
Showing 17 changed files with 134 additions and 126 deletions.
14 changes: 7 additions & 7 deletions Invoke-AtomicRedTeam.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
PowerShellVersion = '5.0'

# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @('powershell-yaml')
RequiredModules = @('powershell-yaml')

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# AtomicClassSchema.ps1 needs to be present in the caller's scope in order for the built-in classes to surface properly.
ScriptsToProcess = @('Private\AtomicClassSchema.ps1','Public\config.ps1')
ScriptsToProcess = @('Private\AtomicClassSchema.ps1', 'Public\config.ps1')

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
Expand All @@ -53,26 +53,26 @@
# Variables to export from this module
VariablesToExport = '*'

NestedModules = @(
NestedModules = @(
"Public\Default-ExecutionLogger.psm1",
"Public\Attire-ExecutionLogger.psm1",
"Public\Syslog-ExecutionLogger.psm1",
"Public\WinEvent-ExecutionLogger.psm1"
)
)

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

PSData = @{

# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('Security', 'Defense')
Tags = @('Security', 'Defense')

# A URL to the license for this module.
LicenseUri = 'https://github.com/redcanaryco/invoke-atomicredteam/blob/master/LICENSE.txt'
LicenseUri = 'https://github.com/redcanaryco/invoke-atomicredteam/blob/master/LICENSE.txt'

# A URL to the main website for this project.
ProjectUri = 'https://github.com/redcanaryco/invoke-atomicredteam'
ProjectUri = 'https://github.com/redcanaryco/invoke-atomicredteam'

# A URL to an icon representing this module.
# IconUri = ''
Expand Down
4 changes: 2 additions & 2 deletions Private/AtomicClassSchema.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class AtomicExecutorBase {
[Bool] $elevation_required

# Implemented to facilitate improved PS object display
[String] ToString(){
[String] ToString() {
return $this.Name
}
}
Expand Down Expand Up @@ -43,7 +43,7 @@ class AtomicTest {
[AtomicExecutorBase] $executor

# Implemented to facilitate improved PS object display
[String] ToString(){
[String] ToString() {
return $this.name
}
}
Expand Down
5 changes: 3 additions & 2 deletions Private/Get-TargetInfo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
$targetHostname = hostname
$targetUser = whoami
if ($IsLinux) { $targetPlatform = "linux" }
elseif ($IsMacOS) { $targetPlatform = "macos" }
else { # windows
elseif ($IsMacOS) { $targetPlatform = "macos" }
else {
# windows
$tmpDir = "$env:TEMP\"
$isElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
Expand Down
2 changes: 1 addition & 1 deletion Private/Invoke-CheckPrereqs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function Invoke-CheckPrereqs ($test, $isElevated, $executionPlatform, $customInp
foreach ($dep in $test.dependencies) {
$executor = Get-PrereqExecutor $test
$final_command = Merge-InputArgs $dep.prereq_command $test $customInputArgs $PathToAtomicsFolder
if($executor -ne "powershell") { $final_command = ($final_Command.trim()).Replace("`n", " && ") }
if ($executor -ne "powershell") { $final_command = ($final_Command.trim()).Replace("`n", " && ") }
$res = Invoke-ExecuteCommand $final_command $executor $executionPlatform $TimeoutSeconds $session
$description = Merge-InputArgs $dep.description $test $customInputArgs $PathToAtomicsFolder
if ($res.ExitCode -ne 0) {
Expand Down
39 changes: 20 additions & 19 deletions Private/Invoke-ExecuteCommand.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,47 @@
$execPrefix = "-c"
$execExe = $executor
if ($executor -eq "command_prompt") {
$execPrefix = "/c";
$execExe = "cmd.exe";
$execCommand = $finalCommand -replace "`n", " & "
$arguments = $execPrefix,"$execCommand"
}
$execPrefix = "/c";
$execExe = "cmd.exe";
$execCommand = $finalCommand -replace "`n", " & "
$arguments = $execPrefix, "$execCommand"
}
else {
$finalCommand = $finalCommand -replace "[\\](?!;)", "`\$&"
$finalCommand = $finalCommand -replace "[`"]", "`\$&"
$execCommand = $finalCommand -replace "(?<!;)\n", "; "
$arguments = "$execPrefix `"$execCommand`""
$finalCommand = $finalCommand -replace "[\\](?!;)", "`\$&"
$finalCommand = $finalCommand -replace "[`"]", "`\$&"
$execCommand = $finalCommand -replace "(?<!;)\n", "; "
$arguments = "$execPrefix `"$execCommand`""

}
}
elseif ($executor -eq "powershell") {
$execCommand = $finalCommand -replace "`"", "`\`"`""
if ($session) {
if ($executionPlatform -eq "windows") {
$execExe = "powershell.exe"
$execExe = "powershell.exe"
}
else {
$execExe = "pwsh"
$execExe = "pwsh"
}
}
else {
$execExe = "powershell.exe"; if ($IsLinux -or $IsMacOS) { $execExe = "pwsh" }
}
if ($execExe -eq "pwsh"){
if ($execExe -eq "pwsh") {
$arguments = "-Command $execCommand"
}else{
}
else {
$arguments = "& {$execCommand}"
}
}
else {
Write-Warning -Message "Unable to generate or execute the command line properly. Unknown executor"
return [PSCustomObject]@{
StandardOutput = ""
ErrorOutput = ""
ExitCode = -1
IsTimeOut = $false
}
StandardOutput = ""
ErrorOutput = ""
ExitCode = -1
IsTimeOut = $false
}
}

# Write-Host -ForegroundColor Magenta "$execExe $arguments"
Expand All @@ -56,7 +57,7 @@
$fp2 = Join-Path $scriptParentPath "Invoke-KillProcessTree.ps1"
invoke-command -Session $session -FilePath $fp
invoke-command -Session $session -FilePath $fp2
$res = invoke-command -Session $session -ScriptBlock { Invoke-Process -filename $Using:execExe -Arguments $Using:arguments -TimeoutSeconds $Using:TimeoutSeconds -stdoutFile "art-out.txt" -stderrFile "art-err.txt" }
$res = invoke-command -Session $session -ScriptBlock { Invoke-Process -filename $Using:execExe -Arguments $Using:arguments -TimeoutSeconds $Using:TimeoutSeconds -stdoutFile "art-out.txt" -stderrFile "art-err.txt" }
}
else {
if ($interactive) {
Expand Down
50 changes: 23 additions & 27 deletions Private/Invoke-Process.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ function Invoke-Process {
[Parameter(Mandatory = $false, Position = 3)]
[Int]$TimeoutSeconds = 120,

[Parameter(Mandatory = $false, Position =4)]
[Parameter(Mandatory = $false, Position = 4)]
[String]$stdoutFile = $null,

[Parameter(Mandatory = $false, Position =5)]
[Parameter(Mandatory = $false, Position = 5)]
[String]$stderrFile = $null
)

Expand All @@ -34,8 +34,7 @@ function Invoke-Process {
$scripBlock =
{
$x = $Event.SourceEventArgs.Data
if (-not [String]::IsNullOrEmpty($x))
{
if (-not [String]::IsNullOrEmpty($x)) {
$Event.MessageData.AppendLine($x)
}
}
Expand All @@ -49,8 +48,7 @@ function Invoke-Process {
# wait for complete
$Timeout = [System.TimeSpan]::FromSeconds(($TimeoutSeconds))
$isTimeout = $false
if (-not $Process.WaitForExit($Timeout.TotalMilliseconds))
{
if (-not $Process.WaitForExit($Timeout.TotalMilliseconds)) {
$isTimeout = $true
Invoke-KillProcessTree $process.id
Write-Host -ForegroundColor Red "Process Timed out after $TimeoutSeconds seconds, use '-TimeoutSeconds' to specify a different timeout"
Expand All @@ -63,12 +61,12 @@ function Invoke-Process {
Unregister-Event -SourceIdentifier $errorEvent.Name

$stdOutString = $stdSb.ToString().Trim()
if($stdOutString.Length -gt 0) {
if ($stdOutString.Length -gt 0) {
Write-Host $stdOutString
}

$stdErrString = $errorSb.ToString().Trim()
if($stdErrString.Length -gt 0) {
if ($stdErrString.Length -gt 0) {
Write-Host $stdErrString
}

Expand All @@ -91,11 +89,12 @@ function Invoke-Process {
# Add a warning in stdoutFile in case of timeout
# problem: $stdoutFile was locked in writing by the process we just killed, sometimes it's too fast and the lock isn't released immediately
# solution: retry at most 10 times with 100ms between each attempt
For($i=0;$i -lt 10;$i++) {
For ($i = 0; $i -lt 10; $i++) {
try {
"<timeout>" | Out-File (Join-Path $WorkingDirectory $stdoutFile) -Append -Encoding ASCII
break # if we're here it means the file wasn't locked and Out-File worked, so we can leave the retry loop
} catch {} # file is locked
}
catch {} # file is locked
Start-Sleep -m 100
}
}
Expand All @@ -108,26 +107,24 @@ function Invoke-Process {
# Get Process result
return [PSCustomObject]@{
StandardOutput = ""
ErrorOutput = ""
ExitCode = $process.ExitCode
ProcessId = $Process.Id
IsTimeOut = $IsTimeout
ErrorOutput = ""
ExitCode = $process.ExitCode
ProcessId = $Process.Id
IsTimeOut = $IsTimeout
}

}

}
finally {
if ($null -ne $process) { $process.Dispose() }
if ($null -ne $stdEvent){ $stdEvent.StopJob(); $stdEvent.Dispose() }
if ($null -ne $errorEvent){ $errorEvent.StopJob(); $errorEvent.Dispose() }
if ($null -ne $stdEvent) { $stdEvent.StopJob(); $stdEvent.Dispose() }
if ($null -ne $errorEvent) { $errorEvent.StopJob(); $errorEvent.Dispose() }
}
}

begin
{
function NewProcess
{
begin {
function NewProcess {
[OutputType([System.Diagnostics.Process])]
[CmdletBinding()]
param
Expand All @@ -149,7 +146,7 @@ function Invoke-Process {
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = $FileName
$psi.Arguments+= $Arguments
$psi.Arguments += $Arguments
$psi.WorkingDirectory = $WorkingDirectory

# Set Process
Expand All @@ -159,8 +156,7 @@ function Invoke-Process {
return $process
}

function GetCommandResult
{
function GetCommandResult {
[OutputType([PSCustomObject])]
[CmdletBinding()]
param
Expand All @@ -180,10 +176,10 @@ function Invoke-Process {

return [PSCustomObject]@{
StandardOutput = $StandardStringBuilder.ToString().Trim()
ErrorOutput = $ErrorStringBuilder.ToString().Trim()
ExitCode = $Process.ExitCode
ProcessId = $Process.Id
IsTimeOut = $IsTimeout
ErrorOutput = $ErrorStringBuilder.ToString().Trim()
ExitCode = $Process.ExitCode
ProcessId = $Process.Id
IsTimeOut = $IsTimeout
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion Private/Replace-InputArgs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ function Get-InputArgs([hashtable]$ip, $customInputArgs, $PathToAtomicsFolder) {
if ($defaultArgs.Keys -contains $key) {
# replace default with user supplied
$defaultArgs.set_Item($key, $customInputArgs[$key])
} else {
}
else {
Write-Verbose "The specified input argument *$key* was ignored as not applicable"
}
}
Expand Down
4 changes: 2 additions & 2 deletions Private/Show-Details.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function Invoke-CleanupDescription(){
function Invoke-CleanupDescription() {
$ret1 = $test.description.ToString().trim() -replace '(?<!\n)\n(?!\n)', ' ' #replace single linefeeds with a space
$ret1 -replace '\n\n', "`n" #replace double linefeeds with a single linefeed
}
Expand All @@ -9,7 +9,7 @@ function Show-Details ($test, $testCount, $technique, $customInputArgs, $PathToA
Write-KeyValue "Technique: " $tName
Write-KeyValue "Atomic Test Name: " $test.name.ToString()
Write-KeyValue "Atomic Test Number: " $testCount
if($test.auto_generated_guid) { Write-KeyValue "Atomic Test GUID: " $test.auto_generated_guid}
if ($test.auto_generated_guid) { Write-KeyValue "Atomic Test GUID: " $test.auto_generated_guid }
Write-KeyValue "Description: " $(Invoke-CleanupDescription $test)

# Attack Commands
Expand Down
4 changes: 2 additions & 2 deletions Private/Write-KeyValue.ps1
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
function Write-KeyValue ($key, $value) {
Write-Host -ForegroundColor Cyan -NoNewline $key
$split = $value -split "(#{[a-z-_A-Z]*})"
foreach ($s in $split){
if($s -match "(#{[a-z-_A-Z]*})"){
foreach ($s in $split) {
if ($s -match "(#{[a-z-_A-Z]*})") {
Write-Host -ForegroundColor Red -NoNewline $s
}
else {
Expand Down
Loading

0 comments on commit 47be37d

Please sign in to comment.