Jump to content

Windows Firewall Policy2 Interface UDF, Provides access to the firewall policy for Windows Vista+


Bilgus
 Share

Recommended Posts

; NetFirewallPolicy2 COM UDF Library for AutoIt3
; AutoIt Version : 3.3.14.5
; Description ...: Windows Firewall Policy2 Interface, Provides access to the firewall policy for Windows Vista+

Including Test Script 

  • _NetFw_Get_CurrentProfileTypes                           Retrieves the currently active firewall profile(s)
  • _NetFw_Get_FirewallEnabled                               Indicates whether a firewall is enabled locally
  • _NetFw_Put_FirewallEnabled                               Specifies whether a firewall is enabled locally
  • _NetFw_Get_ExcludedInterfaces                            Indicates a list of interfaces on which firewall settings are excluded
  • _NetFw_Put_ExcludedInterfaces                            Specifies a list of interfaces on which firewall settings are excluded
  • _NetFw_Get_BlockAllInboundTraffic                        Indicates whether the firewall should not allow inbound traffic
  • _NetFw_Put_BlockAllInboundTraffic                        Specifies whether the firewall should not allow inbound traffic
  • _NetFw_Get_NotificationsDisabled                         Indicates whether interactive firewall notifications are disabled
  • _NetFw_Put_NotificationsDisabled                         Specifies whether interactive firewall notifications are disabled
  • _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled  Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
  • _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled  Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
  • _NetFw_Get_Rules                                         Retrieves the interface to collection of firewall rules
  • _NetFw_Get_ServiceRestriction                            Retrieves the interface used to access the Windows Service Hardening store
  • _NetFw_EnableRuleGroup                                   Enables or disables a specified group of firewall rules
  • _NetFw_IsRuleGroupEnabled                                Determines whether a specified group of firewall rules are enabled or disabled for the current profile
  • _NetFw_RestoreLocalFirewallDefaults                      Restores the local firewall configuration to its default state
  • _NetFw_Get_DefaultInboundAction                          Indicates the default action for inbound traffic
  • _NetFw_Put_DefaultInboundAction                          Specifies the default action for inbound traffic
  • _NetFw_Get_DefaultOutboundAction                         Indicates the default action for outbound traffic
  • _NetFw_Put_DefaultOutboundAction                         Specifies the default action for outbound traffic
  • _NetFw_Get_IsRuleGroupCurrentlyEnabled                   Determines whether a specified group of firewall rules are enabled or disabled for the current profile
  • _NetFw_Get_LocalPolicyModifyState                        Determines if adding or setting a rule or group of rules will take effect in the current firewall profile

 

UDF:

Spoiler
;INetFwPolicy2COM.au3
#include-once
;#RequireAdmin

#include <WinAPIConstants.au3> ; $S_OK, $E_NOINTERFACE, $E_NOTIMPL
#include <WinAPIMisc.au3> ; _WinAPI_GetString


; #INDEX# ========================================================================================================================================================================
; Title .........: NetFirewallPolicy2 COM UDF Library for AutoIt3
; AutoIt Version : 3.3.14.5
; Description ...: Windows Firewall Policy2 Interface, Provides access to the firewall policy for Windows Vista+
; Author(s) .....: Bilgus 2018
; ================================================================================================================================================================================
#Region Global Variables and Constants
Global $__g_oINetFwPolicy2

; #CONSTANTS# ====================================================================================================================================================================
Global Enum $NET_FW_PROFILE2_DOMAIN = 0x1, $NET_FW_PROFILE2_PRIVATE = 0x2, $NET_FW_PROFILE2_PUBLIC = 0x4, $NET_FW_PROFILE2_ALL = 0x7FFFFFFF
Global Enum $NET_FW_MODIFY_STATE_OK = 0x0, $NET_FW_MODIFY_STATE_GP_OVERRIDE, $NET_FW_MODIFY_STATE_INBOUND_BLOCKED
Global Enum $NET_FW_ACTION_BLOCK = 0x0, $NET_FW_ACTION_ALLOW, $NET_FW_ACTION_MAX

; #INTERNAL CONSTANTS#============================================================================================================================================================
Global Enum $NET_FW_VARIANT_TRUE = -1, $NET_FW_VARIANT_FALSE = False ;A value 0 will be equal to Boolean False, Any other number value will be equal to Boolean True
Global Enum $NET_FW_VT_VARIANT = 0x000C, $NET_FW_VT_ARRAY = 0x2000, $NET_FW_VT_BSTR = 0x0008
Global Const $NET_FW_UNKNOWNERROR = 0xE

Global Const $dtag_INetFwPolicy2 = _ ; Inherits from IDispatch.
        "GetTypeInfoCount hresult(dword*);" & _ ; Retrieves the number of type information interfaces that an object provides (either 0 or 1).
        "GetTypeInfo hresult(dword;dword;ptr*);" & _ ; Gets the type information for an object.
        "GetIDsOfNames hresult(ptr;ptr;dword;dword;ptr);" & _ ; Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs, which can be used on subsequent calls to Invoke.
        "Invoke hresult(dword;ptr;dword;word;ptr;ptr;ptr;ptr);" & _ ; Provides access to properties and methods exposed by an object.
        "" & _ ;Endof IDispatch
        "get_CurrentProfileTypes          hresult(long*;);" & _ ;Retrieves the currently active firewall profile(s)
        "get_FirewallEnabled              hresult(int;short*);" & _ ;Indicates whether a firewall is enabled locally
        "put_FirewallEnabled              hresult(int;short);" & _ ;Specifies whether a firewall is enabled locally
        "get_ExcludedInterfaces           hresult(int;ptr);" & _ ;Indicates a list of interfaces on which firewall settings are excluded
        "put_ExcludedInterfaces           hresult(int;ptr);" & _ ;Specifies a list of interfaces on which firewall settings are excluded
        "get_BlockAllInboundTraffic       hresult(int;short*);" & _ ;Indicates whether the firewall should not allow inbound traffic
        "put_BlockAllInboundTraffic       hresult(int;short);" & _ ;Specifies whether the firewall should not allow inbound traffic
        "get_NotificationsDisabled        hresult(int;short*);" & _ ;Indicates whether interactive firewall notifications are disabled
        "put_NotificationsDisabled        hresult(int;short);" & _ ;Specifies whether interactive firewall notifications are disabled
        "get_UnicastResponsesToMulticastBroadcastDisabled        hresult(int;short*);" & _ ;Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
        "put_UnicastResponsesToMulticastBroadcastDisabled        hresult(int;short);" & _ ;Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
        "get_Rules                        hresult(ptr);" & _ ;Retrieves the interface to collection of firewall rules
        "get_ServiceRestriction           hresult(ptr);" & _ ;Retrieves the interface used to access the Windows Service Hardening store
        "EnableRuleGroup                  hresult(long;wstr;short);" & _ ;Enables or disables a specified group of firewall rules
        "IsRuleGroupEnabled               hresult(long;wstr;short*);" & _ ;Determines whether a specified group of firewall rules are enabled or disabled for the current profile
        "RestoreLocalFirewallDefaults     hresult();" & _ ;Restores the local firewall configuration to its default state
        "get_DefaultInboundAction         hresult(int;int*);" & _ ;Indicates the default action for inbound traffic
        "put_DefaultInboundAction         hresult(int;int);" & _ ;Specifies the default action for inbound traffic
        "get_DefaultOutboundAction        hresult(int;int*);" & _ ;Indicates the default action for outbound traffic
        "put_DefaultOutboundAction        hresult(int;int);" & _ ;Specifies the default action for outbound traffic
        "get_IsRuleGroupCurrentlyEnabled  hresult(wstr;short*);" & _ ;Determines whether a specified group of firewall rules are enabled or disabled for the current profile
        "get_LocalPolicyModifyState       hresult(int*);" ;Determines if adding or setting a rule or group of rules will take effect in the current firewall profile
; ================================================================================================================================================================================
#EndRegion Global Variables and Constants


#Region Public NetProfile2_Functions
; #CURRENT# ======================================================================================================================================================================
;  _NetFw_EnableRuleGroup
;  _NetFw_Get_BlockAllInboundTraffic
;  _NetFw_Get_CurrentProfileTypes
;  _NetFw_Get_DefaultInboundAction
;  _NetFw_Get_DefaultOutboundAction
;  _NetFw_Get_ExcludedInterfaces
;  _NetFw_Get_FirewallEnabled
;  _NetFw_Get_IsRuleGroupCurrentlyEnabled
;  _NetFw_Get_LocalPolicyModifyState
;  _NetFw_Get_NotificationsDisabled
;  _NetFw_Get_Rules
;  _NetFw_Get_ServiceRestriction
;  _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled
;  _NetFw_Initialize
;  _NetFw_IsRuleGroupEnabled
;  _NetFw_Put_BlockAllInboundTraffic
;  _NetFw_Put_DefaultInboundAction
;  _NetFw_Put_DefaultOutboundAction
;  _NetFw_Put_ExcludedInterfaces
;  _NetFw_Put_FirewallEnabled
;  _NetFw_Put_NotificationsDisabled
;  _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled
;  _NetFw_RestoreLocalFirewallDefaults
; ================================================================================================================================================================================
; #INTERNAL FUNCTIONS#============================================================================================================================================================
;  __CreateVariant
;  __ExtractVariantStrings
;  __GetAdapterNames
;  __GetAdaptersAddresses
;  __IsValidInterface
;  __SafeArrayCreateVector
;  __SafeArrayPutElement
;  __SetVariant
;  __StringArrayToVariantArray
;  __StringToVariant
;  __SysAllocStringLen
;  __SysFreeString
;  __VariantToString
; ================================================================================================================================================================================

; #FUNCTION _NetFw_EnableRuleGroup# ==============================================================================================================================================
; Author.......: Bilgus
; Description..: Enables or disables a specified group of firewall rules
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345), $bEnabled [True, False]
; Returns......: True on success, False on failure
; ================================================================================================================================================================================

Func _NetFw_EnableRuleGroup($iProfileType, $sRuleGroup, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.EnableRuleGroup($iProfileType, $sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_EnableRuleGroup

; #FUNCTION _NetFw_Get_BlockAllInboundTraffic# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether the firewall should not allow inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_BlockAllInboundTraffic($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_BlockAllInboundTraffic($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_BlockAllInboundTraffic

; #FUNCTION _NetFw_Get_CurrentProfileTypes# ======================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the currently active firewall profile(s)
; Parameters...:
; Returns......: $iCurrentProfilesBitMask ($iProfileType) [1|2|4]
; ================================================================================================================================================================================

Func _NetFw_Get_CurrentProfileTypes()
    Local $iResult, $iCurrentProfilesBitMask = 0

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_CurrentProfileTypes($iCurrentProfilesBitMask)
    EndIf

    Return SetError($iResult, Null, $iCurrentProfilesBitMask)
EndFunc   ;==>_NetFw_Get_CurrentProfileTypes

; #FUNCTION _NetFw_Get_DefaultInboundAction# =====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates the default action for inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: $iAction [0, 1, 2], -1 on failure
; ================================================================================================================================================================================

Func _NetFw_Get_DefaultInboundAction($iProfileType)
    Local $iResult, $iAction = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_DefaultInboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, $iAction)
EndFunc   ;==>_NetFw_Get_DefaultInboundAction

; #FUNCTION _NetFw_Get_DefaultOutboundAction# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates the default action for outbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......:
; ================================================================================================================================================================================

Func _NetFw_Get_DefaultOutboundAction($iProfileType)
    Local $iResult, $iAction = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_DefaultOutboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, $iAction)
EndFunc   ;==>_NetFw_Get_DefaultOutboundAction

; #FUNCTION _NetFw_Get_ExcludedInterfaces# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates a list of interfaces on which firewall settings are excluded
; .............: Due to a bug in this function the program architecture must match the OS Arch in order to use this function See below for more information
; .............: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bSupressArchWarning [True, False] Block msgbox error on wrong architecture
; Returns......: $aInterfaces Array of Strings containing friendly name excluded interface, 0 length array on failure or if no excluded interfaces exist
; ================================================================================================================================================================================

Func _NetFw_Get_ExcludedInterfaces($iProfileType, $bSupressArchWarning = False)
    Local Const $MB_ICONERROR = 16
    Local Static $bIsWarned = $bSupressArchWarning
    Local $iResult
    Local $tVariant = __CreateVariant()

    Local $aInterfaces[0]
    If Not @AutoItX64 And @OSArch <> "X86" Then
        If $bIsWarned Then
            ConsoleWriteError("Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces" & @CRLF)
        Else
            MsgBox($MB_ICONERROR, "INetFwPolicy2 Error", "Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces")
        EndIf
        $bIsWarned = True
        Return SetError(1, 0, $aInterfaces)
    EndIf

    While __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize)

        $iResult = $__g_oINetFwPolicy2.get_ExcludedInterfaces($iProfileType, DllStructGetPtr($tVariant))
        If $iResult <> $S_OK Then ExitLoop

        If DllStructGetData($tVariant, "vt") <> BitOR($NET_FW_VT_VARIANT, $NET_FW_VT_ARRAY) Then
            $iResult = $E_NOTIMPL
            ExitLoop
        EndIf

        $aInterfaces = __ExtractVariantStrings(DllStructGetPtr($tVariant))

        ExitLoop
    WEnd

    Return SetError($iResult, Null, $aInterfaces)
EndFunc   ;==>_NetFw_Get_ExcludedInterfaces

; #FUNCTION _NetFw_Get_FirewallEnabled# ==========================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether a firewall is enabled locally
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_FirewallEnabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_FirewallEnabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_FirewallEnabled

; #FUNCTION _NetFw_Get_IsRuleGroupCurrentlyEnabled# ==============================================================================================================================
; Author.......: Bilgus
; Description..: Determines whether a specified group of firewall rules are enabled or disabled for the current profile
; Parameters...: $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345)
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_IsRuleGroupCurrentlyEnabled($sRuleGroup)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_IsRuleGroupCurrentlyEnabled($sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_IsRuleGroupCurrentlyEnabled

; #FUNCTION _NetFw_Get_LocalPolicyModifyState# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Determines if adding or setting a rule or group of rules will take effect in the current firewall profile
; Parameters...:
; Returns......: $iModifyState [0, 1, 2], -1 on failure
; ================================================================================================================================================================================

Func _NetFw_Get_LocalPolicyModifyState()
    Local $iResult, $iModifyState = -1

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_LocalPolicyModifyState($iModifyState)
    EndIf

    Return SetError($iResult, Null, $iModifyState)
EndFunc   ;==>_NetFw_Get_LocalPolicyModifyState

; #FUNCTION _NetFw_Get_NotificationsDisabled# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether interactive firewall notifications are disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_NotificationsDisabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_NotificationsDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_NotificationsDisabled

; #FUNCTION _NetFw_Get_Rules# ====================================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the interface to collection of firewall rules
; Parameters...:
; Returns......: Pointer to INetFwRules Object, Null on failure
; ================================================================================================================================================================================

Func _NetFw_Get_Rules()
    Local $iResult
    Local $tINetFwRules = DllStructCreate("ptr pObject")

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_Rules(DllStructGetPtr($tINetFwRules))
    EndIf

    Return SetError($iResult, Null, DllStructGetData($tINetFwRules, "pObject"))
EndFunc   ;==>_NetFw_Get_Rules

; #FUNCTION _NetFw_Get_ServiceRestriction# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the interface used to access the Windows Service Hardening store
; Parameters...:
; Returns......: Pointer to INetFwServiceRestriction Object, Null on failure
; ================================================================================================================================================================================

Func _NetFw_Get_ServiceRestriction()
    Local $iResult
    Local $tINetFwServiceRestriction = DllStructCreate("ptr pObject")

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_ServiceRestriction(DllStructGetPtr($tINetFwServiceRestriction))
    EndIf

    Return SetError($iResult, Null, DllStructGetData($tINetFwServiceRestriction, "pObject"))
EndFunc   ;==>_NetFw_Get_ServiceRestriction

; #FUNCTION _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled# =============================================================================================================
; Author.......: Bilgus
; Description..: Indicates whether the firewall should not allow unicast responses to multicast and broadcast traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled($iProfileType)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.get_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_Get_UnicastResponsesToMulticastBroadcastDisabled

; #FUNCTION _NetFw_Initialize# ===================================================================================================================================================
; Author.......: Bilgus
; Description..: Initializes NetFwPolicy2 Interface Returns True if Interface is valid False if not
; .............: Called automatically on first use of a _NetFw_ function
; Parameters...: $bInitialize [True, False - Frees interface]
; Returns......: True, False
; ================================================================================================================================================================================

Func _NetFw_Initialize($bInitialize = True)
    Local $iResult
    If $bInitialize Then
        Local $oObj = ObjCreate("HNetCfg.FwPolicy2")
        Local $sIID = ObjName($oObj, 7) ;Get sIID

        ;Redefine the v-table with our own definitions
        $__g_oINetFwPolicy2 = ObjCreateInterface($oObj, $sIID, $dtag_INetFwPolicy2)
        $iResult = @error
        ;sIID_INetFwPolicy2 = "{98325047-C671-4174-8D81-DEFCD3F03186}"
        ;sCLSID_NetFwPolicy2 = "{E2B3C97F-6AE1-41AC-817A-F6F92166D7DD}"
    Else
        $__g_oINetFwPolicy2 = 0
    EndIf

    If $iResult Or (Not IsObj($__g_oINetFwPolicy2)) Then $bInitialize = False

    Return SetError($iResult, Null, $bInitialize)
EndFunc   ;==>_NetFw_Initialize

; #FUNCTION _NetFw_IsRuleGroupEnabled# ===========================================================================================================================================
; Author.......: Bilgus
; Description..: Determines whether a specified group of firewall rules are enabled or disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $sRuleGroup [Literal name of group or Dll String (@ExFWDll.dll, -12345)
; Returns......: True if enabled False if disabled or doesn't exist
; ================================================================================================================================================================================

Func _NetFw_IsRuleGroupEnabled($iProfileType, $sRuleGroup)
    Local $iResult, $bEnabled = False

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.IsRuleGroupEnabled($iProfileType, $sRuleGroup, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($bEnabled = True))
EndFunc   ;==>_NetFw_IsRuleGroupEnabled

; #FUNCTION _NetFw_Put_BlockAllInboundTraffic# ===================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether the firewall should not allow inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_BlockAllInboundTraffic($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_BlockAllInboundTraffic($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_BlockAllInboundTraffic

; #FUNCTION _NetFw_Put_DefaultInboundAction# =====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies the default action for inbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $iAction [0, 1, 2]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_DefaultInboundAction($iProfileType, $iAction)
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_DefaultInboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_DefaultInboundAction

; #FUNCTION _NetFw_Put_DefaultOutboundAction# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies the default action for outbound traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $iAction [0, 1, 2]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_DefaultOutboundAction($iProfileType, $iAction)
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_DefaultOutboundAction($iProfileType, $iAction)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_DefaultOutboundAction

; #FUNCTION _NetFw_Put_ExcludedInterfaces# =======================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies a list of interfaces on which firewall settings are excluded
; .............: Due to a bug in this function the program architecture must match the OS Arch in order to use this function See below for more information
; .............: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $aInterfaces [String Array containg names of interfaces to exclude], $bSupressArchWarning [True, False] Block msgbox error on wrong architecture
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_ExcludedInterfaces($iProfileType, $aInterfaces, $bSupressArchWarning = False)
    Local Const $MB_ICONERROR = 16
    Local Static $bIsWarned = $bSupressArchWarning

    If Not @AutoItX64 And @OSArch <> "X86" Then
        If $bIsWarned Then
            ConsoleWriteError("Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces" & @CRLF)
        Else
            MsgBox($MB_ICONERROR, "INetFwPolicy2 Error", "Compiled Architecture must equal OS Architecture in order to use ExcludedInterfaces")
        EndIf
        $bIsWarned = True
        Return SetError(1, Null, False)
    EndIf

    Local $iResult
    Local $aNeedsFreed[0] ;Returns variant structs containing Bstr's that need freed
    Local $pSafeArray ;Needed to keep valid reference

    Local $aValidInterfaces[UBound($aInterfaces)]

    ;Remove Invalid Interfaces from list.. ALL Interface names must be valid otherwise the function crashes
    Local $sAdapterNames = __GetAdapterNames()

    Local $j = 0
    For $i = 0 To UBound($aInterfaces) - 1
        If StringInStr($sAdapterNames, $aInterfaces[$i] & ";") > 0 Then
            $aValidInterfaces[$j] = $aInterfaces[$i]
            $j += 1
        EndIf
    Next
    ReDim $aValidInterfaces[$j]

    Local $tVariant = __StringArrayToVariantArray($aValidInterfaces, $pSafeArray, $aNeedsFreed)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_ExcludedInterfaces($iProfileType, DllStructGetPtr($tVariant))
    EndIf

    For $i = 0 To UBound($aNeedsFreed) - 1
        ;Free Bstr's
        __SysFreeString(DllStructGetData($aNeedsFreed[$i], "data"))
    Next

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_ExcludedInterfaces

; #FUNCTION _NetFw_Put_FirewallEnabled# ==========================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether a firewall is enabled locally (the effective result may differ due to group policy settings)
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_FirewallEnabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_FirewallEnabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_FirewallEnabled

; #FUNCTION _NetFw_Put_NotificationsDisabled# ====================================================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether interactive firewall notifications are disabled
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_NotificationsDisabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_NotificationsDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_NotificationsDisabled

; #FUNCTION _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled# =============================================================================================================
; Author.......: Bilgus
; Description..: Specifies whether the firewall should not allow unicast responses to multicast and broadcast traffic
; Parameters...: $iProfileType [1,2,4,0x7FFFFFFF], $bEnabled [True, False]
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    Local $iResult
    $bEnabled = ($bEnabled ? $NET_FW_VARIANT_TRUE : $NET_FW_VARIANT_FALSE)

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.put_UnicastResponsesToMulticastBroadcastDisabled($iProfileType, $bEnabled)
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_Put_UnicastResponsesToMulticastBroadcastDisabled

; #FUNCTION _NetFw_RestoreLocalFirewallDefaults# =================================================================================================================================
; Author.......: Bilgus
; Description..: Restores the local firewall configuration to its default state
; Parameters...:
; Returns......: True on success False on failure
; ================================================================================================================================================================================

Func _NetFw_RestoreLocalFirewallDefaults()
    Local $iResult

    If __IsValidInterface($__g_oINetFwPolicy2, $iResult, _NetFw_Initialize) Then
        $iResult = $__g_oINetFwPolicy2.RestoreLocalFirewallDefaults()
    EndIf

    Return SetError($iResult, Null, ($iResult = $S_OK))
EndFunc   ;==>_NetFw_RestoreLocalFirewallDefaults
#EndRegion Public NetProfile2_Functions

#Region Internal_Functions

; #FUNCTION CreateVariant# =======================================================================================================================================================
; Author.......: Bilgus
; Description..: Creates a Variant sized to the OS architecture 64bit Os Variants are 24 bytes where as X86 uses 16 byte Variants
; Parameters...:
; Returns......: $tVariant (DllStruct Sized Appropriately)
; ================================================================================================================================================================================

Func __CreateVariant()
    Local Const $tagVARIANT_PTR = "word vt;word r1;word r2;word r3;ptr data; ptr"
    ; Thanks @AutoItObject-Team, LarsJ?
    ; The Variant structure takes up 16/24 bytes when running 32/64 bit
    ; Space for the data element at the end represents 2 pointers
    ; This is 8 bytes running 32 bit and 16 bytes running 64 bit

    Local $tVariant = DllStructCreate($tagVARIANT_PTR)

    Return $tVariant
EndFunc   ;==>__CreateVariant

; #FUNCTION ExtractVariantStrings# ===============================================================================================================================================
; Author.......: Bilgus
; Description..: Extracts Strings from Passed Variant Array and places them into an Autoit Array
; Parameters...: $pVariant (Pointer to a Variant)
; Returns......: Array containg each string on success Empty array on failure or if no strings were contained
; ================================================================================================================================================================================

Func __ExtractVariantStrings($pVariant, $sSeparator = "; ")
    Local Const $STR_ENTIRESPLIT = 1, $STR_NOCOUNT = 2
    Local $aEmpty[0]

    If Not $pVariant Then Return SetError(1, 0, $aEmpty)

    Local $sStrings = __VariantToString($pVariant)

    Return SetError(@error, Null, StringSplit($sStrings, $sSeparator, BitOR($STR_ENTIRESPLIT, $STR_NOCOUNT)))
EndFunc   ;==>__ExtractVariantStrings

; #FUNCTION GetAdapterNames# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Uses GetAdaptersAddresses to retrieve a string of adapter FriendlyNames on the computer each name is separated by $sSeparator
; Parameters...: $sSeparator = ";"
; Returns......: String containg adaptor FriendlyNames on success Empty String on failure
; ================================================================================================================================================================================

Func __GetAdapterNames($sSeparator = ";")
    Local Enum Step *2 $GAA_FLAG_SKIP_UNICAST = 0x1, $GAA_FLAG_SKIP_ANYCAST, $GAA_FLAG_SKIP_MULTICAST, $GAA_FLAG_SKIP_DNS_SERVER
    Local $iFlags = BitOR($GAA_FLAG_SKIP_UNICAST, $GAA_FLAG_SKIP_ANYCAST, $GAA_FLAG_SKIP_MULTICAST, $GAA_FLAG_SKIP_DNS_SERVER)

    Local Const $tagIP_ADAPTER_FRIENDLYNAME = "ulong;dword;ptr Next;ptr;ptr;ptr;ptr;ptr;ptr;ptr; ptr FriendlyName;"
    Local $tIP_ADAPTER_FRIENDLYNAME, $sAdapterNames = ""

    Local $tBuf_AdapterAddresses = __GetAdaptersAddresses(0, $iFlags)
    Local $iError = @error

    While Not $iError
        Local $pBuf_AdapterAddress = DllStructGetPtr($tBuf_AdapterAddresses)

        While $pBuf_AdapterAddress
            $tIP_ADAPTER_FRIENDLYNAME = DllStructCreate($tagIP_ADAPTER_FRIENDLYNAME, $pBuf_AdapterAddress)
            $sAdapterNames &= _WinAPI_GetString(DllStructGetData($tIP_ADAPTER_FRIENDLYNAME, "FriendlyName")) & $sSeparator
            $iError = @error
            If $iError Then ExitLoop
            $pBuf_AdapterAddress = DllStructGetData($tIP_ADAPTER_FRIENDLYNAME, "Next")
        WEnd
        ExitLoop
    WEnd

    Return SetError($iError, Null, $sAdapterNames)
EndFunc   ;==>__GetAdapterNames

; #FUNCTION GetAdaptersAddresses# ================================================================================================================================================
; Author.......: Bilgus
; Description..: Retrieves the addresses associated with the adapters on the local computer
; Parameters...: $iFamily = 0 [0,2,23], $iFlags = 0 [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400]
; Returns......: $tBuf_AdapterAddresses[DllStruct Buffer for further processing of data], Empty variable on Failure
; ================================================================================================================================================================================

Func __GetAdaptersAddresses($iFamily = 0, $iFlags = 0)
    Local Const $ERROR_BUFFER_OVERFLOW = 0x6F
    Local $iError = $ERROR_BUFFER_OVERFLOW
    Local $iSzBuffer = 16000 ;Initial Buffer
    Local $iRetries = 3
    Local $aRet, $tBuf_AdapterAddresses
    Local $hIphlpapi = DllOpen("Iphlpapi.dll")
    While $iRetries > 0
        If Not $hIphlpapi Then
            $iError = $NET_FW_UNKNOWNERROR
            ExitLoop
        EndIf

        While $iError = $ERROR_BUFFER_OVERFLOW And $iRetries > 0
            $iRetries -= 1
            $tBuf_AdapterAddresses = DllStructCreate("byte[" & $iSzBuffer & "]")

            $aRet = DllCall($hIphlpapi, "ulong", "GetAdaptersAddresses", _
                    "ulong", $iFamily, _
                    "ulong", $iFlags, _
                    "ptr", Null, _
                    "ptr", DllStructGetPtr($tBuf_AdapterAddresses), _
                    "dword*", $iSzBuffer)

            If Not @error And IsArray($aRet) Then
                $iError = $aRet[0]
                If $aRet[0] = $ERROR_BUFFER_OVERFLOW Then
                    If $iSzBuffer <= DllStructGetSize($tBuf_AdapterAddresses) Then ExitLoop
                    ContinueLoop
                EndIf
            Else
                $iError = @error
            EndIf

            ExitLoop
        WEnd
        ExitLoop
    WEnd

    DllClose($hIphlpapi)
    Return SetError($iError, Null, $tBuf_AdapterAddresses)
EndFunc   ;==>__GetAdaptersAddresses

; #FUNCTION IsValidInterface# ====================================================================================================================================================
; Author.......: Bilgus
; Description..: Checks if passed Object Variable is an Object
; Parameters...: $oInterface[Object], ByRef $iResult, $fInit[function that attempts to (re) initialize object
; Returns......: True if $oInterface is an object, False on failure and iResult is set to $E_NOINTERFACE
; ================================================================================================================================================================================

Func __IsValidInterface(ByRef $oInterface, ByRef $iResult, $fInit = 0)
    If Not IsObj($oInterface) And $fInit <> 0 Then Call($fInit)
    If @error = 0xDEAD Then ConsoleWriteError("Invalid Init Function" & @CRLF)

    If Not IsObj($oInterface) Then
        ConsoleWriteError("Failed To Retrieve Interface" & @CRLF)
        $iResult = $E_NOINTERFACE
        Return SetError($iResult, Null, False)
    EndIf

    Return True
EndFunc   ;==>__IsValidInterface

; #FUNCTION SafeArrayCreateVector# ===============================================================================================================================================
; Author.......: Bilgus
; Description..: Creates a fixed size one-dimensional array
; Parameters...: $iVType[ushort VARTYPE (VT_EMPTY and VT_NULL are not allowed)], $iElements[Integer Number of elements to create], $iLBound = 0[Integer Lower bound of array]
; Returns......: Pointer to SafeArray on success Null on failure
; ================================================================================================================================================================================

Func __SafeArrayCreateVector($iVType, $iElements, $iLBound = 0, $vDll = "OleAut32.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "ptr", "SafeArrayCreateVector", "ushort", $iVType, "long", $iLBound, "ulong", $iElements)

    If Not @error And IsArray($aRet) Then
        If $aRet[0] <> Null Then
            Return $aRet[0]
        EndIf
        $iError = $NET_FW_UNKNOWNERROR
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, Null)
EndFunc   ;==>__SafeArrayCreateVector

; #FUNCTION SafeArrayPutElement# =================================================================================================================================================
; Author.......: Bilgus
; Description..: Stores $pdata at the specified element location in the array
; Parameters...: $pSafeArray[Pointer to SafeArray], $iIndex[Integer element to place data], $pData[Pointer to data to be inserted]
; Returns......: True on success False on error
; ================================================================================================================================================================================

Func __SafeArrayPutElement($pSafeArray, $iIndex, $pData, $vDll = "OleAut32.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "long", "SafeArrayPutElement", "ptr", $pSafeArray, "long*", $iIndex, "ptr", $pData)

    If Not @error And IsArray($aRet) Then
        $iError = $aRet[0]
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, ($iError = $S_OK))
EndFunc   ;==>__SafeArrayPutElement

; #FUNCTION SetVariant# ==========================================================================================================================================================
; Author.......: Bilgus
; Description..: Stores $iVarType and $pData at the specified element location in the variant
; Parameters...: $tVariant[DllStruct Variant], $VarType[The VT_* Constant], $pData[Pointer to data to be inserted]
; Returns......: True on success False on error
; ================================================================================================================================================================================

Func __SetVariant(ByRef $tVariant, $iVarType, $pData)

    Local $iError
    If IsDllStruct($tVariant) Then
        If Not DllStructSetData($tVariant, "vt", $iVarType) Then $iError = BitOR($iError, 1)
        If Not DllStructSetData($tVariant, "data", $pData) Then $iError = BitOR($iError, 2)
    Else
        $iError = 3
    EndIf

    Return SetError($iError, Null, ($iError = 0))
EndFunc   ;==>__SetVariant

; #FUNCTION StringArrayToVariantArray# ===========================================================================================================================================
; Author.......: Bilgus
; Description..: Copies an array of AutoIt strings into a variant array each string is Converted to a BSTR and Placed in a separate Variant
; .............: Top Level Variant is of type (VT_VARIANT|VT_ARRAY) each sub Variant is type (VT_BSTR) and contains an individual BSTR
;..............: $aNeedsFreed holds the sub level variants, The BSTRs within each needs freed when you are finished using them
;..............: $pSafeArray should be passed in as an empty variable to hold a reference to the SafeArray data
;..............: $aNeedsFreed should be an empty array in the form of $aNeedsFreed[0] the function will redim it as necessary
;..............: $tVariant will be a completely empty variant if there are no strings passed within $aArrStrings
; Parameters...: $aArrStrings, ByRef $pSafeArray[EMPTY VARIABLE], ByRef $aNeedsFreed[0]{0 dim array}
; Returns......: $tVariant (DllStruct Containg the Passed Strings)
; ================================================================================================================================================================================

Func __StringArrayToVariantArray($aArrStrings, ByRef $pSafeArray, ByRef $aNeedsFreed)
    ;NOTE!, You Need To Free pBstr's When you are finished with them
    ;$aNeedsFreed Returns variants containg the Bstr's
    Local $iError
    Local $tVariant = __CreateVariant()
    Local $iCtStrings = UBound($aArrStrings)
    ReDim $aNeedsFreed[$iCtStrings]
    While $iCtStrings > 0 ;If The array is empty we want to return empty variant
        $pSafeArray = __SafeArrayCreateVector($NET_FW_VT_VARIANT, $iCtStrings)
        $iError = @error
        If $iError Then ExitLoop

        For $i = 0 To $iCtStrings - 1
            $aNeedsFreed[$i] = __CreateVariant();Create a sub Variant to hold the BSTR

            __StringToVariant($aArrStrings[$i], $aNeedsFreed[$i])
            $iError = @error
            If $iError Then ExitLoop

            __SafeArrayPutElement($pSafeArray, $i, DllStructGetPtr($aNeedsFreed[$i]))
            $iError = @error
            If $iError Then ExitLoop
        Next

        If Not $iError Then
            __SetVariant($tVariant, BitOR($NET_FW_VT_VARIANT, $NET_FW_VT_ARRAY), $pSafeArray)
            $iError = @error
        EndIf

        ExitLoop
    WEnd
    Return SetError($iError, Null, $tVariant)
EndFunc   ;==>__StringArrayToVariantArray

; #FUNCTION StringToVariant# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Copies an AutoIt string into an allocated BSTR Which is placed into a Variant with type VT_BSTR
; Parameters...: $sString, ByRef $tVariant (Variant DllStruct)
; Returns......: True on Success False on Failure
; ================================================================================================================================================================================

Func __StringToVariant($sString, ByRef $tVariant)
    ;NOTE!, YOU Need To Free pBstr When you are finished with it ;__SysFreeString($pBstr)
    Local $pBstr = __SysAllocStringLen($sString)
    Local $iError = @error

    If Not $iError And $pBstr Then
        __SetVariant($tVariant, $NET_FW_VT_BSTR, $pBstr)
        $iError = @error
    Else
        __SetVariant($tVariant, 0, 0)
        $iError = BitOR(@error, $iError)
    EndIf

    Return SetError($iError, Null, ($iError = 0))
EndFunc   ;==>__StringToVariant

; #FUNCTION SysAllocStringLen# ======================================================================================================================================================
; Author.......: Bilgus
; Description..: Allocates a new BSTR and copies the passed AutoIt string into it.
; Parameters...: $sString
; Returns......: NULL on error otherwise pointer to system allocated BSTR
; ================================================================================================================================================================================

Func __SysAllocStringLen($sString, $vDll = "OleAut32.dll")
    ;NOTE!, YOU Need To Free pBstr When you are finished with it ;__SysFreeString($pBstr)
    Local $iError

    Local $aRet = DllCall($vDll, "ptr", "SysAllocStringLen", "wstr", $sString, "uint", StringLen($sString))

    If Not @error And IsArray($aRet) Then
        If $aRet[0] <> Null Then
            Return $aRet[0]
        Else
            $iError = $NET_FW_UNKNOWNERROR
        EndIf
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, Null)
EndFunc   ;==>__SysAllocStringLen

; #FUNCTION SysFreeString# =======================================================================================================================================================
; Author.......: Bilgus
; Description..: Frees a SysAllocString
; Parameters...: $pBstr (Pointer to a BSTR)
; Returns......: None
; ================================================================================================================================================================================

Func __SysFreeString($pBstr, $vDll = "OleAut32.dll")
    DllCall($vDll, "NONE", "SysFreeString", "ptr", $pBstr)
    Return SetError(@error, Null, (@error = 0))
EndFunc   ;==>__SysFreeString

; #FUNCTION VariantToString# =====================================================================================================================================================
; Author.......: Bilgus
; Description..: Converts VT_BSTR to an AutoIt string
; Parameters...: $pVariant (Pointer to a Variant)
; Returns......: String Contained in passed Variant
; ================================================================================================================================================================================

Func __VariantToString($pVariant, $vDll = "Propsys.dll")
    Local $iError
    Local $aRet = DllCall($vDll, "long", "VariantToString", "ptr", $pVariant, "wstr", "", "uint", 65535)

    If Not @error And IsArray($aRet) Then
        If $aRet[0] = $S_OK Then
            Return $aRet[2]
        Else
            $iError = $aRet[0]
        EndIf
    Else
        $iError = @error
    EndIf

    Return SetError($iError, Null, "")
EndFunc   ;==>__VariantToString
#EndRegion Internal_Functions

 

Test Script:

Spoiler
;Test Script For INetFWPolicy2
#RequireAdmin

#include <INetFwPolicy2COM.au3>
#include <GUIConstantsEx.au3>

Global $sOutputAccumulated

;_NetFw_Initialize(True) ;Initialize interface done automatic on first use of a function

Test_Get_CurrentProfileTypes()
Test_Get_LocalPolicyModifyState()
Test_FirewallEnabled()
Test_ExcludedInterfaces()
Test_Rules()
Test_ServiceRestriction()
Test_RuleGroupEnabled()
Test_DefaultAction()

_NetFw_Initialize(False) ;Un-Initialize (Frees) Interface

$sOutputAccumulated &= "Done!" & @CRLF

Global $hGUI = GUICreate("INetFWPolicy2", 600, 400)
Global $idEdit = GUICtrlCreateEdit($sOutputAccumulated, 5, 5, 590, 390)

; Display the GUI.
GUISetState(@SW_SHOW, $hGUI)

; Loop until the user exits.
While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE, $idOK
            ExitLoop

    EndSwitch
WEnd

; Delete the GUI and all controls.
GUIDelete($hGUI)
Exit

Func Test_DefaultAction()
    WriteOutput("Default Inbound/Outbound Actions:" & @CRLF)
    Local $DefaultOutbound = _NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)
    Local $DefaultInbound = _NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)
    WriteOutput("Private Outbound: " & DefaultActionToString($DefaultOutbound) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString($DefaultInbound) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_BLOCK)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_BLOCK)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_ALLOW)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_ALLOW)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_MAX)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $NET_FW_ACTION_MAX)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE, $DefaultOutbound)
    _NetFw_Put_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE, $DefaultInbound)
    WriteOutput("Private Outbound: " & DefaultActionToString(_NetFw_Get_DefaultOutboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF)
    WriteOutput("Private Inbound: " & DefaultActionToString(_NetFw_Get_DefaultInboundAction($NET_FW_PROFILE2_PRIVATE)) & @CRLF & @CRLF)
EndFunc   ;==>Test_DefaultAction

Func Test_ExcludedInterfaces()
    WriteOutput("get Excluded Interfaces:" & @CRLF)

    WriteOutput("Domain: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_DOMAIN)) & @CRLF)

    Local $aPrivateExcluded = _NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE) ; For restoration..
    WriteOutput("Private: " & @CRLF & PrintArray($aPrivateExcluded) & @CRLF)

    WriteOutput("Public: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PUBLIC)) & @CRLF)

    WriteOutput(@CRLF)
    WriteOutput("Put Excluded Interfaces:" & @CRLF)

    Local $aInterfaces[4] = ["Wireless Network Connection", "Wireless Network Connection 2", "Local Area Connection", "Local Area Connection 2"]
    _NetFw_Put_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE, $aInterfaces)

    WriteOutput("Private: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE, $aPrivateExcluded)

    WriteOutput("Private: " & @CRLF & PrintArray(_NetFw_Get_ExcludedInterfaces($NET_FW_PROFILE2_PRIVATE)) & @CRLF)

EndFunc   ;==>Test_ExcludedInterfaces

Func Test_FirewallEnabled()
    WriteOutput("Firewall Enabled:" & @CRLF)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_DOMAIN)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_PUBLIC)
    Toggle_FirewallEnabled($NET_FW_PROFILE2_PRIVATE)
EndFunc   ;==>Test_FirewallEnabled

Func Test_Get_CurrentProfileTypes()
    Local $iCurrentProfilesBitMask = _NetFw_Get_CurrentProfileTypes()
    Local $sProfiles = "CurrentProfiles: " & ProfileTypeToString($iCurrentProfilesBitMask)
    WriteOutput($sProfiles & @CRLF & @CRLF)
EndFunc   ;==>Test_Get_CurrentProfileTypes

Func Test_Get_LocalPolicyModifyState()
    Local $iModifyState = _NetFw_Get_LocalPolicyModifyState()
    WriteOutput("Policy Modify State: " & ModifyStateToString($iModifyState) & @CRLF & @CRLF)
EndFunc   ;==>Test_Get_LocalPolicyModifyState

Func Test_RuleGroupEnabled()
    WriteOutput("Rule Group Enabled:" & @CRLF)
    Local $bEnabled = _NetFw_Get_IsRuleGroupCurrentlyEnabled("Remote Assistance")
    WriteOutput("Remote Assistance Current Profile: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF)
    _NetFw_EnableRuleGroup($NET_FW_PROFILE2_PRIVATE, "Remote Assistance", Not $bEnabled)

    $bEnabled = _NetFw_Get_IsRuleGroupCurrentlyEnabled("Remote Assistance")
    WriteOutput("Remote Assistance Current Profile: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF)
    _NetFw_EnableRuleGroup($NET_FW_PROFILE2_PRIVATE, "Remote Assistance", Not $bEnabled)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    $bEnabled = _NetFw_IsRuleGroupEnabled($NET_FW_PROFILE2_PRIVATE, "Remote Assistance")
    WriteOutput("Remote Assistance: " & ($bEnabled ? "True" : "False") & @CRLF & @CRLF)

EndFunc   ;==>Test_RuleGroupEnabled

Func Test_Rules()
    WriteOutput("Pointer INetFwRule = " & Hex(_NetFw_Get_Rules()) & @CRLF & @CRLF)
EndFunc   ;==>Test_Rules

Func Test_ServiceRestriction()
    WriteOutput("Pointer INetFwServiceRestriction = " & Hex(_NetFw_Get_ServiceRestriction()) & @CRLF & @CRLF)
EndFunc   ;==>Test_ServiceRestriction

Func DefaultActionToString($iAction)
    Local $sAction
    Switch $iAction
        Case $NET_FW_ACTION_BLOCK
            $sAction = "Block"
        Case $NET_FW_ACTION_ALLOW
            $sAction = "Allow"
        Case $NET_FW_ACTION_MAX
            $sAction = "Max"
        Case Else
            $sAction = "Error"
    EndSwitch
    Return $sAction
EndFunc   ;==>DefaultActionToString

Func ModifyStateToString($iModifyState)
    Local $sModifyState
    Switch $iModifyState
        Case $NET_FW_MODIFY_STATE_OK
            $sModifyState = "OK"
        Case $NET_FW_MODIFY_STATE_GP_OVERRIDE
            $sModifyState = "Group Policy Override"
        Case $NET_FW_MODIFY_STATE_INBOUND_BLOCKED
            $sModifyState = "Inbound Blocked"
        Case Else
            $sModifyState = "Error"
    EndSwitch
    Return $sModifyState
EndFunc   ;==>ModifyStateToString

Func PrintArray($aArr)
    $sRet = ""
    If IsArray($aArr) Then
        For $i = 0 To UBound($aArr) - 1
            $sRet &= $aArr[$i] & @CRLF
        Next
    EndIf
    Return $sRet
EndFunc   ;==>PrintArray

Func ProfileTypeToString($iProfileType)
    Local $sProfiles
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_DOMAIN) ? "Domain" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_PRIVATE) ? "Private" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_PUBLIC) ? "Public" : "")
    $sProfiles &= (BitAND($iProfileType, $NET_FW_PROFILE2_ALL) = $NET_FW_PROFILE2_ALL ? "All " : "")
    If $sProfiles = "" Then $sProfiles = "FAILED "
    Return $sProfiles
EndFunc   ;==>ProfileTypeToString

Func Toggle_FirewallEnabled($iProfileType)
    Local Const $sFw = "Firewall Profile "
    Local $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF)

    _NetFw_Put_FirewallEnabled($iProfileType, Not $bEnabled)

    $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF)

    WriteOutput(@CRLF & "Restoring..." & @CRLF)
    _NetFw_Put_FirewallEnabled($iProfileType, Not $bEnabled)

    $bEnabled = _NetFw_Get_FirewallEnabled($iProfileType)
    If Not @error Then WriteOutput($sFw & ProfileTypeToString($iProfileType) & ($bEnabled ? " Enabled" : " Disabled") & @CRLF & @CRLF)
EndFunc   ;==>Toggle_FirewallEnabled

Func WriteOutput($sOutput)

    $sOutputAccumulated &= $sOutput
    ConsoleWrite($sOutput)

EndFunc   ;==>WriteOutput

 

 

Edited by Bilgus
UDF wasn't posted
Link to comment
Share on other sites

Note: In order to use get/put_ExcludedInterfaces your script must be the same architecture as the underlying OS

so if you are running x64 Windows your script should be x64 as well otherwise it returns random junk

Apparently this is a known bug but MS isn't going to fix it So this udf pops a warning and skips the function

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/85c2bac4-5216-466d-a622-d6806d1a18c5/disabling-firewall-interface-using-inetfwpolicy2-fails-with-windows-64-bits?forum=wfp

Edited by Bilgus
Link to comment
Share on other sites

Found an Error in __SysFreeString($pBstr)
Should be:

Func __SysFreeString($pBstr)
    DllCall("OleAut32.dll", "NONE", "SysFreeString", "ptr", $pBstr)
    Return SetError(@error, 0, (@error = 0))
EndFunc   ;==>__SysFreeString

Added: _NetFw_Initialize() to allow Initialization or un-initialize interface

Cleaned Up a few things thanks @ptrex

Changed: Initialization func, Switched to wstr directly instead of ptr to wchar in GroupEnabled funcs and SysAllocStringLen

Edited by Bilgus
Link to comment
Share on other sites

This UDF should be adde here:
https://www.autoitscript.com/wiki/User_Defined_Functions#Windows

remark: temporary I can't login to WiKi 

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Will do :) 

Edit: Done

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

  • 4 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...