Search code examples
vb.netvisual-studiowindows-firewall

Creating exception in Windows firewall using VB.Net


How can I add my application to the exception list of windows firewall, using vb.net code?

Thanks


Solution

  • Windows Vista and 7 provide a rather robust firewall API that can be used to add exceptions to the firewall. The code below will add an exception to the windows firewall for the specified application, provided that the code is run with administrator privileges. Add a reference to %systemroot%\system32\FirewallAPI.dll to your application.

    Imports NetFwTypeLib
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        ' Create the Application we want to add to the exception list
        Dim appType As Type = Type.GetTypeFromProgID("HnetCfg.FwAuthorizedApplication")
        Dim app As INetFwAuthorizedApplication
        app = DirectCast(Activator.CreateInstance(appType), INetFwAuthorizedApplication)
    
        ' Set the application properties
        app.Name = "Negative0's Sandbox"
        app.ProcessImageFileName = "C:\Users\Negative0\vbsandbox2.exe"
        app.Enabled = True
    
    
        ' Get the firewall manager, so we can get the list of authorized apps
        Dim fwMgrType As Type = Type.GetTypeFromProgID("HnetCfg.FwMgr")
        Dim fwMgr As INetFwMgr
        fwMgr = DirectCast(Activator.CreateInstance(fwMgrType), INetFwMgr)
    
        ' Get the list of authorized applications from the Firewall Manager, so we can add our app to that list
        Dim apps As INetFwAuthorizedApplications
        apps = fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications
        apps.Add(app)
    
    End Sub
    

    Source