PowerShell NetSecurity module (4/7)
Part 4 of the NetSecurity module: creating firewall rules (New-NetFirewallRule, Hyper-V rules), building IPsec from proposals, sets and rules, IPsec DoS protection, batch GPO editing with Open-NetGPO, and the Remove- cmdlets. This is how firewall and IPsec policy is written from PowerShell.
220.1 Why is it used?
- Create firewall rules from a script: allow a port only from one IP, block a port, block wireless inbound.
- Build an IPsec policy (domain isolation, site-to-site tunnel) step by step.
- Edit domain GPO firewall policy in one batch (Open-NetGPO / Save-NetGPO).
- Remove rules and dynamic keyword addresses.
220.2 Where it runs
- Built into Windows 10/11 and Server, PowerShell 5.1 and 7; every cmdlet here needs admin and changes firewall, IPsec or GPO policy.
- The office firewall is company-managed, so none were run (not even -WhatIf); only Get-Command / Get-Help ran. Practical = nftables in Docker.
Get-Command -Module NetSecurity ` -Verb New,Remove,Open | Measure-ObjectGet-Help New-NetFirewallRule$ Get-Command -Module NetSecurity -Verb New,Remove,Open | Measure-ObjectCount : 30$ Get-Help New-NetFirewallRuleNAME New-NetFirewallRuleSYNTAX New-NetFirewallRule -DisplayName <string> [-PolicyStore <string>] [-GPOSession <string>] [-Name <string>] NotApplicable}] [-Platform <string[]>] [-Direction {Inbound | Outbound}] [-Action {NotConfigured | Allow | Block}]REMARKS Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.220.3 New-NetFirewallRule
- Step 1
1.App on the server listens on 8080; clients asha and ravi connect
- Step 2
2.Rule 1: allow 8080 only from asha's IP
- Step 3
3.Rule 2: block 8080 for everyone else
- Step 4
4.asha's packet passes the firewall and reaches the server
- Step 5
5.ravi's packet is dropped at the firewall: timeout
# Example (docs), admin only, NOT run here:New-NetFirewallRule -DisplayName "Block Outbound Port 80" ` -Direction Outbound -LocalPort 80 ` -Protocol TCP -Action BlockNew-NetFirewallRule -DisplayName "Block WINS" ` -Direction Inbound -Action Block -RemoteAddress WINSNew-NetFirewallRule -Name "Block Wireless In" ` -Direction Inbound -InterfaceType Wireless -Action Block| Option | Meaning |
|---|---|
| -DisplayName | Required display name |
| -Direction / -Action | Inbound|Outbound / NotConfigured|Allow|Block |
| -Protocol / -LocalPort / -RemotePort | What traffic matches |
| -LocalAddress / -RemoteAddress | IPs, subnets or keywords like WINS, LocalSubnet |
| -Profile | Any|Domain|Private|Public |
| -Program / -Service / -Package | Limit to an exe, service or Store app |
| -InterfaceType | Any|Wired|Wireless|RemoteAccess |
| -Authentication / -Encryption | Require IPsec auth/encryption (done by a separate IPsec rule) |
| -LocalUser / -RemoteUser / -RemoteMachine | Filter by users and machines |
| -EdgeTraversalPolicy / -OverrideBlockRules | NAT traversal (Teredo) / override block rules |
| -PolicyStore / -GPOSession | Where to create the rule |
- Docs: filter objects (port, address...) are created automatically with every rule.
220.4 Hyper-V firewall: New and Remove
New-NetFirewallHyperVRule -DisplayName "Block Outbound Port 80" ` -Direction Outbound -LocalPorts 80 -Protocol TCP -Action BlockNew-NetFirewallHyperVVMSetting ` -Name '{9E288F02-CE00-4D9E-BE2B-14CE463B0298}' ` -LoopbackEnabled TrueRemove-NetFirewallHyperVRule -DisplayName 'MyServerIPBlock'- Hyper-V VM traffic is filtered by a separate Hyper-V firewall; -VMCreatorId says which VM creator a rule applies to.
- New-NetFirewallHyperVVMSetting: per-VM default actions, loopback, -AllowHostPolicyMerge.
- Docs warning: Remove-NetFirewallHyperVRule without parameters deletes all Hyper-V firewall rules.
220.5 Building IPsec: proposal, set, rule
- Step 1
1.Main mode: client and server authenticate (Phase1AuthSet)
- Step 2
2.They agree on encryption, hash and key exchange (MainModeCryptoSet)
- Step 3
3.Quick mode: how data is protected, ESP or AH (QuickModeCryptoSet)
- Step 4
4.Optional second authentication (Phase2AuthSet)
- Step 5
5.Data travels in encrypted ESP packets
In PowerShell each step = proposal -> set -> rule
| Level | Authentication | Main mode crypto | Quick mode crypto |
|---|---|---|---|
| Proposal | New-NetIPsecAuthProposal | New-NetIPsecMainModeCryptoProposal | New-NetIPsecQuickModeCryptoProposal |
| Set | New-NetIPsecPhase1AuthSet / Phase2AuthSet | New-NetIPsecMainModeCryptoSet | New-NetIPsecQuickModeCryptoSet |
| Rule | New-NetIPsecMainModeRule / New-NetIPsecRule | New-NetIPsecMainModeRule | New-NetIPsecRule |
$mkerbauthprop = New-NetIPsecAuthProposal -Machine -Kerberos$mntlmauthprop = New-NetIPsecAuthProposal -Machine -NTLM$p1Auth = New-NetIPsecPhase1AuthSet -DisplayName "First Machine Auth" ` -Proposal $mkerbauthprop,$mntlmauthprop$ukerbauthprop = New-NetIPsecAuthProposal -User -Kerberos$p2Auth = New-NetIPsecPhase2AuthSet -DisplayName "Second User Auth" ` -Proposal $ukerbauthprop,$unentlmauthprop,$anonyauthprop- An auth proposal is one method: Kerberos, NTLM, certificate (-Cert -Authority), or -PreSharedKey; -Default makes a set the default for all IPsec rules.
- Certificate options: -AccountMapping, -Health, -ExtendedKeyUsage, -Signing RSA|ECDSA256|ECDSA384, -Thumbprint, -SelectionCriteria / -ValidationCriteria, -Proxy (Kerberos proxy).
$proposal2 = (New-NetIPsecMainModeCryptoProposal ` -Encryption AES192 -Hash MD5 -KeyExchange DH14)$mmCryptoSet = New-NetIPsecMainModeCryptoSet ` -DisplayName "Main Mode Crypto Set" ` -Proposal $proposal1,$proposal2,$proposal3New-NetIPsecMainModeRule -DisplayName "Custom Main Mode Rule" ` -MainModeCryptoSet $mmCryptoSet.Name$QMProposal = New-NetIPsecQuickModeCryptoProposal ` -Encapsulation ESP -ESPHash SHA1 -Encryption AES128$QMCryptoSet = New-NetIPsecQuickModeCryptoSet ` -DisplayName "esp:sha1-des3" -Proposal $QMProposal$ESPnoAHQM = New-NetIPsecQuickModeCryptoProposal ` -Encapsulation ESP -ESPHash None -Encryption AES256 ` -MaxKiloBytes 50000 -MaxMinutes 30- Main mode proposal = encryption (DES3, AES128/192/256) + hash (MD5, SHA1, SHA256, SHA384) + key exchange group (DH1...DH24).
- Quick mode proposal = -Encapsulation AH|ESP + -AHHash / -ESPHash + -Encryption, with SA life -MaxKiloBytes / -MaxMinutes.
- Docs: quick mode uses the first proposal both peers have in common.
220.6 New-NetIPsecRule
New-NetIPSecRule -DisplayName "Tunnel from HQ to Dallas Branch" ` -Mode Tunnel -LocalAddress 192.168.0.0/16 ` -RemoteAddress 192.157.0.0/16 ` -LocalTunnelEndpoint 1.1.1.1 -RemoteTunnelEndpoint 2.2.2.2 ` -InboundSecurity Require -OutboundSecurity Require ` -QuickModeCryptoSet $qMCryptoSet.NameNew-NetIPsecRule -DisplayName "Domain Isolation Rule" ` -InboundSecurity Require -OutboundSecurity Request| Setting | Require | Request |
|---|---|---|
| InboundSecurity / OutboundSecurity | Traffic without IPsec is not accepted | Authentication is tried, connection still allowed if it fails |
- -Mode Tunnel connects two networks through tunnel endpoints (site-to-site); -Mode Transport protects host-to-host traffic.
- Domain isolation: inbound Require + outbound Request.
220.7 IPsec DoS protection, Open-NetGPO and Remove
New-NetIPsecDospSetting -Name PubNet-CorpNet ` -PublicInterfaceAliases PubNet -PrivateInterfaceAliases CorpNet ` -IpV6IPsecUnauthRateLimitBytesPerSec 2048$gpoSession = Open-NetGPO -PolicyStore ` castle.contoso.com\Win8ClientFirewallPolicyRemove-NetFirewallRule -Name BlockIMAccess -GPOSession $gpoSessionSave-NetGPO -GPOSession $gpoSessionRemove-NetFirewallDynamicKeywordAddress ` -PolicyStore ContosoPolicyStore -AllAutoResolve- New-NetIPsecDospSetting protects IPv6 IPsec (ESP) traffic at the network edge from DoS; needs at least one public and one private interface; limits like rate limit, idle timeout, max states, DSCP.
- Open-NetGPO opens a local cached copy of a domain GPO; changes go into the copy; Save-NetGPO writes them in one batch.
- If the domain controller is not writeable the batch is not applied; non-domain-admins get an error.
220.8 Linux equivalent: nft add / delete rule (Docker lab)
nft add table inet n220nft add chain inet n220 input \ '{ type filter hook input priority 0;' \ 'policy accept; }'nft add rule inet n220 input \ ip saddr 192.168.240.11 tcp dport 8080 \ counter acceptnft add rule inet n220 input \ tcp dport 8080 counter dropnft -a list table inet n220$ nft -a list table inet n220table inet n220 { # handle 2 chain input { # handle 1 type filter hook input priority filter; policy accept; ip saddr 192.168.240.11 tcp dport 8080 counter packets 0 bytes 0 accept # handle 2 tcp dport 8080 counter packets 0 bytes 0 drop # handle 3 }}[asha] $ nc -w 2 192.168.240.10 8080hello from server[ravi] $ nc -zv -w 2 192.168.240.10 8080nc: connect to 192.168.240.10 port 8080 (tcp) timed out: Operation in progress(exit 1)[server] $ nft -a list chain inet n220 input chain input { # handle 1 type filter hook input priority filter; policy accept; ip saddr 192.168.240.11 tcp dport 8080 counter packets 8 bytes 420 accept # handle 2 tcp dport 8080 counter packets 2 bytes 120 drop # handle 3 }nft delete rule inet n220 input handle 3# ravi 192.168.240.12nc -zv -w 2 192.168.240.10 8080nft delete table inet n220[ravi] $ nc -zv -w 2 192.168.240.10 8080Connection to 192.168.240.10 8080 port [tcp/http-alt] succeeded![server] $ nft delete table inet n220[host] module names + sizes before vs afteridentical: 28 modules, no module loaded or unloaded- New-NetFirewallRule = nft add rule; Remove-NetFirewallRule = nft delete rule ... handle N.
- IPsec ESP is a not-loaded module in the lab kernel (CONFIG_INET_ESP=m), so IPsec was shown from the docs only.
220.9 Common mistakes
- Running Remove-NetFirewallHyperVRule (or other Remove- cmdlets) without a selector: all rules get deleted permanently.
- Thinking Open-NetGPO edits the live GPO: nothing changes until Save-NetGPO, and only with a writeable DC.
- Setting -Authentication Required on a firewall rule without an IPsec rule that actually authenticates.
- Using Require on outbound during rollout and breaking connections to non-IPsec peers; Request is the safe start.
220.10 Interview tips
- Allow 8080 from one IP only: New-NetFirewallRule -Direction Inbound -Protocol TCP -LocalPort 8080 -RemoteAddress <IP> -Action Allow; the profile's default inbound action (Block) keeps others out.
- On domain machines put such rules in Group Policy via Open-NetGPO / Save-NetGPO.
- IPsec build order: proposal -> set -> rule (auth, main mode crypto, quick mode crypto).
- Linux: nft add rule / nft delete rule handle N.