Protect (Defend)

(Updated: 2019-09-06) - Windows - Disable/Stop Services - Windows - Host System Firewalls - Windows - Passwords - Windows - Host File - Windows - Whitelist - Windows - Application Restrictions - Windows - IPSEC - Windows - Active Directory - Windows - Stand Alone - Linux - Disable / Stop Services - Linux - Host System Firewalls - Linux - Passwords - Linux - Host File - Linux - Whitelist - Linux - IPSEC -

Windows - Disable/Stop Services

Get a list of services and disable or stop:

C:\> sc query 
C:\> sc config "<SERVICE NAME> start= disabled
C:\> sc stop "<SERVICE NAME>" 
C:\> wmic service where name='<SERVICE NAME>' call ChangeStartmode Disabled 


Windows - Host System Firewalls

Show all rules:

C:\> netsh advfirewall firewall show rule name=all

Set firewall on/off:

C:\> netsh advfirewall set currentprofile state on 
C:\> netsh advfirewall set currentprofile firewallpolicy blockinboundalways,allowoutbound 
C:\> netsh advfirewaIl set publicprofile state on 
C:\> netsh advfirewall set privateprofile state on 
C:\> netsh advfirewall set domainprofile state set 
C:\> netsh advfirewall set allprofile state on 
C:\> netsh advfirewall set allprofile state off 

Set firewall rules examples:

C:\> netsh advfirewall firewall add rule name="Open Port 80" dir=in action=allow protocol=TCP localport=80 
C:\> netsh advfirewall firewall add rule name="My Application" dir=in action=allow 
     program="C:\MyApp\MyApp.exe" enable=yes 
C:\> netsh advfirewall firewall add rule name="My Application" dir=in action=allow 
     program="C:\MyApp\MyApp.exe" enable=yes remoteip=157.60.0.1,172.16.0.60/16,LocalSubnet profile=domain 
C:\> netsh advfirewall firewall add rule name="My Application" dir=in action=allow 
     program="C:\MyApp\MyApp.exe" enable=yes remoteip=157.60.0.1,172.16.0.0/16 LocalSubnet profile=domain 
C:\> netsh advfirewall firewall add rule name="My Application" dir=in action=allow 
     program="C:\MyApp\MyApp.exe" enable=yes remoteip=157.60.0.1,172.16.0.0/16,LocalSubnet profile=private 
C:\> netsh advfirewall firewall delete rule name=rule name program="C:\MyApp\MyApp.exe" 
C:\> netsh advfirewall firewall delete rule name=rule name protocol=udp localport=500 
C:\> netsh advfirewall firewall set rule group="remote desktop" new enable=Yes profile=domain 
C:\> netsh advfirewall firewall set rule group="remote desktop" new enable=No profile=public 

Setup logging location:

C:\> netsh advfirewall set currentprofile logging C:\<LOCATION>\<FILE NAME> 

Windows firewall log location and settings:

C:\> more %systemroot%\system32\LogFiles\Firewall\pfirewall.log 
C:\> netsh advfirewall set allprofile logging maxfilesize 4096
C:\> netsh advfirewall set allprofile logging droppedconnections enable
C:\> netsh advfirewall set allprofile logging allowedconnections enable

Display Firewall logs:

PS C:\> Get-Content $env:systemroot\system32\LogFiles\Firewall\pfirewall.log


Windows - Passwords

Change Password:

C:\> net user <USER NAME> * /domain
C:\> net user <USER NAME> <NEW PASSWORD>

Change password remotely:

Ref. https://technet.microsoft.com/en-us/sysinternals/bb8977543

C:\> pspasswd.exe \\<IP ADDRESS OR NAME> -u <REMOTE USER NAME> -p <NEW PASSWORD>

Change password remotely:

PS C:\> pspasswd.exe \\<IP ADDRESS OR NAME>


Windows - Host File

Flush DNS of malicious domain/IP:

C:\> ipconfig /flushdns

Flush NetBIOS cache of host/IP:

C:\> nbtstat -R

Add new malicious domain to hosts file, and route to localhost:

C:\> echo 127.0.0.1 <MALICIOUS DOMAIN> >> 
C:\Windows\System32\drivers\etc\hosts 

Check if hosts file is working, by sending ping to 127.0.0.1:

C:\> ping <MALICIOUS DOMAIN> -n 1


Windows - Whitelist

Use a Proxy Auto Config(PAC) file to create Bad or IP List (IE, Firefox, Chrome):

function FindProxyForURL(url, host) {
// Send bad DNS name to the proxy 
if (dnsDomainIs(host, ".badsite.com")) 
return "PROXY http://127.0.021:8080";
// Send bad IPs to the proxy 
if (isInNet(myIpAddress(), "222.222.222.222" "2552255.255.0")) 
return "PROXY http://127.0.0.1:8080"; 
// All other traffic bypass proxy 
return "DIRECT";
} 


Windows - Application Restrictions

AppLocker Server 2008 R2 or Windows 7 or higher:

Using GUI Wizard configure:

• Executable Rules (.exe, .com) 
• DLL Rules (mdll, .ocx) 
• Script Rules (.psl, .bat, .cmd, .vbs, .js) 
• Windows Install Rules (.msi, .msp, .mst) 

Steps to employ AppLocker (GUI is needed for digital signed app restrictions):

Step 1: Create a new GPO. 
Step 2: Right—click on it to edit, and then navigate through Computer Configuration, Policies, 
        Windows Settings, Security Settings, Application Control Policies and AppLocker. 
Click Configure Rule Enforcement. 
Step 3: Under Executable Rules, check the Configured box and then make sure Enforce Rules is selected 
        from the drop—down box. Click OK. 
Step 4: In the left pane, click Executable Rules. 
Step 5: Right—click in the right pane and select Create New Rule. 
Step 6: On the Before You Begin screen, click Next. 
Step 7: On the Permissions screen, click Next. 
Step 8: On the Conditions screen, select the Publisher condition and click Next. 
Step 9: Click the Browse button and browse to any executable file on your system. It doesn't matter which. 
Step 10: Drag the slider up to Any Publisher and then click Next. 
Step 11: Click Next on the Exceptions screen. 
Step 12: Name policy, Example "Only run executables that are signed" and click Create. 
Step 13: If this is your first time creating AppLocker policy, Windows will prompt you to default rule, click Yes. 
Step 14: Ensure Application Identity Service is Running. 

C:\> net start AppIDSvc 
C:\> REG add "HKLM\SYSTEM\CurrentControlSet\services\AppIDSW /v Start /t REG_DWORD /d 2 /f 

Step 15: Changes require reboot. 

C:\ shutdown.exe /r 
C:\ shutdownsexe /r /m \\<IP ADDRESS OR COMPUTER NAME> /f 

Add the AppLocker cmdlets into PowerShell:

PS C:\> import-module AppLocker 

Gets the file information for all of the executable files and scripts in the directory

C:Windows\System32: 
PS C:\> Get-AppLockerFileInformation -Directory C:Windows\System32\ -Recurse -FileType Exe, Script 

Create a AppLocker Policy that allow rules for all of the executable files in C:Windows\System32:

PS C:\> Get-ChildItem C:\Windows\System32\*.exe. Get-AppLockerFileInformation | New-AppLockerPolicy -RuleType Publisher, 
Hash -User Everyone - RuleNamePrefix System32 

Sets the local AppLocker policy to the policy specified in C:\Policy.xml:

PS C:\> Set-AppLockerPolicy -XMLPolicy C:\Policyaxml 

Uses the AppLocker policy in C:\Policy.xml to test whether calc.exe and notepad.exe are allowed to run for users who are members of the Everyone group. If you do not specify a group, the Everyone group is used by default:

PS C:\> Test-AppLockerPolicy -XMLPolicy C:\Policy.xml -Path C:\Windows\System32\calc.exe, 
C:\Windows\System32\notepad.exe -User Everyone 

Review how many times a file would have been blocked from running if rules were enforced:

PS C:\> GetsAppLockerFileInformation -EventLog -Logname "MicrosoftsWindowssAppLocker\EXE and DLL" 
- EventType Audited -Statistics 

Creates a new AppLocker policy from the audited events in the local Microsoft-Windows-AppLocker/EXE and DLL event log, applied to <GROUP> and current AppLocker policy will be overwritten:

PS C:\> GetsAppLockerFileInformation -EventLog -LogPath "Microsoft-Windows-AppLocker/EXE and DLL" - EventType Audited | 
New-AppLockerPolicy -RuleType Publisher,Hash -User domain\<GROUP> IgnoreMissingFileInformation 
Set-AppLockerPolicy LDAP "LDAP://<DC>.<DOMAIN>.com/CN={31B2F340-016D-11D2-945F-00C04FB984F9},CM=Policies,CN=System,DC=<DOMAIN>,DC=com" 

Export the local AppLocker policy, comparing User's explicitly denied access to run, and output text file:

PS C:\> Get-AppLockerPolicy -Local | Test-AppLockerPolicy -Path C:\Windows\System32\*.exe -User domain\<USER NAME> 
-Filter Denied | Format-List -Property Path > C:\DeniedFiles.txt 

GridView list of any local rules applicable:

PS C:\> Get-AppLockerPoIicy —Local —Xml | Out-GridView 


Windows - IPSEC

Create a IPSEC Local Security Policy, applied to any connection, any protocol, and using a preshared key:

C:\> netsh ipsec static add filter filterlist=MyIPsecFilter srcaddr=Any dstaddr=Any protocol=ANY 
C:\> netsh ipsec static add filteraction name=MyIPsecAction action=negotiate 
C:\> netsh ipsec static add policy name=MyIPsecPolicy assign=yes 
C:\> netsh ipsec static add rule name=MyIPsecRule policy=MyIPsecPolicy filterlist=MyIPsecFilter 
filteraction=MyIPsecAction conntype=all activate=yes psk=<PASSWORD> 

Add rule to allow web browsing port 80(HTTP) and 443(HTTPS) over IPSEC:

C:\> netsh ipsec static add filteraction name=Allow action=permit 
C:\> netsh ipsec static add filter filterlist=WebFilter srcaddr=Any dstaddr=Any protocol=TCP dstport=80 
C:\> netsh ipsec static add filter filterlist=WebFilter srcaddr=Any dstaddr=Any protocol=TCP dstport=443 
C:\> netsh ipsec static add rule name=WebAllow policy=MyIPsecPolicy filterlist=WebFilter filteraction=Allow 
    conntype=all activate=yes psk=<PASSWORD> 

Shows the IPSEC Local Security Policy with name "MyIPsecPolicy":

C:\> netsh ipsec static show policy name=MyIPsecPolicy 

Stop or Unassign a IPSEC Policy:

C:\> netsh ipsec static set policy name=MyIPsecPolicy 

Create a IPSEC Advance Firewall Rule and Policy and preshared key from and to any connections:

C:\> netsh advfirewall consec add rule name="IPSEC" endpointl=any endPoint2=any action=requireinrequireout
  qmsecmethods=defautt 

Require IPSEC preshared key on all outgoing requests:

C:\> netsh advfitewall firewall add rule name="IPSEC_Out" dir=out action=allow enable=yes profile=any localip=any 
remoteip=any protocol=any interfacetype=any security=authenticate 

Create a rule for web browsing:

C:\> netsh advfirewall firewall add rule name="Allow Outbound Port 80" dir=out localport=80 protocol=TCP action=allow 

Create a rule for DNS:

C:\> netsh advfirewall firewall add rule name="Allow Outbound Port 53" dir=out localport=53 protocol=UDP action=allow 

Delete ISPEC Rule:

C:\> netsh advfirewall firewall delete rule name="IPSEC_RULE" 


Windows - Active Directory

Get and force new policies:

C:\> gpupdate /force 
C:\> gpupdate /sync 

Audit Success and Failure for user Bob:

C:\> auditpol /set /user:bob /category:"Detailed Tracking" /include /success:enable /failure:enable 

Create an Organization Unit to move suspected or infected users and machines:

C:\> dsadd ou <QUARANTINE BAD OU> 

Move an active directory user object into NEW GROUP:

PS C:\> Move-ADObject 'CN=<USER NAME>,CN=<OLD USER GROUP>,DC=<OLD DOMAIN>,DC=<0LD EXTENSION> 
  -TargetPath 'OU=<NEW USER GROUP>,DC=<OLD DOMAIN>,DC=<OLD EXTENSION>'

Alt Option:

C:\> dsmove "CN=<USER NAME>,OU=<OLD USER OU>,DC=<OLD DOMAIN>,DC=<OLD EXTENSION>" -newparent 
OU=‹NEW USER GROUP>,DC=<OLD DOMAIN>,DC=<OLD 


Windows - Stand Alone System

Disallow running a .exe file:

C:\> reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" /v DisallowRun /t 
  REG_DWORD /d "00000001" /f 

C:\> reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun" /v badfile.exe /t 
REG_SZ /d <BAD FILE NAME>.exe /f 

Disable Remote Desktop:

C:\> reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /f /v fDenyTSConnections /t REGJWORD /d 1 

Send NTLMv2 response only/refuse LM and NTLM:

(Windows 7 default)

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa\ /v lmcompatibilitylevel /t REG_DWORD /d 5 /f 

Restrict Anonymous Access:

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v restrictanonymous /t REG_DWORD /d 1 /f 

Do not allow anonymous enumeration of SAM accounts and shares:

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v restrictanonymoussam /t REG_DWORD /d 1 /f 

Disable IPV6:

C:\> reg add HKLM\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters /v DisabledComponents REG_DWORD /d 255 /f 

Disable sticky keys:

C:\> reg add "HKCU\Control Panel\Accessibility\StickyKeys" /v Flags /t REG_SZ /d 506 /f 

Disable Toggle Keys:

C:\> reg add "HKCCU\Control Panel\Accessibility\ToggleKeys" /v Flags /t REG_SZ /d 58 /f 

Disable Filter Keys:

C:\> reg add "HKCU\Control Panel\Accessibility\Keyboard Response" /v Flags /t REG_SZ /d 122 /f 

Disable On-screen Keyboard:

C:\> reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI /f /v ShowTabletKeyboard /t REG_DWORD /d 0

Disable Administrative Shares - Workstations:

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters /f /v AutoShareWks /t REG_DWORD /d 0 

Disable Administrative Shares - Servers

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters /f /v AutoShareServer /t REG_DWORD /d 0

Remove Creation of Hashes Used to Pass the Hash Attack (Requires password reset and reboot to purge old hashes):

C:\> reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa /f /v NoLMHash /t REG_DWORD /d 1 

To Disable Registry Editor: (High Risk)

C:\> reg add HKCU\Software\Microsoft\VVindows\CurrentVersion\Policies\System /v DisableRegistryTools /t REG_DWORD /d 1 /f 

Disable IE Password Cache:

C:\> reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings /v DisablePasswordCaching /t REG_DWORD /d 1 /f 

Disable CMD prompt:

C:\> reg add HKCU\Software\Policies\Microsoft\Windows\System /v DisableCMD /t REG_DWORD /d 1 /f 
 

Disable Admin credentials cache on host when using RDP:

C:\> reg add HKLM\System\CurrentControlSet\Contro1\Lsa /v DisableRestrictedAdmin /t REG_DWORD /d 0 /f 

Do not process the run once list:

C:\> reg add HKLM\Software\MicrosoftWindows\CurrentVersion\Policies\Explorer /v DisableLocalMachineRunOnce /t REG_DWORD /d 1
C:\> reg add HKCU\Software\MicrosoftWindows\CurrentVersion\Policies\Explorer /v DisableLocalMachineRunOnce /t REG DWORD /d 1

Require User Access Control (UAC) Permission:

C:\> reg add HKLM\SOFTWARE\MicrosoftWindows\CurrentVersion\Policies\System /v EnableLUA /t REGJWORD /d 1 /f 

Change password at next logon:

PS C:\> Set-ADAccountPassword <USER> -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $True 

Change password at next Logon for OU Group:

PS C:\> Get-ADuser -filter "department -eq '<OU GROUP>' -AND enabled -eq 'True'" | Set-ADuser -ChangePasswordAtLogon $True 

Enabled Firewall logging:

C:\> netsh firewall set logging droppedpackets connections = enable 


Linux - Disable / Stop Services

Services information:

# service --status—all 
# ps -ef
# ps -aux

Get a list of upstart jobs:

# initctl list 

Example of start, stop, restart a service Ubuntu:

# /etc/init.d/apache2 start 
# /etc/init.d/apache2 restart 
# /etc/init.d/apache2 stop (stops only until reboot) 
# service mysql start  
# service mysql restart 
# service mysql stop (stops only until reboot) 

List all Upstart services:

# ls /etc/init/*.conf 

Show if a program is managed by upstart and the process ID:

# status ssh 

If not managed by upstart:

# update—rcpd apache2 disable 
# service apache2 stop 


Linux - Host System Firewalls

Export existing iptables firewall rules:

# iptables-save > firewall.out 

Edit firewall rules and chains in firewall.out and save the file:

# vi firewall.out 

Apply iptables:

# iptables-restore < firewall.out 

Example iptables commands (IP, IP Range, Port Blocks):

# iptables -A INPUT -s 10.10.10.10 -j DROP 
# iptables -A INPUT -s 10.10.10.0/24 -j DROP 
# iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP 
# iptables -A INPUT -p tcp --dport ssh -j DROP 

Block all connections:

# iptables-policy INPUT DROP 
# iptables-policy OUTPUT DROP 
# iptables-policy FORWARD DROP 

Log all denied iptables rules:

# iptables -I INPUT 5 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7 

Save all current iptables rules:

Ubuntu:

# /etc/init.d/iptables save 
# /sbin/service iptables save 

RedHat / CentOS:

# /etc/init.d/iptab1es save 
# /sbin/iptables-save 

List all current iptables rules:

# iptables —L 

Flush all current iptables rules:

# iptables —F 

Start/Stop iptables service:

# service iptables start 
# service iptables stop 

Start/Stop ufw service:

# ufw enable 
# ufw disable 

Start/Stop ufw logging:

# ufw logging on 
# ufw logging off 

Backup all current ufw rules:

# cp /lib/ufw/{user.rules,user6.rules} /<BACKUP LOCATION> 
# cp /lib/ufw/{user.rules,user6.rules} ./ 

Example uncomplicated firewall (ufw) Commands (IP, IP range, Port blocks):

# ufw status verbose 
# ufw delete <RULE #> 
# ufw allow for <IP ADDRESS> 
# ufw allow all 80/tcp 
# ufw allow all ssh 
# ufw deny from <BAD IP ADDRESS> proto udp to port 443 


Linux - Passwords

Change password:

$ passwd (For current user) 
$ passwd bob (For user Bob) 
$ sudo su passwd (For root) 


Linux - Host File

Add new malicious domain to hosts file, and route to localhost:

# echo 127.0.0.1 <MALICIOUS DOMAIN> » /etc/hosts 

Check if hosts file is working, 127.0.0.1:

# ping —c 1 <MALICIOUS DOMAIN> 

Ubuntu/Debian DNS cache flush:

# /etc/init.d/dns—clean start 

Flush nscd DNS cache four ways:

# /etc/init.d/nscd restart 
# service nscd restart 
# service nscd reload 
# nscd -i hosts 

Flush dnsmasq DNS cache:

# /etc/init.d/dnsmasq restart 


Linux - Whitelist

Use a Proxy Auto Config(PAC) file to create bad URL or IP List:

function FindProxyForURL(url, host) {
// Send bad DNS name to the proxy 
if (dnsDomainIs(host, ".badsite.com")) 
return "PROXY http://127.0.0.1:8080"; 
// Send bad IPs to the proxy 
if (isInNet(myIpAddress(), "222.222.222.222", "255.255.255.0")) 
return "PROXY http://127.0.0.1:8080"; 
// Alt other traffic bypass proxy return "DIRECT"; 
} 


Linux - IPSEC

Allow firewall to pass IPSEC traffic:

# iptables -A INPUT -p esp -j ACCEPT 
# iptables -A INPUT -p ah -j ACCEPT 
# iptables -A INPUT -p udp --dport 500 -j ACCEPT 
# iptables -A INPUT -p udp --dport 4500 -j ACCEPT 

Pass IPSEC traffic:

Step 1: Install Racoon utility on <HOST1 IP ADDRESS> and <HOST2 IP ADDRESS> to enable IPSEC tunnel in Ubuntu. 
# apt-get install racoon 

Step 2: Choose direct then edit /etc/ipsec-tools.conf on <HOST1 IP ADDRESS> and <HOST2 IP ADDRESS>. 
flush; 
spdflush;

spdadd <HOST1 IP ADDRESS> <HOST2 IP ADDRESS> any —P 
out ipsec  
  esp/transport//require; 
spdadd <HOST2 IP ADDRESS> <HOST1 IP ADDRESS> any —P 
in ipsec 
  esp/transport//require; 

Step 3: Edit /etc/racoon/racoon.conf on <HOST1 IP ADDRESS> and <HOST2 IP ADDRESS>. 
log notify; 
path pre_shared_key "/etc/racoon/psk,txt"; 
path certificate "/etc/racoon/certs"; 
remote anonymous {
  exchange mode main, aggressive; 
  proposal {
    encryption_algorithm aes_256; 
    hashalgorithmsha256; 
    authentication method 
pre_shared_key;
    dh_group modp1024;
  }
  generate_policy off; 
} 
sainfo anonymous {
  pfs_group 2; 
  encryption_algorithm aes_256; 
  authentication_algorithm hmac_sha256; 
  compression_algorithm deflate; 
}

Step 4: Add preshared key to both hosts. 
On HOST1: 
# echo <HOST2 IP ADDRESS> <PRESHARED PASSWORD> 
>>/etc/racoon psk.txt 

On HOST2: 
# echo <HOST1 IP ADDRESS> <PRESHARED PASSWORD> 
»ifetc/racoon/psk.txt 

Step 5: Restart service on both systems. 
# service setkey restart 

Check security associations, configuration and polices:

# setkey -D
# setkey -DP