Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Visual-Studio VB.NET
Hi,
How can I create exception of my application in windows firewall, using vb.net code?
 
Thanks
Posted 23-Jan-13 19:27pm
Comments
Logi Guna at 24-Jan-13 9:32am
   
see my edited answer. TypeLibType( ... is now emitted correctly. thanks

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:
WinFirewall.Authorize("yourAppName", "appExecutablePath")
 
Don't forget to handle the exception in catch block.
Hope this helps.
  Permalink  
v2

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

  Print Answers RSS
0 Maciej Los 225
1 OriginalGriff 145
2 manoj kumar choubey 115
3 _Amy 115
4 Sergey Alexandrovich Kryukov 105
0 OriginalGriff 7,320
1 Sergey Alexandrovich Kryukov 6,043
2 Maciej Los 3,749
3 Peter Leow 3,408
4 DamithSL 2,555


Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 24 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100