Firewall since VB

57 views Asked by At

I've been trying to add a rule in Visual Basic to the firewall that allows receiving and responding to requests from other devices. My last hurdle is the firewall rules. I've attempted to create a .bat file that, when executed, provides two possible responses: 1. The rule has already been created, 2. The rule has been successfully created. The bat script is as follows:

@echo off
set "ruleName=helenaProyectX"
set "appName=C:\Users\ONS\Documents\helenaProxectX\helenaProyectX\bin\Debug\helenaProyectX.exe"

:: Verifica si la regla ya existe
netsh advfirewall firewall show rule name="%ruleName%" > nul 2>&1
if %errorlevel% neq 0 (
    echo the firewall's rule exist.
) else (
    :: Crea la regla del firewall
    netsh advfirewall firewall add rule name="%ruleName%" dir=in action=allow program="%appName%" enable=yes
    echo the firewall's rule has been created.
)

If the rule doesn't exist why the script prints "the firewall's rule exist"; I'm looking for the rule but I don't find it?

This is my module's complete structure:

Public Sub firewall()
    Dim appName As String = Application.ExecutablePath
    Dim ruleName As String = "helenaProyectX"
    Dim creadorDeRegla As String = Application.StartupPath & "\creadorDeRegla.bat"

    If IsAdmin() Then
        Try
            ' Contenido del archivo .bat
            Dim batchContent As String = "@echo off" & vbCrLf &
                          "set ""ruleName=" & ruleName & """" & vbCrLf &
                          "set ""appName=" & appName & """" & vbCrLf &
                          "" & vbCrLf &
                          ":: Verifica si la regla ya existe" & vbCrLf &
                          "netsh advfirewall firewall show rule name=""%ruleName%"" > nul 2>&1" & vbCrLf &
                          "if %errorlevel% neq 0 (" & vbCrLf &
                          "    echo La regla del firewall ya existe." & vbCrLf &
                          ") else (" & vbCrLf &
                          "    :: Crea la regla del firewall" & vbCrLf &
                          "    netsh advfirewall firewall add rule name=""%ruleName%"" dir=in action=allow program=""%appName%"" enable=yes" & vbCrLf &
                          "    echo Regla del firewall creada con éxito." & vbCrLf &
                          ")"

            ' Crea el archivo .bat
            Using writer As New StreamWriter(creadorDeRegla)
                writer.Write(batchContent)
            End Using

            Dim processInfo As New ProcessStartInfo("cmd.exe", "/c """ & creadorDeRegla & """")

            processInfo.RedirectStandardOutput = True
            processInfo.UseShellExecute = False
            processInfo.CreateNoWindow = True

            ' Inicia el proceso
            Dim process As New Process()
            process.StartInfo = processInfo
            process.Start()

            ' Captura la salida del proceso
            Dim output As String = process.StandardOutput.ReadToEnd()

            ' Espera a que el proceso termine
            process.WaitForExit()

            ' Muestra la salida en la consola o haz lo que necesites con la variable 'output'
            Console.WriteLine("Salida del proceso:")
            Console.WriteLine(output)
            MsgBox(output, MsgBoxStyle.OkOnly, "bat")
        Catch
            End
        End Try
    Else
        MessageBox.Show("Se necesitan permisos de administrador.", "Acceso a firewall", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End If
End Sub

Private Function IsAdmin() As Boolean
    ' Verificar si la aplicación se está ejecutando con privilegios de administrador
    Dim identity = WindowsIdentity.GetCurrent()
    Dim principal = New WindowsPrincipal(identity)
    Return principal.IsInRole(WindowsBuiltInRole.Administrator)
End Function
0

There are 0 answers