Initial implementation of FirewallApi.dll. Yes, it is in VB instaead of C#. Ony VB support parameterized properties and the underlying COM objects have these. Plus, it was a fun experiment.

pull/180/head
dahall 2020-09-18 21:28:36 -06:00
parent ad3189ebb5
commit 6f0789ce03
10 changed files with 4122 additions and 1 deletions

1
.gitignore vendored
View File

@ -253,3 +253,4 @@ ModelManifest.xml
UndefinedMethods.txt
/1.1.0 Changes.txt
~*.cs
*.zip

View File

@ -1,6 +1,7 @@
<Project>
<PropertyGroup>
<DocumentationFile>$(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<DocumentationFile>\bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
<!--<DocumentationFile>$(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>-->
<!--<DefaultItemExcludes>$(DefaultItemExcludes);**\~*.cs</DefaultItemExcludes>-->
</PropertyGroup>
<PropertyGroup Condition=" $(TargetFramework.StartsWith('netstandard')) Or $(TargetFramework.StartsWith('netcore')) Or '$(TargetFramework)' == 'net45' ">

View File

@ -0,0 +1,313 @@
Partial Public Module FirewallApi
''' <summary>The <c>NET_FW_ACTION</c> enumerated type specifies the action for a rule or default setting.</summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_ACTION_")>
Public Enum NET_FW_ACTION
''' <summary>Block traffic.</summary>
NET_FW_ACTION_BLOCK
''' <summary>Allow traffic.</summary>
NET_FW_ACTION_ALLOW
''' <summary>Maximum traffic.</summary>
NET_FW_ACTION_MAX
End Enum
''' <summary>
''' The <c>NET_FW_AUTHENTICATE_TYPE</c> enumerated type specifies the type of authentication which must occur in order for traffic to be allowed..
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_AUTHENTICATE_TYPE_")>
Public Enum NET_FW_AUTHENTICATE_TYPE
''' <summary>No security check is performed.</summary>
NET_FW_AUTHENTICATE_NONE
''' <summary>
''' The traffic is allowed if it is IPsec-protected with authentication and no encapsulation protection. This means that the peer is
''' authenticated, but there is no integrity protection on the data.
''' </summary>
NET_FW_AUTHENTICATE_NO_ENCAPSULATION
''' <summary>The traffic is allowed if it is IPsec-protected with authentication and integrity protection.</summary>
NET_FW_AUTHENTICATE_WITH_INTEGRITY
''' <summary>
''' The traffic is allowed if its is IPsec-protected with authentication and integrity protection. In addition, negotiation of
''' encryption protections on subsequent packets is requested.
''' </summary>
NET_FW_AUTHENTICATE_AND_NEGOTIATE_ENCRYPTION
''' <summary>
''' The traffic is allowed if it is IPsec-protected with authentication, integrity and encryption protection since the very first packet.
''' </summary>
NET_FW_AUTHENTICATE_AND_ENCRYPT
End Enum
''' <summary>
''' The <c>NET_FW_EDGE_TRAVERSAL_TYPE</c> enumerated type specifies the conditions under which edge traversal traffic is allowed.
''' </summary>
''' <remarks>
''' In order for Windows Firewall to dynamically allow edge traversal traffic, the application must use the IPV6_PROTECTION_LEVEL socket
''' option on the listening socket and set it to <c>PROTECTION_LEVEL_UNRESTRICTED</c> only in the cases where edge traversal traffic
''' should be allowed. The Windows Firewall rule added for the application must then set its edge traversal option to
''' <c>NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP</c> or <c>NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_USER</c>.
''' </remarks>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_EDGE_TRAVERSAL_TYPE_")>
Public Enum NET_FW_EDGE_TRAVERSAL_TYPE
''' <summary>
''' Edge traversal traffic is always blocked.This is the same as setting the EdgeTraversal property using INetFwRule to VARIANT_FALSE.
''' </summary>
NET_FW_EDGE_TRAVERSAL_TYPE_DENY
''' <summary>
''' Edge traversal traffic is always allowed.This is the same as setting the EdgeTraversal property using INetFwRule to VARIANT_TRUE.
''' </summary>
NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW
''' <summary>
''' Edge traversal traffic is allowed when the application sets the IPV6_PROTECTION_LEVEL socket option to
''' PROTECTION_LEVEL_UNRESTRICTED. Otherwise, it is blocked.
''' </summary>
NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP
''' <summary>
''' The user is prompted whether to allow edge traversal traffic when the application sets the IPV6_PROTECTION_LEVEL socket option
''' to PROTECTION_LEVEL_UNRESTRICTED. If the user chooses to allow edge traversal traffic, the rule is modified to defer to the
''' application's settings.If the application has not set the IPV6_PROTECTION_LEVEL socket option to PROTECTION_LEVEL_UNRESTRICTED,
''' edge traversal traffic is blocked.In order to use this option, the firewall rule must have both the application path and
''' protocol scopes specified. This option cannot be used if port(s) are defined.
''' </summary>
NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_USER
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_IP_PROTOCOL</c> enumeration type specifies the Internet protocol.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_IP_PROTOCOL_")>
Public Enum NET_FW_IP_PROTOCOL
''' <summary/>
NET_FW_IP_PROTOCOL_ANY = &H100
''' <summary>Transmission Control Protocol.</summary>
NET_FW_IP_PROTOCOL_TCP = 6
''' <summary>User Datagram Protocol.</summary>
NET_FW_IP_PROTOCOL_UDP = &H11
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_IP_VERSION</c> enumerated type specifies the IP version for a port.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_IP_VERSION_")>
Public Enum NET_FW_IP_VERSION
''' <summary>The port supports IPv4.</summary>
NET_FW_IP_VERSION_V4
''' <summary>The port supports IPv6.</summary>
NET_FW_IP_VERSION_V6
''' <summary>The port supports either version of IP.</summary>
NET_FW_IP_VERSION_ANY
''' <summary>This value is used for boundary checking only and is not valid for application programming.</summary>
NET_FW_IP_VERSION_MAX
End Enum
''' <summary>The NET_FW_MODIFY_STATE enumerated type specifies the effect of modifications to the current policy.</summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_MODIFY_STATE_")>
Public Enum NET_FW_MODIFY_STATE
''' <summary>Changing or adding a firewall rule or firewall group to the current profile will take effect.</summary>
NET_FW_MODIFY_STATE_OK
''' <summary>
''' Changing or adding a firewall rule or firewall group to the current profile will not take effect because the profile is
''' controlled by the group policy.
''' </summary>
NET_FW_MODIFY_STATE_GP_OVERRIDE
''' <summary>
''' Changing or adding a firewall rule or firewall group to the current profile will not take effect because unsolicited inbound
''' traffic is not allowed.
''' </summary>
NET_FW_MODIFY_STATE_INBOUND_BLOCKED
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_POLICY_TYPE</c> enumerated type specifies the type of policy.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_POLICY_TYPE_")>
Public Enum NET_FW_POLICY_TYPE
''' <summary>Policy type is group.</summary>
NET_FW_POLICY_GROUP
''' <summary>Policy type is local.</summary>
NET_FW_POLICY_LOCAL
''' <summary>Policy type is effective.</summary>
NET_FW_POLICY_EFFECTIVE
''' <summary>Used for boundary checking only. Not valid for application programming.</summary>
NET_FW_POLICY_TYPE_MAX
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_PROFILE_TYPE</c> enumerated type specifies the type of profile.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_PROFILE_TYPE_")>
Public Enum NET_FW_PROFILE_TYPE
''' <summary>Profile type is domain.</summary>
NET_FW_PROFILE_DOMAIN
''' <summary>Profile type is standard.</summary>
NET_FW_PROFILE_STANDARD
''' <summary>Profile type is current.</summary>
NET_FW_PROFILE_CURRENT
''' <summary>Used for boundary checking only. Not valid for application programming.</summary>
NET_FW_PROFILE_TYPE_MAX
End Enum
''' <summary>The <c>NET_FW_PROFILE_TYPE2</c> enumerated type specifies the type of profile.</summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_PROFILE_TYPE2_")>
<Flags>
Public Enum NET_FW_PROFILE_TYPE2
''' <summary/>
NET_FW_PROFILE2_ALL = &H7FFFFFFF
''' <summary>Profile type is domain.</summary>
NET_FW_PROFILE2_DOMAIN = 1
''' <summary>Profile type is private. This profile type is used for home and other private network types.</summary>
NET_FW_PROFILE2_PRIVATE = 2
''' <summary>Profile type is public. This profile type is used for public Internet access points.</summary>
NET_FW_PROFILE2_PUBLIC = 4
End Enum
''' <summary>The <c>NET_FW_RULE_CATEGORY</c> enumerated type specifies the firewall rule category.</summary>
''' <remarks>For more information about using <c>NET_FW_RULE_CATEGORY</c>, download the Windows Firewall and User Facing Impact document.</remarks>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_RULE_CATEGORY_")>
Public Enum NET_FW_RULE_CATEGORY
''' <summary>Specifies boot time filters.</summary>
NET_FW_RULE_CATEGORY_BOOT
''' <summary>Specifies stealth filters.</summary>
NET_FW_RULE_CATEGORY_STEALTH
''' <summary>Specifies firewall filters.</summary>
NET_FW_RULE_CATEGORY_FIREWALL
''' <summary>Specifies connection security filters.</summary>
NET_FW_RULE_CATEGORY_CONSEC
''' <summary>Maximum value for testing purposes.</summary>
NET_FW_RULE_CATEGORY_MAX
End Enum
''' <summary>The <c>NET_FW_RULE_DIRECTION</c> enumerated type specifies the direction of traffic to which a rule applies.</summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_RULE_DIRECTION_")>
Public Enum NET_FW_RULE_DIRECTION
''' <summary>The rule applies to inbound traffic.</summary>
NET_FW_RULE_DIR_IN = 1
''' <summary>The rule applies to outbound traffic.</summary>
NET_FW_RULE_DIR_OUT = 2
''' <summary>This value is used for boundary checking only and is not valid for application programming.</summary>
NET_FW_RULE_DIR_MAX = 3
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_SCOPE</c> enumerated type specifies the scope of addresses from which a port can listen.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_SCOPE_")>
Public Enum NET_FW_SCOPE
''' <summary>Scope is all.</summary>
NET_FW_SCOPE_ALL
''' <summary>Scope is local subnet only.</summary>
NET_FW_SCOPE_LOCAL_SUBNET
''' <summary>Scope is custom.</summary>
NET_FW_SCOPE_CUSTOM
''' <summary>Used for boundary checking only. Not valid for application programming.</summary>
NET_FW_SCOPE_MAX
End Enum
''' <summary>
''' <para>
''' [The Windows Firewall API is available for use in the operating systems specified in the Requirements section. It may be altered or
''' unavailable in subsequent versions. For Windows Vista and later, use of the Windows Firewall with Advanced Security API is recommended.]
''' </para>
''' <para>The <c>NET_FW_SERVICE_TYPE</c> enumerated type specifies the type of service.</para>
''' </summary>
<PInvokeData("icftypes.h", MSDNShortId:="NE:icftypes.NET_FW_SERVICE_TYPE_")>
Public Enum NET_FW_SERVICE_TYPE
''' <summary>Service type is File and Print Sharing.</summary>
NET_FW_SERVICE_FILE_AND_PRINT
''' <summary>Service type is UPnP Framework.</summary>
NET_FW_SERVICE_UPNP
''' <summary>Service type is Remote Desktop.</summary>
NET_FW_SERVICE_REMOTE_DESKTOP
''' <summary>Not a valid service type. This is used to indicate that a port is not part of a service.</summary>
NET_FW_SERVICE_NONE
''' <summary>Used for boundary checking only. Not valid for application programming.</summary>
NET_FW_SERVICE_TYPE_MAX
End Enum
End Module

View File

@ -0,0 +1,381 @@
Imports System.Runtime.InteropServices
Imports System.Runtime.InteropServices.CustomMarshalers
Partial Public Module FirewallApi
Friend Const Lib_Firewallapi As String = "firewallapi.dll"
''' <summary>
''' The <c>PAC_CHANGES_CALLBACK_FN</c> function is used to add custom behavior to the app container change notification process.
''' </summary>
''' <param name="context">TOptional context pointer.</param>
''' <param name="pChange"/>
''' <remarks>Call NetworkIsolationRegisterForAppContainerChanges to register this callback function.</remarks>
<UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet:=CharSet.Unicode)>
<PInvokeData("netfw.h", MSDNShortId:="NC:netfw.PAC_CHANGES_CALLBACK_FN")>
Public Delegate Sub PAC_CHANGES_CALLBACK_FN(<[In], Out, [Optional]> ByVal context As IntPtr, <[In]> ByRef pChange As INET_FIREWALL_AC_CHANGE)
''' <summary>Callback used by <see cref="NetworkIsolationGetEnterpriseIdAsync"/>.</summary>
''' <param name="context">TOptional context pointer.</param>
''' <param name="wszEnterpriseId">The WSZ enterprise identifier.</param>
''' <param name="dwErr">The dw error.</param>
<UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet:=CharSet.Unicode)>
<PInvokeData("netfw.h", MSDNShortId:="NC:netfw.PAC_CHANGES_CALLBACK_FN")>
Public Delegate Sub PNETISO_EDP_ID_CALLBACK_FN(<[In], Out, [Optional]> ByVal context As IntPtr, <[In], [Optional], MarshalAs(UnmanagedType.LPWStr)> ByVal wszEnterpriseId As String, ByVal dwErr As Win32Error)
''' <summary>
''' The <c>INET_FIREWALL_AC_CREATION_TYPE</c> enumeration specifies the type of app container creation events for which notifications
''' will be delivered.
''' </summary>
<PInvokeData("netfw.h", MSDNShortId:="NE:netfw._INET_FIREWALL_AC_CREATION_TYPE")>
<Flags>
Public Enum INET_FIREWALL_AC_CREATION_TYPE
''' <summary>This value is reserved for system use.</summary>
INET_FIREWALL_AC_NONE = &H0
''' <summary>Notifications will be delivered when an app container is created with a package identifier.</summary>
INET_FIREWALL_AC_PACKAGE_ID_ONLY = &H1
''' <summary>Notifications will be delivered when an app container is created with a binary path.</summary>
INET_FIREWALL_AC_BINARY = &H2
''' <summary>Maximum value for testing purposes.</summary>
INET_FIREWALL_AC_MAX = &H4
End Enum
''' <summary>The <c>NETISO_ERROR_TYPE</c> enumerated type specifies the type of error related to a network isolation operation.</summary>
<PInvokeData("netfw.h", MSDNShortId:="NE:netfw._NETISO_ERROR_TYPE")>
Public Enum NETISO_ERROR_TYPE
''' <summary>No error.</summary>
NETISO_ERROR_TYPE_NONE
''' <summary>The failure was caused because the privateNetworkClientServer capability is missing.</summary>
NETISO_ERROR_TYPE_PRIVATE_NETWORK
''' <summary>The failure was caused because the internetClient capability is missing.</summary>
NETISO_ERROR_TYPE_INTERNET_CLIENT
''' <summary>The failure was caused because the internetClientServer capability is missing.</summary>
NETISO_ERROR_TYPE_INTERNET_CLIENT_SERVER
''' <summary>Maximum value for testing purposes.</summary>
NETISO_ERROR_TYPE_MAX
End Enum
''' <summary>The <c>NETISO_FLAG</c> enumerated type specifies whether binaries should be returned for app containers.</summary>
''' <remarks>
''' By default, binaries are not returned. <c>NETISO_FLAG_FORCE_COMPUTE_BINARIES</c> must be set in order for these to be returned.
''' </remarks>
<PInvokeData("netfw.h", MSDNShortId:="NE:netfw.NETISO_FLAG")>
<Flags>
Public Enum NETISO_FLAG
''' <summary>
''' Specifies that all binaries will be computed before the app container is returned.This flag should be set if the caller requires
''' up-to-date and complete information on app container binaries. If this flag is not set, returned data may be stale or incomplete.
''' </summary>
NETISO_FLAG_FORCE_COMPUTE_BINARIES = &H1
''' <summary>Maximum value for testing purposes.</summary>
NETISO_FLAG_MAX = &H2
End Enum
''' <summary>A bitmask value of control flags which specify the context of <see cref="NetworkIsolationGetEnterpriseIdAsync"/>.</summary>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationGetEnterpriseIdAsync")>
Public Enum NETISO_GEID
''' <summary>
''' Default API behavior. Returns the Enterprise ID for Enterprise resources. Returns NULL for Personal resources. For Neutral
''' resources, returns Enterprise ID if it is called from an Enterprise context, or returns NULL if it is called from a Personal context.
''' </summary>
NETISO_GEID_DEFAULT = &H0
''' <summary>Used in the context of the Windows Defender Application Guard (WDAG) scenario.</summary>
NETISO_GEID_FOR_WDAG = &H1
''' <summary>
''' Used by applications that are aware of neutral resources. For Neutral resources the API will return L*. For Enterprise
''' resources the API will return the Enterprise ID. For Personal resources the API will return NULL.
''' </summary>
NETISO_GEID_FOR_NEUTRAL_AWARE = &H2
''' <summary>
''' Forces API to check the resource even in cases when neither Windows Information Protection nor Windows Defender Application
''' Guard are enabled.
''' </summary>
NETISO_GEID_FORCE_TO_CHECK = &H4
End Enum
''' <summary>
''' The <c>NetworkIsolationEnumAppContainers</c> function enumerates all of the app containers that have been created in the system.
''' </summary>
''' <param name="Flags">
''' <para>Type: <c>DWORD</c></para>
''' <para>
''' May be set to <c>NETISO_FLAG_FORCE_COMPUTE_BINARIES</c> to ensure that all binaries are computed before the app container is
''' returned. This flag should be set if the caller requires up-to-date and complete information on app container binaries. If this flag
''' is not set, returned data may be stale or incomplete.
''' </para>
''' <para>See NETISO_FLAG for more information.</para>
''' </param>
''' <param name="pdwNumPublicAppCs">
''' <para>Type: <c>DWORD*</c></para>
''' <para>The number of app containers in the <c>ppPublicAppCs</c> member.</para>
''' </param>
''' <param name="ppPublicAppCs">
''' <para>Type: <c>PINET_FIREWALL_APP_CONTAINER*</c></para>
''' <para>The list of app container structure elements.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' <para>ERROR_OUTOFMEMORY will be returned if memory is unavailable.</para>
''' </returns>
''' <remarks>If no app containers are installed on the system, ERROR_SUCCESS will still be returned (and ppPublicAppCs will be empty).</remarks>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationEnumAppContainers")>
Public Function NetworkIsolationEnumAppContainers(ByVal Flags As NETISO_FLAG, <Out> ByRef pdwNumPublicAppCs As UInteger, <Out> ByRef ppPublicAppCs As IntPtr) As Win32Error
End Function
''' <summary>The <c>NetworkIsolationEnumerateAppContainerRules</c> function enumerates all of the rules related to app containers.</summary>
''' <param name="newEnum">
''' <para>Type: <c>IEnumVARIANT**</c></para>
''' <para>Enumerator interface of an INetFwRule3 object that represents the rules enforcing app containers.</para>
''' </param>
''' <returns>
''' <para>Type: <c>HRESULT</c></para>
''' <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para>
''' </returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationEnumerateAppContainerRules")>
Public Function NetworkIsolationEnumerateAppContainerRules(<Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(EnumeratorToEnumVariantMarshaler), MarshalCookie:="")> ByRef newEnum As IEnumerable) As HRESULT
End Function
''' <summary>
''' <para>
''' Gets the Enterprise ID based on Network Isolation endpoints in the context of the Windows Information Protection (WIP) or the
''' Windows Defender Application Guard (WDAG) scenarios. If neither WIP nor WDAG are on, the API returns NULL, unless the flag
''' <c>NETISO_GEID_FORCE_TO_CHECK</c> is passed. The Enterprise ID can be any string different from NULL or *.
''' </para>
''' <para>Example of NetworkIsolationGetEnterpriseIdAsync usage: https://github.com/microsoft/EnterpriseStateClassify</para>
''' </summary>
''' <param name="wszServerName">The name of the Enterprise Data Protection Server.</param>
''' <param name="dwFlags">
''' <para>A bitmask value of control flags which specify the context of the API call. May contain one or more of the following flags.</para>
''' <list type="table">
''' <listheader>
''' <term>Value</term>
''' <term>Meaning</term>
''' </listheader>
''' <item>
''' <term>NETISO_GEID_DEFAULT 0x00</term>
''' <term>
''' Default API behavior. Returns the Enterprise ID for Enterprise resources. Returns NULL for Personal resources. For Neutral
''' resources, returns Enterprise ID if it is called from an Enterprise context, or returns NULL if it is called from a Personal context.
''' </term>
''' </item>
''' <item>
''' <term>NETISO_GEID_FOR_WDAG 0x01</term>
''' <term>Used in the context of the Windows Defender Application Guard (WDAG) scenario.</term>
''' </item>
''' <item>
''' <term>NETISO_GEID_FOR_NEUTRAL_AWARE 0x02</term>
''' <term>
''' Used by applications that are aware of neutral resources. For Neutral resources the API will return L*. For Enterprise resources
''' the API will return the Enterprise ID. For Personal resources the API will return NULL.
''' </term>
''' </item>
''' <item>
''' <term>NETISO_GEID_FORCE_TO_CHECK 0x04</term>
''' <term>
''' Forces API to check the resource even in cases when neither Windows Information Protection nor Windows Defender Application Guard
''' are enabled.
''' </term>
''' </item>
''' </list>
''' </param>
''' <param name="context">Optional context pointer.</param>
''' <param name="callback">Function pointer that will be invoked when a notification is ready for delivery.</param>
''' <param name="hOperation">The handle for the Enterprise Data Protection Server endpoints.</param>
''' <returns>Returns ERROR_SUCCESS if successful, or an error value otherwise.</returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationGetEnterpriseIdAsync")>
Public Function NetworkIsolationGetEnterpriseIdAsync(<MarshalAs(UnmanagedType.LPWStr)> ByVal wszServerName As String, ByVal dwFlags As NETISO_GEID,
<[In], [Optional]> ByVal context As IntPtr, ByVal callback As PNETISO_EDP_ID_CALLBACK_FN, <Out> ByRef hOperation As HANDLE) As Win32Error
End Function
''' <summary>
''' <para>
''' This API is used for closing the handle returned by NetworkIsolationGetEnterpriseIdAsync as well as for synchronizing the operation.
''' </para>
''' <para>Example of NetworkIsolationGetEnterpriseIdClose usage: https://github.com/microsoft/EnterpriseStateClassify</para>
''' </summary>
''' <param name="hOperation">The handle to release.</param>
''' <param name="bWaitForOperation">Indicates whether to wait for synchronization.</param>
''' <returns>Returns ERROR_SUCCESS if successful, or an error value otherwise.</returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationGetEnterpriseIdClose")>
Public Function NetworkIsolationGetEnterpriseIdClose(ByVal hOperation As HANDLE, <MarshalAs(UnmanagedType.Bool)> ByVal bWaitForOperation As Boolean) As Win32Error
End Function
''' <summary>The <c>NetworkIsolationSetAppContainerConfig</c> function is used to set the configuration of one or more app containers.</summary>
''' <param name="dwNumPublicAppCs">
''' <para>Type: <c>DWORD</c></para>
''' <para>The number of app containers in the <c>appContainerSids</c> member.</para>
''' </param>
''' <param name="appContainerSids">
''' <para>Type: <c>PSID_AND_ATTRIBUTES</c></para>
''' <para>The security identifiers (SIDs) of app containers that are allowed to send loopback traffic. Used for debugging purposes.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
''' <remarks>
''' Note that it is the calling program's responsibility to first call the <c>NetworkIsolationGetAppContainerConfig</c> function in
''' order to retrieve and preserve the app container SIDs already configured to send loopback traffic.
''' </remarks>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationSetAppContainerConfig")>
Public Function NetworkIsolationSetAppContainerConfig(ByVal dwNumPublicAppCs As UInteger, <[In]> ByVal appContainerSids As IntPtr) As Win32Error
End Function
''' <summary>
''' The <c>NetworkIsolationSetupAppContainerBinaries</c> function is used by software installers to provide information about the image
''' paths of applications that are running in an app container. This information is provided to third-party firewall applications about
''' the applications in order to enhance user experience and security decisions.
''' </summary>
''' <param name="applicationContainerSid">
''' <para>Type: <c>PSID</c></para>
''' <para>The package identifier of the app container.</para>
''' </param>
''' <param name="packageFullName">
''' <para>Type: <c>LPCWSTR</c></para>
''' <para>
''' A string representing the package identity of the app that owns this app container. Contains the 5-part tuple as individual fields
''' (name, version, architecture, resourceid, publisher).
''' </para>
''' </param>
''' <param name="packageFolder">
''' <para>Type: <c>LPCWSTR</c></para>
''' <para>The file location of the app that owns this app container.</para>
''' </param>
''' <param name="displayName">
''' <para>Type: <c>LPCWSTR</c></para>
''' <para>The friendly name of the app container.</para>
''' </param>
''' <param name="bBinariesFullyComputed">
''' <para>Type: <c>BOOL</c></para>
''' <para>True if the binary files are being provided by the caller; otherwise, false.</para>
''' </param>
''' <param name="binaries">
''' <para>Type: <c>LPCWSTR*</c></para>
''' <para>An array of paths to the applications running in the app container.</para>
''' </param>
''' <param name="binariesCount">
''' <para>Type: <c>DWORD</c></para>
''' <para>The number of paths contained in the binaries parameter.</para>
''' </param>
''' <returns>
''' <para>Type: <c>HRESULT</c></para>
''' <para>If the function succeeds, it returns S_OK.</para>
''' <para>
''' If the function fails, it returns an <c>HRESULT</c> value that indicates the error. For a list of common error codes, see Common
''' HRESULT Values.
''' </para>
''' </returns>
''' <remarks>
''' Applications creating an app container can use <c>NetworkIsolationSetupAppContainerBinaries</c> to provide third-party firewall
''' applications with the direct path to applications running inside that app container.
''' </remarks>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("netfw.h", MSDNShortId:="NF:netfw.NetworkIsolationSetupAppContainerBinaries")>
Public Function NetworkIsolationSetupAppContainerBinaries(ByVal applicationContainerSid As PSID, <MarshalAs(UnmanagedType.LPWStr)> ByVal packageFullName As String,
<MarshalAs(UnmanagedType.LPWStr)> ByVal packageFolder As String,
<MarshalAs(UnmanagedType.LPWStr)> ByVal displayName As String,
<MarshalAs(UnmanagedType.Bool)> ByVal bBinariesFullyComputed As Boolean,
<[In], MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.LPWStr)> ByVal binaries As String(),
ByVal binariesCount As UInteger) As HRESULT
End Function
''' <summary>The <c>INET_FIREWALL_AC_BINARIES</c> structure contains the binary paths to applications running in an app container.</summary>
<PInvokeData("netfw.h", MSDNShortId:="NS:netfw._INET_FIREWALL_AC_BINARIES")>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure INET_FIREWALL_AC_BINARIES
''' <summary>The number of paths in the <c>binaries</c> member.</summary>
Public count As UInteger
''' <summary>Paths to the applications running in the app container.</summary>
Public binaries As IntPtr
End Structure
''' <summary>The INET_FIREWALL_AC_CHANGE structure contains information about a change made to an app container.</summary>
<PInvokeData("netfw.h", MSDNShortId:="NS:netfw._INET_FIREWALL_AC_CHANGE")>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure INET_FIREWALL_AC_CHANGE
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_CHANGE_TYPE</c></para>
''' <para>The type of change made.</para>
''' </summary>
Public changeType As INET_FIREWALL_AC_CHANGE_TYPE
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_CREATION_TYPE</c></para>
''' <para>The method by which the app container was created.</para>
''' </summary>
Public createType As INET_FIREWALL_AC_CREATION_TYPE
''' <summary>
''' <para>Type: <c>SID*</c></para>
''' <para>The package identifier of the app container</para>
''' </summary>
Public appContainerSid As PSID
''' <summary>
''' <para>Type: <c>SID*</c></para>
''' <para>The security identifier (SID) of the user to whom the app container belongs.</para>
''' </summary>
Public userSid As PSID
''' <summary>
''' <para>Type: <c>LPWSTR</c></para>
''' <para>Friendly name of the app container.</para>
''' </summary>
<MarshalAs(UnmanagedType.LPWStr)>
Public displayName As String
''' <summary/>
Public union As UNIONType
''' <summary/>
<StructLayout(LayoutKind.Explicit)>
Public Structure UNIONType
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_CAPABILITIES</c></para>
''' <para>Information about the capabilities of the changed app container.</para>
''' </summary>
<FieldOffset(0)>
Public capabilities As INET_FIREWALL_AC_CAPABILITIES
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_BINARIES</c></para>
''' <para>Binary paths to the applications running in the changed app container.</para>
''' </summary>
<FieldOffset(0)>
Public binaries As INET_FIREWALL_AC_BINARIES
End Structure
End Structure
End Module

2814
PInvoke/FirewallApi/NetFW.vb Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,240 @@
Imports System.Runtime.InteropServices
Partial Public Module FirewallApi
''' <summary>The <c>INET_FIREWALL_AC_CHANGE_TYPE</c> enumeration specifies which type of app container change occurred.</summary>
<PInvokeData("networkisolation.h", MSDNShortId:="NE:networkisolation._INET_FIREWALL_AC_CHANGE_TYPE")>
Public Enum INET_FIREWALL_AC_CHANGE_TYPE
''' <summary>This value is reserved for system use.</summary>
INET_FIREWALL_AC_CHANGE_INVALID
''' <summary>An app container was created.</summary>
INET_FIREWALL_AC_CHANGE_CREATE
''' <summary>An app container was deleted.</summary>
INET_FIREWALL_AC_CHANGE_DELETE
''' <summary>Maximum value for testing purposes.</summary>
INET_FIREWALL_AC_CHANGE_MAX
End Enum
''' <summary>
''' The <c>NetworkIsolationDiagnoseConnectFailureAndGetInfo</c> function gets information about a network isolation connection failure
''' due to a missing capability. This function can be used to identify the capabilities required to connect to a server.
''' </summary>
''' <param name="wszServerName">
''' <para>Type: <c>LPCWSTR</c></para>
''' <para>Name (or IP address literal string) of the server to which a connection was attempted.</para>
''' </param>
''' <param name="netIsoError">
''' <para>Type: <c>NETISO_ERROR_TYPE*</c></para>
''' <para>The error that has occurred, indicating which network capability was missing and thus caused the failure.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("networkisolation.h", MSDNShortId:="NF:networkisolation.NetworkIsolationDiagnoseConnectFailureAndGetInfo")>
Public Function NetworkIsolationDiagnoseConnectFailureAndGetInfo(
<MarshalAs(UnmanagedType.LPWStr)> ByVal wszServerName As String, <Out> ByRef netIsoError As NETISO_ERROR_TYPE) As Win32Error
End Function
''' <summary>
''' The <c>NetworkIsolationFreeAppContainers</c> function is used to release memory resources allocated to one or more app containers
''' </summary>
''' <param name="pPublicAppCs">
''' <para>Type: <c>PINET_FIREWALL_APP_CONTAINER</c></para>
''' <para>The app container memory resources to be freed.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("networkisolation.h", MSDNShortId:="NF:networkisolation.NetworkIsolationFreeAppContainers")>
Public Function NetworkIsolationFreeAppContainers(
<[In]> ByVal pPublicAppCs As IntPtr) As Win32Error
End Function
''' <summary>
''' The <c>NetworkIsolationGetAppContainerConfig</c> function is used to retrieve configuration information about one or more app containers.
''' </summary>
''' <param name="pdwNumPublicAppCs">
''' <para>Type: <c>DWORD*</c></para>
''' <para>The number of app containers in the <c>appContainerSids</c> member.</para>
''' </param>
''' <param name="appContainerSids">
''' <para>Type: <c>PSID_AND_ATTRIBUTES*</c></para>
''' <para>The security identifiers (SIDs) of app containers that are allowed to send loopback traffic. Used for debugging purposes.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
''' <remarks>
''' <para>
''' Note that it is the calling program's responsibility to free the memory associated with the PSID_AND_ATTRIBUTES structure. The
''' following code sample shows how to call this function. The FreeAppContainerConfig function shows how to free all of the associated memory.
''' </para>
''' <para>
''' <code> #include "stdafx.h" #include &lt;netfw.h&gt; typedef DWORD (WINAPI *FN_NETWORKISOLATIONGETAPPCONTAINERCONFIG)( _Out_ DWORD *pdwNumPublicAppCs, _Outptr_result_buffer_(*pdwNumPublicAppCs) PSID_AND_ATTRIBUTES *appContainerSids ); void FreeAppContainerConfig( __in DWORD sidCount, __in_ecount(sidCount) SID_AND_ATTRIBUTES *srcSidAttrib ) { DWORD dwIndex = 0; for (dwIndex = 0; dwIndex &lt; sidCount; dwIndex++) { HeapFree(GetProcessHeap(), 0, srcSidAttrib[dwIndex].Sid); } HeapFree(GetProcessHeap(), 0, srcSidAttrib); } int _tmain(int argc, _TCHAR* argv[]) { DWORD dwErr = 0; PSID_AND_ATTRIBUTES appContainerSids = NULL; DWORD dwCount = 0; HMODULE hModule = NULL; FN_NETWORKISOLATIONGETAPPCONTAINERCONFIG pfnNetworkIsolationGetAppContainerConfig = NULL; hModule = LoadLibraryW(L"FirewallAPI.dll"); if (hModule == NULL) { dwErr = GetLastError(); goto Cleanup; } pfnNetworkIsolationGetAppContainerConfig = (FN_NETWORKISOLATIONGETAPPCONTAINERCONFIG)GetProcAddress( hModule, "NetworkIsolationGetAppContainerConfig" ); if (pfnNetworkIsolationGetAppContainerConfig == NULL) { dwErr = GetLastError(); goto Cleanup; } dwErr = pfnNetworkIsolationGetAppContainerConfig( &amp;dwCount, &amp;appContainerSids ); if (dwErr != ERROR_SUCCESS) { goto Cleanup; } // Process the app container sids Cleanup: FreeAppContainerConfig( dwCount, appContainerSids ); if (hModule != NULL) { FreeLibrary(hModule); } return 0; }</code>
''' </para>
''' </remarks>
<DllImport(Lib_Firewallapi, SetLastError:=True, ExactSpelling:=True)>
<PInvokeData("networkisolation.h", MSDNShortId:="NF:networkisolation.NetworkIsolationGetAppContainerConfig")>
Public Function NetworkIsolationGetAppContainerConfig(<Out> ByRef pdwNumPublicAppCs As UInteger, <Out> ByRef appContainerSids As IntPtr) As Win32Error
End Function
''' <summary>
''' The <c>NetworkIsolationRegisterForAppContainerChanges</c> function is used to register for the delivery of notifications regarding
''' changes to an app container.
''' </summary>
''' <param name="flags">
''' <para>Type: <c>DWORD</c></para>
''' <para>A bitmask value of control flags which specify when to receive notifications. May contain one or more of the following flags.</para>
''' <list type="table">
''' <listheader>
''' <term>Value</term>
''' <term>Meaning</term>
''' </listheader>
''' <item>
''' <term>INET_FIREWALL_AC_NONE 0x00</term>
''' <term>No notifications will be delivered.</term>
''' </item>
''' <item>
''' <term>INET_FIREWALL_AC_PACKAGE_ID_ONLY 0x01</term>
''' <term>Notifications will be delivered when an app container is created with a package identifier.</term>
''' </item>
''' <item>
''' <term>INET_FIREWALL_AC_BINARY 0x02</term>
''' <term>Notifications will be delivered when an app container is created with a binary path.</term>
''' </item>
''' <item>
''' <term>INET_FIREWALL_AC_MAX 0x04</term>
''' <term>Maximum value for testing purposes.</term>
''' </item>
''' </list>
''' </param>
''' <param name="callback">
''' <para>Type: <c>PAC_CHANGES_CALLBACK_FN</c></para>
''' <para>Function pointer that will be invoked when a notification is ready for delivery.</para>
''' </param>
''' <param name="context">
''' <para>Type: <c>PVOID</c></para>
''' <para>Optional context pointer. This pointer is passed to the callback function along with details of the change.</para>
''' </param>
''' <param name="registrationObject">
''' <para>Type: <c>HANDLE*</c></para>
''' <para>Handle to the newly created registration.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("networkisolation.h", MSDNShortId:="NF:networkisolation.NetworkIsolationRegisterForAppContainerChanges")>
Public Function NetworkIsolationRegisterForAppContainerChanges(ByVal flags As INET_FIREWALL_AC_CREATION_TYPE, ByVal callback As PAC_CHANGES_CALLBACK_FN,
<[In], [Optional]> ByVal context As IntPtr, <Out> ByRef registrationObject As HANDLE) As Win32Error
End Function
''' <summary>
''' The <c>NetworkIsolationUnregisterForAppContainerChanges</c> function is used to cancel an app container change registration and stop
''' receiving notifications.
''' </summary>
''' <param name="registrationObject">
''' <para>Type: <c>HANDLE</c></para>
''' <para>Handle to the previously created registration.</para>
''' </param>
''' <returns>
''' <para>Type: <c>DWORD</c></para>
''' <para>Returns ERROR_SUCCESS if successful, or an error value otherwise.</para>
''' </returns>
<DllImport(Lib_Firewallapi, SetLastError:=False, ExactSpelling:=True)>
<PInvokeData("networkisolation.h", MSDNShortId:="NF:networkisolation.NetworkIsolationUnregisterForAppContainerChanges")>
Public Function NetworkIsolationUnregisterForAppContainerChanges(ByVal registrationObject As HANDLE) As Win32Error
End Function
''' <summary>The <c>INET_FIREWALL_AC_CAPABILITIES</c> structure contains information about the capabilities of an app container.</summary>
<PInvokeData("networkisolation.h", MSDNShortId:="NS:networkisolation._INET_FIREWALL_AC_CAPABILITIES")>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure INET_FIREWALL_AC_CAPABILITIES
''' <summary>
''' <para>Type: <c>DWORD</c></para>
''' <para>The number of security identifiers (SIDs) in the <c>capabilities</c> member.</para>
''' </summary>
Public count As UInteger
''' <summary>
''' <para>Type: <c>SID_AND_ATTRIBUTES*</c></para>
''' <para>Security information related to the app container's capabilities.</para>
''' </summary>
Public capabilities As IntPtr
End Structure
''' <summary>The <c>INET_FIREWALL_APP_CONTAINER</c> structure contains information about an specific app container.</summary>
<PInvokeData("networkisolation.h", MSDNShortId:="NS:networkisolation._INET_FIREWALL_APP_CONTAINER")>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure INET_FIREWALL_APP_CONTAINER
''' <summary>
''' <para>Type: <c>SID*</c></para>
''' <para>The package identifier of the app container</para>
''' </summary>
Public appContainerSid As PSID
''' <summary>
''' <para>Type: <c>SID*</c></para>
''' <para>The security identifier (SID) of the user to whom the app container belongs.</para>
''' </summary>
Public userSid As PSID
''' <summary>
''' <para>Type: <c>LPWSTR</c></para>
''' <para>The app container's globally unique name.</para>
''' <para>Also referred to as the Package Family Name, for the app container of a Windows Store app.</para>
''' </summary>
<MarshalAs(UnmanagedType.LPWStr)>
Public appContainerName As String
''' <summary>
''' <para>Type: <c>LPWSTR</c></para>
''' <para>Friendly name of the app container</para>
''' </summary>
<MarshalAs(UnmanagedType.LPWStr)>
Public displayName As String
''' <summary>
''' <para>Type: <c>LPWSTR</c></para>
''' <para>A description of the app container (its use, the objective of the application that uses it, etc.)</para>
''' </summary>
<MarshalAs(UnmanagedType.LPWStr)>
Public description As String
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_CAPABILITIES</c></para>
''' <para>The capabilities of the app container.</para>
''' </summary>
Public capabilities As INET_FIREWALL_AC_CAPABILITIES
''' <summary>
''' <para>Type: <c>INET_FIREWALL_AC_BINARIES</c></para>
''' <para>Binary paths to the applications running in the app container.</para>
''' </summary>
Public binaries As INET_FIREWALL_AC_BINARIES
''' <summary/>
<MarshalAs(UnmanagedType.LPWStr)>
Public workingDirectory As String
''' <summary/>
<MarshalAs(UnmanagedType.LPWStr)>
Public packageFullName As String
End Structure
End Module

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<ProjectExtensions>
<SupportedDlls>FirewallApi.dll</SupportedDlls>
</ProjectExtensions>
<PropertyGroup>
<Description>PInvoke API (methods, structures and constants) imported from FirewallApi.dll for Windows Firewall with Advanced Security.</Description>
<AssemblyTitle>$(AssemblyName)</AssemblyTitle>
<TargetFrameworks>net20;net35;net40;net45;netcoreapp2.0;netcoreapp2.1;netcoreapp3.0;netcoreapp3.1</TargetFrameworks>
<AssemblyName>Vanara.PInvoke.FirewallApi</AssemblyName>
<DocumentationFile>$(AssemblyName).xml</DocumentationFile>
<PackageId>$(AssemblyName)</PackageId>
<PackageTags>pinvoke;vanara;net-extensions;interop;FirewallApi;windows firewall</PackageTags>
<PackageReleaseNotes />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\Vanara.Core.csproj" />
<ProjectReference Include="..\Shared\Vanara.PInvoke.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="CustomMarshalers" Condition=" $(TargetFramework.StartsWith('net2')) Or $(TargetFramework.StartsWith('net3')) Or $(TargetFramework.StartsWith('net4')) " />
</ItemGroup>
</Project>

View File

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="16.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6A9599A6-89D5-4072-8DA1-A13E37023613}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<AssemblyName>UnitTest.PInvoke.FirewallApi</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Core\Vanara.Core.csproj">
<Project>{241f73ee-9298-45c9-b869-a045dff94c03}</Project>
<Name>Vanara.Core</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\PInvoke\FirewallApi\Vanara.PInvoke.FirewallApi.vbproj">
<Project>{e74c1a09-1051-4616-8693-b69a6a95ad03}</Project>
<Name>Vanara.PInvoke.FirewallApi</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\PInvoke\Shared\Vanara.PInvoke.Shared.csproj">
<Project>{a5e519e9-feba-4fe3-93a5-b8269bef72f4}</Project>
<Name>Vanara.PInvoke.Shared</Name>
</ProjectReference>
<ProjectReference Include="..\..\CSharpRunner\Shared.csproj">
<Project>{a96cff10-0967-429a-8700-4a86c97c5603}</Project>
<Name>Shared</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="NUnit">
<Version>3.12.0</Version>
</PackageReference>
<PackageReference Include="NUnit3TestAdapter">
<Version>3.16.1</Version>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Include="FirewallApiTests.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,255 @@
using NUnit.Framework;
using NUnit.Framework.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Vanara.Extensions;
using Vanara.InteropServices;
using static Vanara.PInvoke.FirewallApi;
namespace Vanara.PInvoke.Tests
{
[TestFixture]
public class FirewallApiTests
{
[OneTimeSetUp]
public void _Setup()
{
}
[OneTimeTearDown]
public void _TearDown()
{
}
[Test]
public void INetFwMgrTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
pMgr.Item.CurrentProfileType.WriteValues();
pMgr.Item.IsPortAllowed(null, NET_FW_IP_VERSION.NET_FW_IP_VERSION_ANY, 80, null, NET_FW_IP_PROTOCOL.NET_FW_IP_PROTOCOL_TCP, out var allowed, out var restricted);
TestContext.WriteLine($"Port 80: allowed={allowed}, restricted={restricted}");
pMgr.Item.IsIcmpTypeAllowed(NET_FW_IP_VERSION.NET_FW_IP_VERSION_V4, null, 0, out allowed, out restricted);
TestContext.WriteLine($"ECHO: allowed={allowed}, restricted={restricted}");
}
[Test]
public void GetProfileByTypeTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.GetProfileByType(NET_FW_PROFILE_TYPE.NET_FW_PROFILE_DOMAIN));
Assert.IsNotNull(pProf.Item);
TestContext.WriteLine($"Type={pProf.Item.Type}, FwEnable={pProf.Item.FirewallEnabled}, NoExc={pProf.Item.ExceptionsNotAllowed}, NoNtf={pProf.Item.NotificationsDisabled}, NoUnc={pProf.Item.UnicastResponsesToMulticastBroadcastDisabled}");
}
[Test]
public void RemoteAdminSettingsTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.CurrentProfile);
Assert.IsNotNull(pProf.Item);
using var pSet = ComReleaserFactory.Create(pProf.Item.RemoteAdminSettings);
Assert.IsNotNull(pSet.Item);
TestContext.WriteLine($"Ver={pSet.Item.IpVersion}, Scope={pSet.Item.Scope}, Addr={pSet.Item.RemoteAddresses}, Enabled={pSet.Item.Enabled}");
}
[Test]
public void IcmpSettingsTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.CurrentProfile);
Assert.IsNotNull(pProf.Item);
using var pSet = ComReleaserFactory.Create(pProf.Item.IcmpSettings);
Assert.IsNotNull(pSet.Item);
TestContext.WriteLine($"ObDest={pSet.Item.AllowOutboundDestinationUnreachable}, Redircope={pSet.Item.AllowRedirect}, InEcho={pSet.Item.AllowInboundEchoRequest}, ObTimeout={pSet.Item.AllowOutboundTimeExceeded}");
TestContext.WriteLine($"ObParam={pSet.Item.AllowOutboundParameterProblem}, ObSrcQuench={pSet.Item.AllowOutboundSourceQuench}, InRtReq={pSet.Item.AllowInboundRouterRequest}, InTimeReq={pSet.Item.AllowInboundTimestampRequest}");
TestContext.WriteLine($"InMaskReq={pSet.Item.AllowInboundMaskRequest}, ObBigPkt={pSet.Item.AllowOutboundPacketTooBig}");
}
[Test]
public void GloballyOpenPortsTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.CurrentProfile);
Assert.IsNotNull(pProf.Item);
using var pSet = ComReleaserFactory.Create(pProf.Item.GloballyOpenPorts);
Assert.IsNotNull(pSet.Item);
var i = 0;
foreach (var pPort in pSet.Item.Cast<INetFwOpenPort>().Select(p => ComReleaserFactory.Create(p)))
{
using (pPort)
{
TestContext.WriteLine($"{i}) Name={pPort.Item.Name}, Ver={pPort.Item.IpVersion}, Prot={pPort.Item.Protocol}, Port={pPort.Item.Port}");
TestContext.WriteLine($" Scope={pPort.Item.Scope}, RmAdd={pPort.Item.RemoteAddresses}, Enab={pPort.Item.Enabled}, BuiltIn={pPort.Item.BuiltIn}");
}
i += 1;
}
Assert.That(i, Is.EqualTo(pSet.Item.Count));
using var pNewPort = ComReleaserFactory.Create(new INetFwOpenPort());
pNewPort.Item.Name = "HTTP";
pNewPort.Item.Port = 80;
pNewPort.Item.Protocol = NET_FW_IP_PROTOCOL.NET_FW_IP_PROTOCOL_TCP;
pSet.Item.Add(pNewPort.Item);
Assert.That(i + 1, Is.EqualTo(pSet.Item.Count));
using var pAddedPort = ComReleaserFactory.Create(pSet.Item.Item(pNewPort.Item.Port, pNewPort.Item.Protocol));
Assert.IsNotNull(pAddedPort.Item);
pSet.Item.Remove(pNewPort.Item.Port, pNewPort.Item.Protocol);
Assert.That(i, Is.EqualTo(pSet.Item.Count));
}
[Test]
public void ServicesTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.CurrentProfile);
Assert.IsNotNull(pProf.Item);
using var pSet = ComReleaserFactory.Create(pProf.Item.Services);
Assert.IsNotNull(pSet.Item);
var i = 0;
foreach (var pSvc in pSet.Item.Cast<INetFwService>().Select(p => ComReleaserFactory.Create(p)))
{
using (pSvc)
{
TestContext.WriteLine($"{i}) Name={pSvc.Item.Name}, Type={pSvc.Item.Type}, Cust={pSvc.Item.Customized}, IpVer={pSvc.Item.IpVersion}");
TestContext.WriteLine($" Scope={pSvc.Item.Scope}, RmAdd={pSvc.Item.RemoteAddresses}, Enab={pSvc.Item.Enabled}");
}
i += 1;
}
Assert.That(i, Is.EqualTo(pSet.Item.Count));
}
[Test]
public void AuthorizedApplicationsTest()
{
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
Assert.IsNotNull(pMgr.Item);
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
Assert.IsNotNull(pPol.Item);
using var pProf = ComReleaserFactory.Create(pPol.Item.CurrentProfile);
Assert.IsNotNull(pProf.Item);
using var pSet = ComReleaserFactory.Create(pProf.Item.AuthorizedApplications);
Assert.IsNotNull(pSet.Item);
var i = 0;
foreach (var pApp in pSet.Item.Cast<INetFwAuthorizedApplication>().Select(p => ComReleaserFactory.Create(p)))
{
using (pApp)
{
TestContext.WriteLine($"{i}) Name={pApp.Item.Name}, FN={pApp.Item.ProcessImageFileName}, IpVer={pApp.Item.IpVersion}");
TestContext.WriteLine($" Scope={pApp.Item.Scope}, RmAdd={pApp.Item.RemoteAddresses}, Enab={pApp.Item.Enabled}");
}
i += 1;
}
Assert.That(i, Is.EqualTo(pSet.Item.Count));
using var pNewApp = ComReleaserFactory.Create(new INetFwAuthorizedApplication());
pNewApp.Item.Name = "Notepad";
pNewApp.Item.ProcessImageFileName = @"C:\Windows\notepad.exe";
pNewApp.Item.Enabled = true;
pSet.Item.Add(pNewApp.Item);
Assert.That(i + 1, Is.EqualTo(pSet.Item.Count));
pSet.Item.Remove(pNewApp.Item.ProcessImageFileName);
Assert.That(i, Is.EqualTo(pSet.Item.Count));
}
[Test]
public void INetFwProductsTest()
{
using var pProds = ComReleaserFactory.Create(new INetFwProducts());
Assert.IsNotNull(pProds.Item);
var i = 0;
foreach (var pProd in pProds.Item.Cast<INetFwProduct>().Select(p => ComReleaserFactory.Create(p)))
{
using (pProd)
{
TestContext.WriteLine($"{i}) Name={pProd.Item.DisplayName}, Exe={pProd.Item.PathToSignedProductExe}");
TestContext.WriteLine($" Cats={string.Join("; ", (string[])pProd.Item.RuleCategories)}");
}
i += 1;
}
Assert.That(i, Is.EqualTo(pProds.Item.Count));
}
[Test]
public void INetFwPolicy2Test()
{
using var pPol = ComReleaserFactory.Create(new INetFwPolicy2());
Assert.IsNotNull(pPol.Item);
TestContext.WriteLine($"Types={pPol.Item.CurrentProfileTypes}; ModState={pPol.Item.LocalPolicyModifyState}");
var prof = pPol.Item.CurrentProfileTypes.GetFlags().First();
var exInt = pPol.Item.ExcludedInterfaces[prof];
TestContext.WriteLine($"Enab={pPol.Item.FirewallEnabled[prof]}, ExInt={exInt}, BlkInb={pPol.Item.BlockAllInboundTraffic[prof]}, NoNotf={pPol.Item.NotificationsDisabled[prof]}");
TestContext.WriteLine($"NoUni={pPol.Item.UnicastResponsesToMulticastBroadcastDisabled[prof]}, DefInAct={pPol.Item.DefaultInboundAction[prof]}, DefOutAct={pPol.Item.DefaultOutboundAction[prof]}");
using var pRules = ComReleaserFactory.Create(pPol.Item.Rules);
Assert.IsNotNull(pRules.Item);
var i = 0;
var groups = new List<string>();
foreach (var pRule in pRules.Item.Cast<INetFwRule>().Select(p => ComReleaserFactory.Create(p)))
{
using (pRule)
groups.Add(pRule.Item.Grouping);
i++;
}
Assert.That(i, Is.EqualTo(pRules.Item.Count));
groups = groups.Distinct().ToList();
using var pRstr = ComReleaserFactory.Create(pPol.Item.ServiceRestriction);
Assert.IsNotNull(pRules.Item);
if (groups.Count > 0 && pPol.Item.IsRuleGroupCurrentlyEnabled[groups[0]])
{
TestContext.WriteLine($"Group '{groups[0]}' is enabled={pPol.Item.IsRuleGroupEnabled(prof, groups[0])}");
}
}
[Test]
public void INetFwRuleTest()
{
using var pPol = ComReleaserFactory.Create(new INetFwPolicy2());
Assert.IsNotNull(pPol.Item);
using var pRules = ComReleaserFactory.Create(pPol.Item.Rules);
Assert.IsNotNull(pRules.Item);
foreach (var pRule in pRules.Item.Cast<INetFwRule>().Select(p => ComReleaserFactory.Create(p)))
{
using (pRule)
{
var r3 = (INetFwRule3)pRule.Item;
var intf = r3.GetInterfaces();
TestContext.WriteLine(new string('=', 30));
TestContext.WriteLine($"{r3.Name}: {r3.Description}");
TestContext.WriteLine($" App={r3.ApplicationName}, Svc={r3.serviceName}, Prot={r3.Protocol}, LcPrt={r3.LocalPorts}, RmPrt={r3.RemotePorts}, LcAddr={r3.LocalAddresses}");
TestContext.WriteLine($" RmAddr={r3.RemoteAddresses}, Icmp={r3.IcmpTypesAndCodes}, Dir={r3.Direction}, Intf={string.Join(";", intf)}, IntfT={r3.InterfaceTypes}, Enab={r3.Enabled}");
TestContext.WriteLine($" Grp={r3.Grouping}, Prof={r3.Profiles}, EdgeTrv={r3.EdgeTraversal}");
TestContext.WriteLine($" Action={r3.Action}, EdgeTrvOp={r3.EdgeTraversalOptions}, LcPkg={r3.LocalAppPackageId}");
TestContext.WriteLine($" LcUsr={r3.LocalUserOwner}, LcUsrAuth={r3.LocalUserAuthorizedList}, RmUsrAuth={r3.RemoteUserAuthorizedList}, RmMachAuth={r3.RemoteMachineAuthorizedList}, Sec={r3.SecureFlags}");
}
}
}
}
}

View File

@ -247,6 +247,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vanara.PInvoke.PeerDist", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vanara.PInvoke.Drt", "PInvoke\Drt\Vanara.PInvoke.Drt.csproj", "{1AB1FB9D-CE35-4A2D-9132-FFA681654031}"
EndProject
Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Vanara.PInvoke.FirewallApi", "PInvoke\FirewallApi\Vanara.PInvoke.FirewallApi.vbproj", "{E74C1A09-1051-4616-8693-B69A6A95AD03}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FirewallApi", "UnitTests\PInvoke\FirewallApi\FirewallApi.csproj", "{6A9599A6-89D5-4072-8DA1-A13E37023613}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -795,6 +799,16 @@ Global
{1AB1FB9D-CE35-4A2D-9132-FFA681654031}.DebugNoTests|Any CPU.Build.0 = Debug|Any CPU
{1AB1FB9D-CE35-4A2D-9132-FFA681654031}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1AB1FB9D-CE35-4A2D-9132-FFA681654031}.Release|Any CPU.Build.0 = Release|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.DebugNoTests|Any CPU.ActiveCfg = Debug|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.DebugNoTests|Any CPU.Build.0 = Debug|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E74C1A09-1051-4616-8693-B69A6A95AD03}.Release|Any CPU.Build.0 = Release|Any CPU
{6A9599A6-89D5-4072-8DA1-A13E37023613}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A9599A6-89D5-4072-8DA1-A13E37023613}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A9599A6-89D5-4072-8DA1-A13E37023613}.DebugNoTests|Any CPU.ActiveCfg = Debug|Any CPU
{6A9599A6-89D5-4072-8DA1-A13E37023613}.Release|Any CPU.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -901,6 +915,8 @@ Global
{BBA10B94-658F-4BD7-A3DD-AA39CDF9A68D} = {385CAD2D-0A5E-4F80-927B-D5499D126B90}
{3108565B-2F79-447B-9386-42203CD949A5} = {212ABBD0-B724-4CFA-9D6D-E3891547FA90}
{1AB1FB9D-CE35-4A2D-9132-FFA681654031} = {212ABBD0-B724-4CFA-9D6D-E3891547FA90}
{E74C1A09-1051-4616-8693-B69A6A95AD03} = {212ABBD0-B724-4CFA-9D6D-E3891547FA90}
{6A9599A6-89D5-4072-8DA1-A13E37023613} = {385CAD2D-0A5E-4F80-927B-D5499D126B90}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {543FAC75-2AF1-4EF1-9609-B242B63FEED4}