Click here to Skip to main content
16,012,153 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
SQL
Hi,
How can I create exception of my application in windows firewall, using vb.net code?

Thanks
Posted
Comments
Logi Guna 24-Jan-13 9:32am    
see my edited answer. TypeLibType( ... is now emitted correctly. thanks
Member 8474866 10-Oct-16 11:52am    
Logi, this is a wonderful submission. The code works wonderfully. However, this code only adds INBOUND rules/exceptions to the Windows Firewall, and not OUTBOUND. Can you assist in explaining how to modify it so OUTBOUND rules can be added as well? Thanks again for this wonderful function.

1 solution

VB
Imports System.Runtime.InteropServices

''' <summary>
''' A minimal-build class for accessing Windows Firewall
''' </summary>
Friend Class WinFirewall

    ' Windows Firewall Interfaces
    ' Main page: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366449%28v=VS.85%29.aspx

    ' To reduce code size, some interface member has been modified
    ' Actual implementation code preserved as comment

    <Guid("F7898AF5-CAC4-4632-A2EC-DA06E5111AF2"), TypeLibType(4160S)> _
    Friend Interface INetFwMgr
        ReadOnly Property LocalPolicy() As <MarshalAs(UnmanagedType.Interface)> INetFwPolicy
        ReadOnly Property CurrentProfileType() As NET_FW_PROFILE_TYPE_
        Sub RestoreDefaults()
        Sub IsPortAllowed(<[In](), MarshalAs(UnmanagedType.BStr)> ByVal imageFileName As String, <[In]()> ByVal IpVersion As NET_FW_IP_VERSION_, <[In]()> ByVal portNumber As Integer, <[In](), MarshalAs(UnmanagedType.BStr)> ByVal localAddress As String, <[In]()> ByVal ipProtocol As NET_FW_IP_PROTOCOL_, <Out(), MarshalAs(UnmanagedType.Struct)> ByRef allowed As Object, <Out(), MarshalAs(UnmanagedType.Struct)> ByRef restricted As Object)
        Sub IsIcmpTypeAllowed(<[In]()> ByVal IpVersion As NET_FW_IP_VERSION_, <[In](), MarshalAs(UnmanagedType.BStr)> ByVal localAddress As String, <[In]()> ByVal Type As Byte, <Out(), MarshalAs(UnmanagedType.Struct)> ByRef allowed As Object, <Out(), MarshalAs(UnmanagedType.Struct)> ByRef restricted As Object)
    End Interface

    <Guid("D46D2478-9AC9-4008-9DC7-5563CE5536CC"), TypeLibType(4160S)> _
    Friend Interface INetFwPolicy
        ReadOnly Property CurrentProfile() As <MarshalAs(UnmanagedType.Interface)> INetFwProfile
        Function GetProfileByType(<[In]()> ByVal profileType As NET_FW_PROFILE_TYPE_) As <MarshalAs(UnmanagedType.Interface)> INetFwProfile
    End Interface

    <Guid("174A0DDA-E9F9-449D-993B-21AB667CA456"), TypeLibType(4160S)> _
    Friend Interface INetFwProfile
        ReadOnly Property Type() As NET_FW_PROFILE_TYPE_
        Property FirewallEnabled() As Boolean
        Property ExceptionsNotAllowed() As Boolean
        Property NotificationsDisabled() As Boolean
        Property UnicastResponsesToMulticastBroadcastDisabled() As Boolean
        ' ReadOnly Property RemoteAdminSettings As <MarshalAs(UnmanagedType.Interface)> INetFwRemoteAdminSettings
        ReadOnly Property RemoteAdminSettings() As Object
        ' ReadOnly Property IcmpSettings As <MarshalAs(UnmanagedType.Interface)> INetFwIcmpSettings
        ReadOnly Property IcmpSettings() As Object
        ' ReadOnly Property GloballyOpenPorts As <MarshalAs(UnmanagedType.Interface)> INetFwOpenPorts
        ReadOnly Property GloballyOpenPorts() As Object
        ' ReadOnly Property Services As <MarshalAs(UnmanagedType.Interface)> INetFwServices
        ReadOnly Property Services() As Object
        ReadOnly Property AuthorizedApplications() As <MarshalAs(UnmanagedType.Interface)> INetFwAuthorizedApplications
    End Interface

    <Guid("644EFD52-CCF9-486C-97A2-39F352570B30"), TypeLibType(4160S)> _
    Friend Interface INetFwAuthorizedApplications
        Inherits IEnumerable

        ReadOnly Property Count() As Integer
        Sub Add(<[In](), MarshalAs(UnmanagedType.Interface)> ByVal app As INetFwAuthorizedApplication)
        Sub Remove(<[In](), MarshalAs(UnmanagedType.BStr)> ByVal imageFileName As String)
        Function Item(<[In](), MarshalAs(UnmanagedType.BStr)> ByVal imageFileName As String) As <MarshalAs(UnmanagedType.Interface)> INetFwAuthorizedApplication

        ' <TypeLibFunc(1S), DispId(-4)> _
        ' Function GetEnumerator() As <MarshalAs(UnmanagedType.CustomMarshaler, MarshalType:="", MarshalTypeRef:=GetType(EnumeratorToEnumVariantMarshaler), MarshalCookie:="")> IEnumerator

    End Interface

    <Guid("B5E64FFA-C2C5-444E-A301-FB5E00018050"), TypeLibType(4160S)> _
    Friend Interface INetFwAuthorizedApplication
        Property Name() As <MarshalAs(UnmanagedType.BStr)> String
        Property ProcessImageFileName() As <MarshalAs(UnmanagedType.BStr)> String
        Property IpVersion() As NET_FW_IP_VERSION_
        Property Scope() As NET_FW_SCOPE_
        Property RemoteAddresses() As <MarshalAs(UnmanagedType.BStr)> String
        Property Enabled() As Boolean
    End Interface

    Friend Enum NET_FW_PROFILE_TYPE_
        NET_FW_PROFILE_CURRENT = 2
        NET_FW_PROFILE_DOMAIN = 0
        NET_FW_PROFILE_STANDARD = 1
        NET_FW_PROFILE_TYPE_MAX = 3
    End Enum

    Friend Enum NET_FW_IP_VERSION_
        NET_FW_IP_VERSION_ANY = 2
        NET_FW_IP_VERSION_MAX = 3
        NET_FW_IP_VERSION_V4 = 0
        NET_FW_IP_VERSION_V6 = 1
    End Enum

    Friend Enum NET_FW_SCOPE_
        NET_FW_SCOPE_ALL = 0
        NET_FW_SCOPE_CUSTOM = 2
        NET_FW_SCOPE_LOCAL_SUBNET = 1
        NET_FW_SCOPE_MAX = 3
    End Enum

    Friend Enum NET_FW_IP_PROTOCOL_
        NET_FW_IP_PROTOCOL_ANY = &H100
        NET_FW_IP_PROTOCOL_TCP = 6
        NET_FW_IP_PROTOCOL_UDP = &H11
    End Enum


    Private Shared Function CreateInstance(Of T)(ByVal progId As String) As T
        Return DirectCast(Activator.CreateInstance(Type.GetTypeFromProgID(progId)), T)
    End Function

    Private Shared m_Manager As INetFwMgr

    Private Shared ReadOnly Property CurrentProfile() As INetFwProfile
        Get
            If (m_Manager Is Nothing) Then
                m_Manager = CreateInstance(Of INetFwMgr)("HNetCfg.FwMgr")
            End If
            Return m_Manager.LocalPolicy.CurrentProfile
        End Get
    End Property

    ''' <summary>
    ''' True if the firewall is enabled
    ''' </summary>
    Friend Shared ReadOnly Property IsEnabled() As Boolean
        Get
            Try
                Return CurrentProfile.FirewallEnabled
            Catch ex As Exception
                ' An Exception if Windows Firewall service is not running
            End Try
            Return False
        End Get
    End Property

    ''' <summary>
    ''' True if the application is authorized
    ''' </summary>
    Friend Shared ReadOnly Property IsAuthorized(ByVal executablePath As String) As Boolean
        Get
            Try
                Return CurrentProfile.AuthorizedApplications.Item(executablePath).Enabled
            Catch ex As Exception
                ' FileNotFoundException for non-AuthorizedApplication
            End Try
            Return False
        End Get
    End Property

    ''' <summary>
    ''' Authorize an application; True if success
    ''' </summary>
    Friend Shared Function Authorize(ByVal applicationName As String, ByVal executablePath As String) As Boolean
        Try

            ' Check if application already authorized
            If IsEnabled AndAlso IsAuthorized(executablePath) Then
                Return True
            End If

            Dim app As INetFwAuthorizedApplication = CreateInstance(Of INetFwAuthorizedApplication)("HNetCfg.FwAuthorizedApplication")
            If (app IsNot Nothing) Then
                app.Name = applicationName
                app.ProcessImageFileName = executablePath
                app.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL

                ' You can specify the remote addresses from which the application can listen for traffic
                ' see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365342%28v=vs.85%29.aspx
                ' app.RemoteAddresses = "*"

                app.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY ' IPv4 and IPv6 both allowed
                app.Enabled = True
                CurrentProfile.AuthorizedApplications.Add(app)

                ' Again, check if application already authorized
                Return IsAuthorized(executablePath)
            End If
        Catch ex As Exception
            ' An Exception (ACCESSDENIED, INVALIDARG, OUTOFMEMORY, ...)
        End Try

        Return False
    End Function

End Class


To authorize your application:
VB
WinFirewall.Authorize("yourAppName", "appExecutablePath")


Don't forget to handle the exception in catch block.
Hope this helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900