The only method I know how to execute IPsec changes involves calling netsh to do the changes. Is there a method using System.Management and WMI objects directly? If so, what is
1) Exact: WMI.
The EnableIPFilterSec WMI class static method can enable IP security globally across all IP-bound network adapters. With security enabled, security characteristics for any specific adapter can be altered with the EnableIPSec WMI class method. MSDN for the former here:
http://msdn.microsoft.com/en-us/library/aa390381%28VS.85%29.aspx
And see this MSDN entry for information about EnableIPSec and its parameters (that allow you to declare a list of ports and protocols):
http://msdn.microsoft.com/en-us/library/aa390382%28VS.85%29.aspx
Finally, this is a link to the WMI.NET code directory, where there are useful samples of code using System.Management to execute WQL queries.
http://msdn.microsoft.com/en-us/library/ms257338.aspx
NOTE:
If you need to mess around extensively with WQL tests for your ObjectQuery/SelectQuery System.Management objects, as I did, give wbemtest a try. It is the Windows Management Instrumentation tester, and makes writing, testing, and honing WQL for your applications much nicer.
2) Related: Programmatic firewall changes on Vista or later using FirewallAPI, INetFwRule Interface, and anything else one may need.
On Vista or later, using the FirewallAPI.dll is an easy option if you need ipsec functionality but don't care about the legacy PolicyAgent implementation.
I did not realize this was an option at first because I did not know that the Advanced Firewall in Vista and later truly combines IPSec and firewalling within the WFP (Windows Filtering Platform), and keeps legacy IPSec implementations going through PolicyAgent.
This means that using FirewallAPI.dll can give all the functionality of IPSec with the stateful intelligence of the firewall, which is exactly what I wanted. I just add blacklist rules (since blacklist rules take precedence), and add to the blacklist when needed through the API and WFP starts dropping the traffic. Done!
You can't do it with WMI. WMI is restricted to TCP Filtering, meaning blocking ports. Nothing more.
If you are using previous Windows versions, you can either:
a) use a command line tool, in this case either ipseccmd.exe or ipsecpol.exe (W2K), or netsh
or
b) Write the policies to the registry
My guess is that the command line tools do just that: they write values to the registry.
I've been into it for some time now and i didn't find a managed code solution. Too bad that the WFP API is not available in previous windows versions.
In IIS 7 IP restriction can be manipulate directly from config file, without messing with metadatabase. For easy maintenance config file can be split with configSource so that IPSecure section can be saved into it's own file.
Full article:
http://boseca.blogspot.com/2010/12/programmatically-addremove-ip-security.html