# Firewall rule management MBFireWall instruction document

# Overview and Introduction

# What is MBfirewall?

MBfirewall (MB Firewall Management Tool) is an enterprise-grade firewall rule management solution designed specifically for the Windows operating system. It provides convenient, efficient, and secure Windows Defender firewall rule management through both a graphical user interface (GUI) and a command-line interface (CLI).

# Product Positioning

MBfirewall is positioned as:

  1. An enterprise-level firewall management tool: provides IT administrators with the ability to manage firewall rules in bulk
  2. A software development integration component: provides developers with programmatic firewall rule configuration interfaces
  3. A personal user security assistant: simplifies complex Windows Firewall configurations for ordinary users
  4. An automated deployment tool: supports scripted deployment and bulk configuration, suitable for CI/CD processes

# Design Principles

MBfirewall's design follows the following core principles:

  • Simplicity and ease of use: both GUI and CLI strive for simple and intuitive operations
  • Powerful features: covers all common firewall management scenarios
  • Stability and reliability: based on Windows COM interfaces to ensure perfect compatibility with the system
  • Extensibility: provides complete API interfaces to support third-party integration
  • Security first: all operations require administrator privileges to ensure system safety

# Supported Windows Versions

MBfirewall fully supports the following Windows versions:

  • Windows 7 (SP1 and above)
  • Windows 8 / 8.1
  • Windows 10 (all editions)
  • Windows 11 (all editions)
  • Windows Server 2008 R2 and above

Note: For Windows 7 compatibility, MBfirewall provides a specially compiled version to ensure perfect operation on Windows 7 systems.

# Technology Stack

  • Programming language: Go 1.21+ (Go 1.21 ensures Windows 7 compatibility)
  • GUI framework: lxn/walk (native Windows GUI library)
  • System interface: Windows COM API (INetFwPolicy2, INetFwRules)
  • Build method: native compilation, no runtime dependencies

# Core Features and Highlights

# Dual-mode runtime architecture

MBfirewall's major feature is support for two running modes simultaneously to meet different user needs:

# GUI Mode (Graphical Interface)

Features:

  • Intuitive window interface, no need to remember commands
  • Real-time display of firewall status and rule list
  • Supports visual operations, suitable for personal users and junior administrators
  • System tray support, minimize to run in the background
  • Automatic status refresh to reflect firewall changes in real time

Applicable scenarios:

  • Daily use by individual users
  • Quick viewing and modification of rules by IT administrators
  • Scenarios that require visual operations

# CLI Mode (Command-line Interface)

Features:

  • Full command-line support for scripts and automation
  • Silent mode (--silent), only returns exit codes, suitable for batch scripts
  • JSON formatted output for easy program parsing
  • Supports batch operations, handle multiple rules in one command
  • Rich filtering and query options

Applicable scenarios:

  • Automated deployment scripts
  • CI/CD pipeline integration
  • Bulk configuration across multiple systems
  • Remote management scenarios

# Complete firewall management capabilities

MBfirewall provides complete management capabilities for Windows Defender Firewall:

# Configuration file management

  • Supports three network configuration profiles: Domain, Private, Public
  • Can manage each profile's state individually or collectively
  • Query profile enable status in real time

# Rule management

  • Add rules: supports full parameters such as program path, port, protocol, direction
  • Remove rules: supports deletion by program path or rule name
  • Query rules: supports listing all rules with prefix filtering
  • Rule validation: validate rule validity before adding to avoid invalid rules
  • Batch operations: supports bulk addition from a JSON configuration file

# Status monitoring

  • Query overall firewall status in real time
  • Check whether a specific program's rules exist and their status
  • Retrieve detailed rule information

# Import/Export

  • Export rules to a JSON file for backup and migration
  • Import JSON configuration files to quickly restore or deploy rules

# Deep integration with MBbrowser (候鸟浏览器)

MBfirewall provides dedicated integration features for MBbrowser (MBbrowser):

# Automatic detection of installation path

  • Automatically read MBbrowser installation path from the registry
  • No manual path input required; one-click configuration for all rules

# Intelligent rule configuration

  • Automatically detects 9 core MBbrowser program files
  • Automatically adds inbound and outbound rules for each program
  • Configures different protocols and ports for different programs

Supported program list:

  1. mbbrowser.exe: MBbrowser main program (both directions, all protocols)
  2. cdp.exe: Chrome DevTools Protocol (TCP, port 9222)
  3. mbservice.exe: MBbrowser background service (both directions, all protocols)
  4. apiserver.exe: API server (TCP, ports 80/443)
  5. chrome.exe: Chrome browser core (TCP, ports 80/443)
  6. chrome_proxy.exe: Chrome proxy (TCP, ports 80/443)
  7. chrome_pwa_launcher.exe: Chrome PWA launcher (TCP, ports 80/443)
  8. chromedriver.exe: Browser automation driver (TCP, port 9515)
  9. notification_helper.exe: Notification helper (TCP, ports 80/443)

One command to complete configuration:

mbfirewall.exe add-mbbrowser

This command will automatically:

  1. Read the MBbrowser installation path from the registry
  2. Check whether all program files exist
  3. Add inbound and outbound rules for each existing program (total 18 rules)
  4. Display detailed execution results and error information

# Flexible parameter configuration

MBfirewall supports rich parameter configuration options to meet various complex scenarios:

# Rule direction

  • inbound / in: inbound rules (external access to internal)
  • outbound / out: outbound rules (internal access to external)
  • both: both directions (default)

# Protocol types

  • tcp: TCP protocol
  • udp: UDP protocol
  • icmp: ICMP protocol
  • any / all: any protocol (default)

# Port configuration

  • Single port: 80
  • Multiple ports: 80,443,8080
  • Port range: 8000-9000
  • All ports: * (default)

# Profile types

  • domain: domain network profile
  • private: private network profile
  • public: public network profile
  • all: all profiles (default)

# Enterprise features

# Batch operations

  • Supports bulk addition from JSON configuration files
  • Supports bulk deletion of rules
  • Detailed feedback on batch operation results

# Import/Export

  • Export rules to JSON files with prefix filtering support
  • Import JSON configuration files for quick deployment
  • Standardized configuration file format, easy for version control

# Logging and auditing

  • Optional logging feature (enabled with --enable-log)
  • Log files split by date for easy management
  • Detailed error and debug information

# Error handling

  • Standard exit codes (0-4) for script detection
  • Detailed error messages for diagnostics
  • Silent mode support for automated scenarios

# Security and permission management

# Administrator permission requirements

  • All modification operations require administrator privileges
  • Automatic permission detection with friendly prompts
  • Supports UAC elevation

# Operation validation

  • Validate path existence before adding rules
  • Check whether rules already exist to avoid duplicates
  • Validate parameter legality to prevent invalid configurations

# Principle of least privilege

  • Query operations can run under normal user (limited functions)
  • Only modification operations require administrator privileges
  • Help and version information do not require privileges

# Use Cases

# Scenario 1: Software development integration

Background: A software development company needs to automatically configure firewall rules during installation to ensure the software can access the network. Manual configuration is too complex for users and prone to errors.

Solution: Integrate MBfirewall CLI into the installer to automatically add firewall rules upon installation.

Example code (C++ pseudo-code):

void OnInstallComplete() {
    // Call MBfirewall to add rules
    system("mbfirewall.exe add --app \"C:\\Program Files\\MyApp\\app.exe\" --name \"MyApp\" --silent");
    // Or use a batch configuration file
    system("mbfirewall.exe import --input \"install_dir\\config\\firewall_rules.json\"");
}

Advantages:

  • Users do not need to configure firewall manually
  • Reduces technical support costs
  • Ensures the software can access the network
  • Supports bulk rule configuration

# Scenario 2: Enterprise IT bulk deployment

Background: Enterprise IT needs to uniformly configure firewall rules for hundreds of computers. Manual configuration is time-consuming and error-prone.

Solution: Use MBfirewall CLI with configuration files and deploy via Group Policy or remote scripts.

Deployment steps:

  1. Prepare configuration file (apps.json):
{
  "version": "1.0",
  "description": "Enterprise application firewall rules",
  "apps": [
    {
      "name": "ERP client",
      "path": "C:\\Program Files\\ERP\\client.exe",
      "direction": "both",
      "protocol": "tcp",
      "ports": "8080",
      "enabled": true
    },
    {
      "name": "Database client",
      "path": "C:\\Program Files\\DB\\client.exe",
      "direction": "outbound",
      "protocol": "tcp",
      "ports": "1433",
      "enabled": true
    }
  ]
}
  1. Create deployment script (deploy.bat):
@echo off
echo Deploying firewall rules ...
mbfirewall.exe import --input "%~dp0apps.json"
if %ERRORLEVEL% EQU 0 (
    echo Firewall rules deployed successfully
) else (
    echo Deployment failed, please check logs
    exit /b 1
)
  1. Deploy via Group Policy or remote script execution

Advantages:

  • One-time deployment for many machines
  • Consistent configuration to avoid omissions
  • Supports version control and rollback
  • Can be automated

# Scenario 3: Simplifying configuration for personal users

Background: After installing software, Windows Firewall prompts users and they often don't know how to handle it, or need to configure complex rules manually.

Solution: Use MBfirewall GUI mode to intuitively view and manage firewall rules.

Usage flow:

  1. Run mbfirewall.exe to start the GUI
  2. View current firewall status
  3. Add a new program rule:
    • Click "Add Rule"
    • Choose program path
    • Set rule name and parameters
    • Confirm to add
  4. Check rule list to confirm the rule was added

Advantages:

  • Graphical interface with intuitive operations
  • Real-time status updates
  • No need to understand command line
  • Friendly error prompts

# Scenario 4: CI/CD automation

Background: CI/CD pipelines need automatic firewall rule configuration in test environments to ensure tests run properly.

Solution: Use MBfirewall CLI in CI/CD scripts to automatically configure testing environments.

CI/CD script example (GitLab CI):

test_stage:
  script:
    # Configure firewall rules
    - mbfirewall.exe add --app "C:\\App\\test.exe" --name "Test App" --silent
    # Verify rules added
    - mbfirewall.exe check --app "C:\\App\\test.exe" --silent
    # Run tests
    - run_tests.bat
  after_script:
    # Cleanup rules
    - mbfirewall.exe remove --app "C:\\App\\test.exe" --silent

Advantages:

  • Integrates into automated workflows
  • Supports silent mode without polluting logs
  • Exit codes indicate results
  • Automatically cleans up after tests

# Scenario 5: MBbrowser users

Background: MBbrowser users need to configure multiple firewall rules after installation; manual setup is tedious and error-prone.

Solution: Use MBfirewall's MBbrowser integration to complete all configuration with one command.

Usage steps:

  1. Ensure MBbrowser is installed (installation path recorded in registry)
  2. Run the command as administrator:
mbfirewall.exe add-mbbrowser
  1. Wait for automatic configuration to finish (about 18 rules)

Advantages:

  • One command completes all configuration
  • Automatically detects installation path
  • Skips non-existent files intelligently
  • Provides detailed execution feedback

# Scenario 6: Security audit and compliance

Background: Enterprises need regular audits of firewall rules to ensure compliance with security policies and to generate audit reports.

Solution: Use MBfirewall's export feature to regularly export rules for audit analysis.

Audit process:

  1. Regularly export rules (daily/weekly):
@echo off
set BACKUP_DIR=backup\%date:~0,4%%date:~5,2%%date:~8,2%
mkdir "%BACKUP_DIR%"
mbfirewall.exe export --output "%BACKUP_DIR%\firewall_rules.json"
  1. Analyze rule configurations:

    • Check for unauthorized rules
    • Verify rule configurations comply with security policies
    • Identify abnormal ports and protocol configurations
  2. Generate audit reports:

    • Compare rule changes over time
    • Record rule change history
    • Produce compliance reports

Advantages:

  • Traceable configuration history
  • Facilitates compliance review
  • Timely detection of abnormal configurations
  • Supports automated auditing

# Scenario 7: Troubleshooting

Background: When users encounter network connection issues, they need to check whether firewall rules are configured correctly.

Solution: Use MBfirewall's query features to quickly check rule status.

Troubleshooting steps:

  1. Check overall firewall status:
mbfirewall.exe status
  1. Check specific program rules:
mbfirewall.exe check --app "C:\\Program Files\\App\\app.exe"
  1. List all related rules:
mbfirewall.exe list --prefix "App"
  1. Fix issues based on check results:
    • If rule not found, add rule
    • If rule disabled, enable rule
    • If rule misconfigured, delete and re-add

Advantages:

  • Quickly locate problems
  • Clear rule status display
  • Supports bulk checks
  • Facilitates remote assistance

# Detailed Feature Description

# Firewall status query (status)

Description: Query the overall Windows Firewall status, including each profile's enable state and rule counts.

Usage:

GUI mode:

  • After launch, the main UI displays current firewall status
  • Status bar shows each profile's state
  • Click "Refresh" to update status

CLI mode:

# Basic query
mbfirewall.exe status

# Silent mode (only exit code)
mbfirewall.exe status --silent

Output example:

{
  "domain_profile": {
    "profile_type": "domain",
    "enabled": true,
    "last_updated": "2025-11-03T10:30:00Z"
  },
  "private_profile": {
    "profile_type": "private",
    "enabled": true,
    "last_updated": "2025-11-03T10:30:00Z"
  },
  "public_profile": {
    "profile_type": "public",
    "enabled": false,
    "last_updated": "2025-11-03T10:30:00Z"
  },
  "profiles": [
    {
      "type": "domain",
      "enabled": true,
      "last_updated": "2025-11-03T10:30:00Z"
    },
    {
      "type": "private",
      "enabled": true,
      "last_updated": "2025-11-03T10:30:00Z"
    },
    {
      "type": "public",
      "enabled": false,
      "last_updated": "2025-11-03T10:30:00Z"
    }
  ],
  "rule_count": 150,
  "is_admin": true,
  "last_checked": "2025-11-03T10:30:00Z",
  "timestamp": "2025-11-03T10:30:00Z"
}

Exit codes:

  • 0: query successful
  • 2: insufficient permissions (requires administrator)
  • 1: query failed

Use cases:

  • Check whether the firewall is enabled
  • Monitor firewall status changes
  • Use in automation scripts to determine firewall status
  • Diagnose issues by understanding global status

Notes:

  • This command requires administrator privileges for complete information
  • Normal users can only query and cannot modify status
  • Status information is updated in real time

# Rule check (check)

Description: Check whether firewall rules for a specified program exist and the rule state (enabled/disabled).

Usage:

# Check program rule status
mbfirewall.exe check --app "C:\\Program Files\\MyApp\\app.exe"

# Silent mode check
mbfirewall.exe check --app "C:\\Program Files\\MyApp\\app.exe" --silent

Parameter:

  • --app <path>: Full path to the program executable (required)

Output example:

{
  "app": "C:\\Program Files\\MyApp\\app.exe",
  "inbound": "enabled",
  "outbound": "enabled",
  "rules": [
    {
      "name": "MBbrowser - app.exe (inbound)",
      "direction": "inbound",
      "enabled": true,
      "protocol": "any",
      "ports": "*"
    },
    {
      "name": "MBbrowser - app.exe (outbound)",
      "direction": "outbound",
      "enabled": true,
      "protocol": "any",
      "ports": "*"
    }
  ]
}

Status values:

  • enabled: rule exists and is enabled
  • disabled: rule exists but is disabled
  • not_found: rule does not exist

Exit codes:

  • 0: rule added and enabled
  • 1: rule not found
  • 2: rule exists but not enabled
  • 4: invalid program path

Use cases:

  • Verify rule added after installation
  • Troubleshoot by checking rule status
  • Validate configuration in automation scripts
  • Periodically check rule integrity

Notes:

  • Path must be absolute, not relative
  • Path may be case-sensitive in some cases
  • If multiple rules exist for a program, all related rules will be listed

# Add rule (add)

Description: Add firewall rules for a specified program, supporting rich parameter configuration.

Usage:

Add a single program rule

# Basic add (both directions, any protocol, all ports)
mbfirewall.exe add --app "C:\\Program Files\\MyApp\\app.exe"

# Add with custom name
mbfirewall.exe add --app "C:\\Program Files\\MyApp\\app.exe" --name "MyApp"

# Add inbound TCP rule with specified ports
mbfirewall.exe add --app "C:\\Server\\server.exe" --direction inbound --protocol tcp --ports 80,443

# Add outbound UDP rule
mbfirewall.exe add --app "C:\\Client\\client.exe" --direction outbound --protocol udp --ports 53

# Add rule with port range
mbfirewall.exe add --app "C:\\Game\\game.exe" --protocol tcp --ports 27015-27030

# Silent mode add
mbfirewall.exe add --app "C:\\App\\app.exe" --name "App" --silent

Parameter description:

Parameter Description Values Default
--app <path> Program executable path (required) - -
--name <name> Rule name (optional) Any string Use filename
--direction <direction> Rule direction inbound / in / outbound / out / both both
--protocol <protocol> Protocol type tcp / udp / icmp / any any
--ports <ports> Port numbers 80 / 80,443 / 8000-9000 / * *
--silent Silent mode - false

Rule naming rules: If --name is not specified, the rule name format is: {rule_prefix} - {filename} ({direction}) For example: MBbrowser - app.exe (inbound)

Batch add rules: Use a JSON configuration file to add rules in bulk:

mbfirewall.exe add --batch "config\\apps.json"

Configuration file format:

{
  "name": "My app rule set",
  "description": "Bulk added firewall rules",
  "version": "1.0",
  "apps": [
    {
      "name": "Chrome",
      "path": "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
      "direction": "both",
      "protocol": "any",
      "ports": "*",
      "enabled": true,
      "description": "Chrome browser firewall rule"
    },
    {
      "name": "Web Server",
      "path": "C:\\Server\\nginx.exe",
      "direction": "inbound",
      "protocol": "tcp",
      "ports": "80,443",
      "enabled": true,
      "description": "Nginx Web Server"
    }
  ]
}

Exit codes:

  • 0: add success
  • 1: add failed (see detailed output)
  • 2: insufficient permissions
  • 3: invalid parameters
  • 4: rule already exists

Use cases:

  • Automatically add rules during installation
  • Configure server application network access
  • Bulk deploy rules for multiple programs
  • Temporarily add test rules

Notes:

  • Requires administrator privileges
  • If rule already exists, returns error (will not overwrite)
  • Adding both-direction rules will create two rules (inbound + outbound)
  • Path must be absolute
  • Adding rules for non-existent files may be allowed depending on settings

# Remove rule (remove)

Description: Remove firewall rules for a specified program, supports deletion by program path or rule name.

Usage:

Remove by program path

# Remove all rules for a program (inbound + outbound)
mbfirewall.exe remove --app "C:\\Program Files\\MyApp\\app.exe"

# Silent mode remove
mbfirewall.exe remove --app "C:\\Program Files\\MyApp\\app.exe" --silent

Remove by rule name

# Remove a specific rule
mbfirewall.exe remove --name "MBbrowser - app.exe (inbound)"

# Remove specific rule (silent)
mbfirewall.exe remove --name "MBbrowser - app.exe (inbound)" --silent

Parameter description:

  • --app <path>: Program executable path (mutually exclusive with --name)
  • --name <name>: Rule name (mutually exclusive with --app)
  • --silent: Silent mode

Exit codes:

  • 0: remove success
  • 1: remove failed
  • 2: insufficient permissions
  • 3: invalid parameters (neither or both parameters provided)
  • 4: rule not found

Use cases:

  • Clean up rules when uninstalling programs
  • Modify rule configuration (remove old and add new)
  • Clean up invalid rules
  • Bulk rule cleanup

Notes:

  • Requires administrator privileges
  • Removing by path deletes all rules for that program (inbound + outbound)
  • Remove operations are irreversible; proceed with caution
  • If rule does not exist, returns non-zero exit code

# List rules (list)

Description: List all rules or rules filtered by a specific prefix.

Usage:

# List all rules
mbfirewall.exe list

# List rules with a specific prefix
mbfirewall.exe list --prefix "MBbrowser"

# List MBbrowser related rules
mbfirewall.exe list --prefix "MBbrowser"

# Silent mode
mbfirewall.exe list --prefix "MBbrowser" --silent

Parameter description:

  • --prefix <prefix>: Filter by rule name prefix (optional)
  • --silent: Silent mode

Output example:

{
  "count": 10,
  "rules": [
    {
      "name": "MBbrowser - Chrome (inbound)",
      "display_name": "MBbrowser - Chrome (inbound)",
      "description": "Chrome core - rendering and execution",
      "enabled": true,
      "direction": "inbound",
      "protocol": "tcp",
      "local_ports": "80, 443",
      "remote_ports": "*",
      "application_path": "C:\\Program Files\\MBbrowser\\MBbrowser\\chrome.exe",
      "profiles": 7
    },
    {
      "name": "MBbrowser - Chrome (outbound)",
      "display_name": "MBbrowser - Chrome (outbound)",
      "description": "Chrome core - rendering and execution",
      "enabled": true,
      "direction": "outbound",
      "protocol": "tcp",
      "local_ports": "80,443",
      "remote_ports": "*",
      "application_path": "C:\\Program Files\\MBbrowser\\MBbrowser\\chrome.exe",
      "profiles": 7
    }
  ]
}

Exit codes:

  • 0: query success
  • 1: query failed
  • 2: insufficient permissions

Use cases:

  • View all firewall rules
  • Check rules for a specific application
  • Audit and compliance checks
  • Troubleshooting

Notes:

  • Requires administrator privileges
  • Rule lists can be very long (hundreds); using prefix filters is recommended
  • Output may include system and other program-created rules

# Enable firewall (enable)

Description: Enable Windows Firewall for specified profiles.

Usage:

# Enable all profiles
mbfirewall.exe enable --profile all

# Enable only public profile
mbfirewall.exe enable --profile public

# Enable private profile
mbfirewall.exe enable --profile private

# Enable domain profile
mbfirewall.exe enable --profile domain

# Silent mode
mbfirewall.exe enable --profile all --silent

Parameter description:

  • --profile <type>: Profile type (required)
    • domain: domain profile
    • private: private profile
    • public: public profile
    • all: all profiles
  • --silent: Silent mode

Exit codes:

  • 0: enable success
  • 1: enable failed
  • 2: insufficient permissions

Use cases:

  • Fix disabled firewall
  • Enable firewall for specific networks
  • Ensure firewall is enabled during bulk deployment
  • Security policies requiring firewall enabled

Notes:

  • Requires administrator privileges
  • Enabling firewall does not affect existing rules
  • It is recommended to keep firewall enabled for security

# Disable firewall (disable)

Description: Disable Windows Firewall for specified profiles.

Usage:

# Disable all profiles (not recommended)
mbfirewall.exe disable --profile all

# Disable only public profile
mbfirewall.exe disable --profile public

Parameter description:

  • --profile <type>: Profile type (required)
  • --silent: Silent mode

Exit codes:

  • 0: disable success
  • 1: disable failed
  • 2: insufficient permissions

Security warning: Disabling the firewall significantly reduces system security and makes the system vulnerable to network attacks. Disable only for special needs and re-enable as soon as possible.

Use cases:

  • Temporary troubleshooting (to check if firewall causes issues)
  • Specific test environment needs
  • Internal network environments protected by other firewall devices

Notes:

  • Requires administrator privileges
  • Disabling firewall takes effect immediately and all firewall rules cease to be effective
  • It is recommended to re-enable firewall promptly

# Export rules (export)

Description: Export firewall rule configuration to a JSON file, supports prefix filtering.

Usage:

# Export all rules
mbfirewall.exe export --output "backup\\all_rules.json"

# Export rules with specific prefix
mbfirewall.exe export --output "backup\\mbbrowser_rules.json" --prefix "MBbrowser"

# Export to current directory
mbfirewall.exe export --output "firewall_backup.json"

# Silent mode
mbfirewall.exe export --output "backup.json" --silent

Parameter description:

  • --output <file>: Output file path (required)
  • --prefix <prefix>: Only export rules with specified prefix (optional)
  • --silent: Silent mode

Output file format:

{
  "version": "1.0",
  "description": "Exported firewall rules",
  "created_at": "2025-11-03T10:30:00Z",
  "apps": [
    {
      "name": "MBbrowser - Chrome",
      "path": "C:\\Program Files\\MBbrowser\\MBbrowser\\chrome.exe",
      "direction": "both",
      "protocol": "tcp",
      "ports": "80,443",
      "enabled": true,
      "description": "Chrome core - rendering and execution"
    }
  ]
}

Exit codes:

  • 0: export success
  • 1: export failed
  • 2: insufficient permissions
  • 3: invalid parameters (invalid output path)

Use cases:

  • Regularly backup firewall rules
  • Migrate rules to other machines
  • Version control and configuration management
  • Audit and compliance checks

Notes:

  • Requires administrator privileges
  • Exporting will overwrite existing files
  • Export format is the same as the batch add format and can be directly used for import

# Import rules (import)

Description: Import firewall rules from a JSON configuration file in bulk.

Usage:

# Import from a backup file
mbfirewall.exe import --input "backup\\all_rules.json"

# Import from configuration file
mbfirewall.exe import --input "config\\default_rules.json"

# Silent mode
mbfirewall.exe import --input "backup.json" --silent

Parameter description:

  • --input <file>: Input file path (required)
  • --silent: Silent mode

Configuration file format: same as used for batch add (see "Add rule" section).

Exit codes:

  • 0: import success
  • 1: import failed (partial or complete failure)
  • 2: insufficient permissions
  • 3: invalid parameters (file not found or format error)
  • 4: file not found

Use cases:

  • Restore rules from backup
  • Bulk deploy rules to multiple machines
  • Migrate rules to new systems
  • Quickly configure from templates

Notes:

  • Requires administrator privileges
  • Existing rules will be skipped (not overwritten)
  • Failed rules will be reported in output
  • It is recommended to export current rules as a backup before importing

# MBbrowser-specific command (add-mbbrowser)

Description: Automatically add firewall rules for all MBbrowser programs.

Usage:

# Add MBbrowser rules (standard mode)
mbfirewall.exe add-mbbrowser

# Enable logging and add rules
mbfirewall.exe --enable-log add-mbbrowser

How it works:

  1. Read installation path: read MBbrowser install path from registry HKEY_CURRENT_USER\\SOFTWARE\\MBbrowser\\Path

  2. Check program files: check the existence of the following 9 program files:

    • mbbrowser.exe (main program)
    • cdp.exe (CDP debug)
    • mbservice.exe (background service)
    • apiserver.exe (API server)
    • MBbrowser\chrome.exe (Chrome core)
    • MBbrowser\chrome_proxy.exe (Chrome proxy)
    • MBbrowser\chrome_pwa_launcher.exe (PWA launcher)
    • MBbrowser\chromedriver.exe (browser driver)
    • MBbrowser\notification_helper.exe (notification helper)
  3. Add rules: add inbound and outbound rules for each existing program (up to 18 rules)

  4. Display results: show detailed execution results including successes and failures

Output example:

🔥 MBbrowser firewall rules adding
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📍 Install path: C:\\Program Files\\MBbrowser

The following MBbrowser programs will have firewall rules added:

  • mbbrowser.exe (MBbrowser main program)
  • cdp.exe (Chrome DevTools Protocol)
  • mbservice.exe (MBbrowser background service)
  • apiserver.exe (API server)
  • chrome.exe (Chrome core)
  • chrome_proxy.exe (Chrome proxy)
  • chrome_pwa_launcher.exe (PWA launcher)
  • chromedriver.exe (browser driver)
  • notification_helper.exe (notification helper)

Each program will have inbound and outbound rules added
A total of 18 firewall rules

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📦 Processing: mbbrowser.exe
   Path: C:\\Program Files\\MBbrowser\\mbbrowser.exe
   Description: MBbrowser main program - needs internet access
   Protocol: any | Ports: *
   [1/2] Adding inbound rule... ✅ Success
   [2/2] Adding outbound rule... ✅ Success

...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Execution results
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ Successfully added all 18 rules

The following programs had firewall rules added:
  • mbbrowser.exe
  • cdp.exe
  • mbservice.exe
  • apiserver.exe
  • chrome.exe
  • chrome_proxy.exe
  • chrome_pwa_launcher.exe
  • chromedriver.exe
  • notification_helper.exe

Each program had inbound and outbound rules added

Exit codes:

  • 0: all rules added successfully
  • 1: partial or complete failure

Use cases:

  • Automatically configure firewall after MBbrowser installation
  • Fix MBbrowser network issues
  • Reconfigure MBbrowser firewall rules

Notes:

  • Requires administrator privileges
  • Ensure MBbrowser is correctly installed
  • Missing files will be skipped
  • Existing rules will be skipped (not overwritten)

Troubleshooting: If the command fails, check:

  1. Registry path: ensure HKEY_CURRENT_USER\\SOFTWARE\\MBbrowser\\Path exists and contains the correct path value
  2. File paths: ensure corresponding program files exist in the MBbrowser installation directory
  3. Administrator privileges: ensure the command is run as administrator
  4. Firewall service: ensure Windows Firewall service is running

The following continues to strictly follow the original document structure at ### (h3) and #### (h4) levels; do not add any additional explanations, emoji, symbols, or subjective polishing — keep the content exactly consistent with the original.


# Technical Features and Architecture

# Architecture Design

MBfirewall uses a layered architecture to ensure maintainability and extensibility:

┌─────────────────────────────────────────┐
│           User Interface Layer (UI/CLI)             │
│  - GUI (ui/)
│  - CLI commands (cmd/)
└─────────────────────────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│           Business Logic Layer (firewall/)          │
│  - Manager (high-level API)
│  - Rule validation and construction
│  - Batch operations
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│           System Interface Layer (firewall/)          │
│  - COMFirewall (COM interface wrapper)
│  - Windows COM API calls
└─────────────────────────────────────────┘
                    ↓
┌─────────────────────────────────────────┐
│           System Layer                          │
│  - Windows Defender Firewall               │
│  - INetFwPolicy2 / INetFwRules         │
└─────────────────────────────────────────┘

# Core Technologies

# Windows COM Interface

MBfirewall uses Windows COM (Component Object Model) interfaces to interact with Windows Firewall:

Main interfaces:

  • INetFwPolicy2: firewall policy interface
    • Get and set profile states
    • Get rule collections
  • INetFwRules: firewall rule collection interface
    • Enumerate all rules
    • Add, remove, modify rules
  • INetFwRule: firewall rule interface
    • All rule attributes (name, path, direction, protocol, etc.)

Advantages:

  • Official API, stable and reliable
  • Supports Windows 7 and above
  • No third-party dependencies
  • Excellent performance

# Go language features

Concurrency safety:

  • Uses Go's concurrency model to ensure thread safety
  • COM interface calls are executed on a single thread to avoid race conditions

Memory management:

  • Go's automatic garbage collection eliminates manual memory management
  • Proper release of COM objects ensures no resource leaks

Error handling:

  • Detailed error messages for problem diagnosis
  • Standardized error handling flow

# Modular design

MBfirewall uses a modular design with clear module responsibilities:

cmd module:

  • CLI parsing and routing
  • Command-line parameter validation
  • Output formatting

firewall module:

  • Core firewall operation logic
  • COM interface wrapping
  • Rule management

models module:

  • Data model definitions
  • Type conversion and validation
  • Configuration file parsing

ui module:

  • GUI implementation
  • Event handling
  • Status updates

utils module:

  • Utility functions (path, permission, logging, etc.)
  • Common functionality

# Performance optimizations

# COM object reuse

  • Reuse firewall policy objects to avoid frequent creation
  • Reuse connections for batch operations

# Lazy loading

  • Initialize COM objects only when needed
  • Query rules on demand to avoid loading all rules at once

# Path normalization

  • Unify path formats to avoid duplicate queries
  • Cache normalized results

# Fast error return

  • Validate parameters early to avoid unnecessary operations
  • Check permissions first

# Security design

# Permission control

  • All modification operations require administrator privileges
  • Automatic permission detection with friendly prompts
  • Support UAC elevation

# Input validation

  • Strict parameter validation
  • Path normalization to prevent path traversal attacks
  • Protocol and port range validation

# Operation auditing

  • Optional logging
  • Detailed operation logs
  • Easy to trace and audit

# Principle of least privilege

  • Query operations run under normal user (limited features)
  • Only modification operations require administrator privileges

# Compatibility design

# Windows 7 support

  • Use Go 1.21 for compatibility
  • Provide a dedicated Windows 7 build
  • Test coverage for Windows 7 SP1 and above

# Character encoding

  • Support UTF-8 encoding
  • Proper handling of Chinese paths and rule names
  • Console output automatically sets code page

# Path handling

  • Support long paths (Windows 10+)
  • Proper handling of UNC paths
  • Unified path normalization

# Installation and Configuration

# System Requirements

Operating system:

  • Windows 7 SP1 and above
  • Windows 8 / 8.1
  • Windows 10 (all editions)
  • Windows 11 (all editions)
  • Windows Server 2008 R2 and above

Permission requirements:

  • Administrator privileges (for modifying firewall rules)
  • Normal user privileges (for query operations)

Other requirements:

  • Windows Defender Firewall service running
  • Sufficient disk space (about 10MB)

# Installation Methods

# Method 1: Run the executable directly

  1. Download the program:

    • Download the latest mbfirewall.exe or mbfirewall_v1.0.43.exe
    • Windows 7 users download mbfirewall_v1.0.43_win7.exe
  2. Place the file:

    • Put the file anywhere (recommended C:\Program Files\MBfirewall\)
    • Or place it in a directory in the system PATH for global access
  3. Run the program:

    • Double-click to start GUI mode
    • Or run from command line to start CLI mode

Notes:

  • First run will request administrator privileges (UAC prompt)
  • Running as a normal user may restrict some features

# Method 2: Build from source

Prerequisites:

  • Go 1.21 or later
  • Windows SDK (usually installed with Visual Studio or Build Tools)
  • Git (optional, for cloning source)

Build steps:

  1. Clone the repo (if using Git):
git clone https://github.com/yourusername/mbfirewall.git
cd mbfirewall/mbfirewall

or download and extract the source archive.

  1. Build GUI version (no console window):
go build -ldflags="-H windowsgui" -o mbfirewall.exe
  1. Build console version (for CLI):
go build -o mbfirewall_console.exe
  1. Build Windows 7 compatible version:
# Use Go 1.21
go build -ldflags="-H windowsgui" -o mbfirewall_win7.exe

Resource integration: If you need to embed icons and manifest files:

  1. Prepare resource files:

    • mbfirewall.ico: program icon
    • manifest.xml: program manifest (for UAC elevation)
  2. Use windres to compile resources (if using rc files):

windres -i resource.rc -o resource.syso
go build -ldflags="-H windowsgui" -o mbfirewall.exe

# Configuration files

MBfirewall uses JSON configuration files to store settings:

Configuration file locations:

  • Settings: %APPDATA%\MBfirewall\config\settings.json
  • App configuration: %APPDATA%\MBfirewall\config\apps.json

Default settings:

{
  "auto_refresh": true,
  "refresh_interval": 30,
  "create_both_rules": true,
  "enable_new_rules": true,
  "default_protocol": "any",
  "rule_prefix": "MBbrowser ",
  "log_level": "info",
  "log_retention_days": 30,
  "check_file_exists": false,
  "confirm_on_delete": true,
  "minimize_to_tray": false,
  "start_minimized": false,
  "language": "zh-CN"
}

Settings description:

Setting Description Default
rule_prefix Rule name prefix "MBbrowser "
auto_refresh Auto refresh in GUI mode true
refresh_interval Refresh interval (seconds) 30
check_file_exists Check file existence before adding rule false
log_level Log level (debug/info/warn/error) "info"
log_retention_days Days to retain logs 30

Modify configuration: Configuration file is auto-created on first run. You can manually edit it to change settings.

# Logging configuration

Log file location: %APPDATA%\MBfirewall\logs\

Log filename format: mbfirewall_YYYYMMDD.log

Enable logging:

  • GUI: start with --enable-log
  • CLI: add --enable-log before commands

Example:

mbfirewall.exe --enable-log status

# GUI Usage Guide

# Start the application

Start methods:

  1. Double-click mbfirewall.exe to start GUI mode
  2. Or run mbfirewall.exe (no arguments) from command line

First run:

  • If not run as administrator, a UAC prompt will request elevation
  • Click "Yes" to allow elevation
  • The program will auto-create config and log directories

# Main interface overview

Layout:

┌─────────────────────────────────────────────────────┐
│  MB Firewall Management Tool                     [ Minimize ][ Close ] │
├─────────────────────────────────────────────────────┤
│                                                     │
│   Firewall Status         │
│  ┌─────────┬─────────┬─────────┐                   │
│  │  Domain   │  Private  │  Public  │                   │
│  │  ✅ Enabled  │  ✅ Enabled  │  ❌ Disabled  │                   │
│  └─────────┴─────────┴─────────┘                   │
│                                                      │
│   Total rules: 150                                      │
│                                                     │
│  ┌───────────────────────────────────────────────┐ │
│  │ [ Refresh ] [ Add Rule ] [ Delete Rule ] [ Export ] [ Import ]    │ │
│  └───────────────────────────────────────────────┘ │
│                                                     │
│   Rule list                                            │
│  ┌───────────────────────────────────────────────┐ │
│  │  Name                     │  Status  │  Direction  │  Action   │ │
│  ├───────────────────────────────────────────────┤ │
│  │  MBbrowser - app.exe ... │ ✅   │  Inbound  │ [ Delete ]│ │
│  │  MBbrowser - app.exe... │ ✅   │  Outbound  │ [ Delete ]│ │
│  │ ...                                           │ │
│  └───────────────────────────────────────────────┘ │
│                                                      │
│   Search: [____________] [ Filter ]                        │
│                                                     │
└─────────────────────────────────────────────────────┘

Main components:

  1. Status bar: displays three profile states (domain / private / public)
  2. Total rules: displays current total firewall rule count
  3. Action buttons: Refresh, Add, Delete, Export, Import
  4. Rule list: displays all firewall rules
  5. Search box: filter the rule list

# Basic operations

# View firewall status

On launch, the main UI auto-displays current firewall status:

  • Green ✅ means enabled
  • Red ❌ means disabled Click "Refresh" to manually update.

# Add firewall rule

Steps:

  1. Click "Add Rule" button
  2. In the dialog:
    • Select or enter program path
    • Set rule name (optional)
    • Set direction (inbound / outbound / both)
    • Set protocol (TCP/UDP/ICMP/Any)
    • Set ports (optional)
  3. Click "OK" to add

Shortcuts:

  • Drag and drop program files into the UI to add
  • Right-click menu to add rules

# Delete firewall rule

Steps:

  1. Select rule(s) in the rule list
  2. Click "Delete Rule" button
  3. Confirm deletion

Batch delete:

  • Hold Ctrl to select multiple rules
  • Hold Shift to select a range
  • Click "Delete Rule" to remove in bulk

# Search and filter rules

Search:

  • Type keywords in the search box
  • Rules are filtered in real time
  • Supports name, path, description search

Prefix filter:

  • Filter rules by prefix
  • e.g., prefix "MBbrowser" shows all MBbrowser rules

# Export rules

Steps:

  1. Click "Export" button
  2. Choose save location
  3. Optional: set prefix filter
  4. Click "Save"

Exported file is JSON and can be used for backup or import on other machines.

# Import rules

Steps:

  1. Click "Import" button
  2. Choose JSON file
  3. Confirm import

Import shows progress and results; failed rules are marked.

# System tray

Tray icon:

  • Program minimizes to system tray
  • Right-click tray icon to:
    • Show main window
    • Exit program
    • View firewall status

Auto-refresh:

  • Auto-refresh interval configurable
  • Tray icon shows firewall status in real time

# CLI Usage Guide

# Command format

Basic format:

mbfirewall.exe [command] [options]

Enable logging:

mbfirewall.exe --enable-log [command] [options]

Silent mode: Most commands support --silent which:

  • Outputs nothing to console
  • Only returns result via exit code
  • Suitable for scripts

# Command quick reference

Command Function Example
status Query firewall status mbfirewall.exe status
check Check program rules mbfirewall.exe check --app "C:\app.exe"
list List rules mbfirewall.exe list --prefix "MBbrowser"
add Add rule mbfirewall.exe add --app "C:\app.exe"
add-mbbrowser Add MBbrowser rules mbfirewall.exe add-mbbrowser
remove Remove rule mbfirewall.exe remove --app "C:\app.exe"
enable Enable firewall mbfirewall.exe enable --profile all
disable Disable firewall mbfirewall.exe disable --profile public
export Export rules mbfirewall.exe export --output "backup.json"
import Import rules mbfirewall.exe import --input "backup.json"
version Show version mbfirewall.exe version
help Show help mbfirewall.exe help

# Exit codes

All commands return standard exit codes:

Code Meaning Notes
0 Success Operation completed successfully
1 General error Operation failed, check error output
2 Insufficient permissions Requires administrator privileges
3 Invalid parameters Command line argument error
4 Not found Specified resource not found

Use in batch scripts:

@echo off
mbfirewall.exe status --silent
if %ERRORLEVEL% EQU 0 (
    echo Firewall is enabled
) else (
    echo Firewall not enabled or check failed
)

In PowerShell:

.\mbfirewall.exe status --silent
if ($LASTEXITCODE -eq 0) {
    Write-Host "Firewall is enabled"
} else {
    Write-Host "Firewall not enabled or check failed"
}

# Practical examples

# Example 1: Automation deployment script

@echo off
echo Configuring firewall rules ...

REM Add application rule
mbfirewall.exe add --app "C:\\MyApp\\server.exe" --name "MyApp Server" --direction inbound --protocol tcp --ports 8080
if %ERRORLEVEL% NEQ 0 (
    echo Error: failed to add firewall rule
    exit /b 1
)

echo Firewall configuration complete!

# Example 2: Bulk adding multiple apps

@echo off
echo Bulk adding firewall rules ...
mbfirewall.exe add --batch "config\\production_apps.json"
if %ERRORLEVEL% EQU 0 (
    echo Successfully added all rules
) else (
    echo Partial failures occurred, check details
)

# Example 3: Regularly backup rules

@echo off
set BACKUP_DIR=backup\%date:~0,4%%date:~5,2%%date:~8,2%
mkdir "%BACKUP_DIR%"

echo Exporting firewall rules ...
mbfirewall.exe export --output "%BACKUP_DIR%\firewall_rules.json"
echo Backup complete: %BACKUP_DIR%

# Example 4: Installer integration

@echo off
echo Installing application ...
REM Install application
installer.exe /S

echo Configuring firewall ...
mbfirewall.exe add --app "%ProgramFiles%\MyApp\app.exe" --name "MyApp" --silent
if %ERRORLEVEL% EQU 0 (
    echo Firewall configured successfully
) else (
    echo Warning: firewall configuration failed, manual configuration may be required
)

# API Integration and Development

MBfirewall provides a comprehensive command-line interface that can be integrated into other applications by process invocation.

# C++ integration example

# Basic invocation wrapper

#include <windows.h>
#include <string>
#include <iostream>

// Execute mbfirewall.exe command
int ExecuteFirewallCommand(const std::wstring& command, std::wstring& output) {
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    // Create pipe for reading output
    HANDLE hReadPipe, hWritePipe;
    if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) {
        return -1;
    }

    // Ensure read handle is not inherited
    SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

    STARTUPINFOW si = { sizeof(STARTUPINFOW) };
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;
    si.wShowWindow = SW_HIDE;

    PROCESS_INFORMATION pi = { 0 };

    std::wstring cmdLine = L"mbfirewall.exe " + command;

    // Create process
    BOOL success = CreateProcessW(
        NULL,
        const_cast<LPWSTR>(cmdLine.c_str()),
        NULL, NULL, TRUE,
        CREATE_NO_WINDOW,
        NULL, NULL,
        &si, &pi
    );

    if (!success) {
        CloseHandle(hReadPipe);
        CloseHandle(hWritePipe);
        return -1;
    }

    CloseHandle(hWritePipe);

    // Read output
    char buffer[4096];
    DWORD bytesRead;
    std::string result;

    while (ReadFile(hReadPipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
        buffer[bytesRead] = '\0';
        result += buffer;
    }

    // Wait for process to finish
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Get exit code
    DWORD exitCode;
    GetExitCodeProcess(pi.hProcess, &exitCode);

    CloseHandle(hReadPipe);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    // Convert output to wstring
    int len = MultiByteToWideChar(CP_UTF8, 0, result.c_str(), -1, NULL, 0);
    if (len > 0) {
        wchar_t* wbuffer = new wchar_t[len];
        MultiByteToWideChar(CP_UTF8, 0, result.c_str(), -1, wbuffer, len);
        output = wbuffer;
        delete[] wbuffer;
    }

    return exitCode;
}

# Advanced wrapper class

class MBFirewallManager {
private:
    std::wstring exePath;

    int Execute(const std::wstring& args, std::wstring& output) {
        std::wstring fullCmd = args;
        return ExecuteFirewallCommand(fullCmd, output);
    }

public:
    MBFirewallManager(const std::wstring& path = L"mbfirewall.exe")
        : exePath(path) {}

    // Check firewall status
    bool IsFirewallEnabled() {
        std::wstring output;
        return Execute(L"status --silent", output) == 0;
    }

    // Add program rule
    bool AddProgramRule(const std::wstring& appPath, const std::wstring& name) {
        std::wstring output;
        std::wstring cmd = L"add --app \"" + appPath + L"\" --name \"" + name + L"\" --dir both --silent";
        return Execute(cmd, output) == 0;
    }

    // Remove program rule
    bool RemoveProgramRule(const std::wstring& appPath) {
        std::wstring output;
        std::wstring cmd = L"remove --app \"" + appPath + L"\" --silent";
        return Execute(cmd, output) == 0;
    }

    // Check program rule status
    bool IsProgramRuleEnabled(const std::wstring& appPath) {
        std::wstring output;
        std::wstring cmd = L"check --app \"" + appPath + L"\" --silent";
        return Execute(cmd, output) == 0;
    }

    // Enable firewall
    bool EnableFirewall(const std::wstring& profile = L"all") {
        std::wstring output;
        std::wstring cmd = L"enable --profile " + profile + L" --silent";
        return Execute(cmd, output) == 0;
    }

    // Disable firewall
    bool DisableFirewall(const std::wstring& profile = L"all") {
        std::wstring output;
        std::wstring cmd = L"disable --profile " + profile + L" --silent";
        return Execute(cmd, output) == 0;
    }

    // Bulk add rules (using config file)
    bool ImportRules(const std::wstring& configPath) {
        std::wstring output;
        std::wstring cmd = L"import --input \"" + configPath + L"\" --silent";
        return Execute(cmd, output) == 0;
    }
};

# Usage example

int main() {
    MBFirewallManager fw;

    // Check firewall
    if (fw.IsFirewallEnabled()) {
        std::wcout << L"Firewall is enabled" << std::endl;
    }

    // Add MBbrowser rule
    if (fw.AddProgramRule(L"C:\\Program Files\\MBBrowser\\mbbrowser.exe", L"MBbrowser")) {
        std::wcout << L"Rule added successfully" << std::endl;
    }

    // Check rule status
    if (fw.IsProgramRuleEnabled(L"C:\\Program Files\\MBBrowser\\mbbrowser.exe")) {
        std::wcout << L"Rule is enabled" << std::endl;
    }

    return 0;
}

# PowerShell integration

# Wrapper function
function Add-FirewallRule {
    param(
        [string]$AppPath,
        [string]$Name
    )

    $result = & "mbfirewall.exe" add --app $AppPath --name $Name --silent
    return $LASTEXITCODE -eq 0
}

function Check-FirewallStatus {
    $result = & "mbfirewall.exe" status --silent
    return $LASTEXITCODE -eq 0
}

# Usage examples
if (Check-FirewallStatus) {
    Write-Host "Firewall is enabled"
}

if (Add-FirewallRule -AppPath "C:\\App\\app.exe" -Name "MyApp") {
    Write-Host "Rule added successfully"
}

# Python integration

import subprocess
import json

class MBFirewallManager:
    def __init__(self, exe_path="mbfirewall.exe"):
        self.exe_path = exe_path

    def execute(self, args, silent=True):
        cmd = [self.exe_path] + args
        if silent:
            cmd.append("--silent")
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.returncode == 0, result.stdout, result.stderr

    def add_rule(self, app_path, name=None):
        args = ["add", "--app", app_path]
        if name:
            args.extend(["--name", name])
        return self.execute(args)[0]

    def check_status(self, app_path):
        args = ["check", "--app", app_path]
        return self.execute(args)[0]

    def enable_firewall(self, profile="all"):
        args = ["enable", "--profile", profile]
        return self.execute(args)[0]

# Usage example
fw = MBFirewallManager()
if fw.add_rule("C:\\App\\app.exe", "MyApp"):
    print("Rule added successfully")

# MBbrowser Integration

MBfirewall provides deep integration features for MBbrowser that make configuring MBbrowser firewall rules extremely simple.

# Integration feature overview

Core features:

  • Automatically detect installation path (read from registry)
  • One-click configure all rules (18 rules)
  • Skip non-existent files intelligently
  • Detailed execution feedback

Supported programs: 9 core MBbrowser program files; each program will have inbound and outbound rules added for a total of 18 rules.

# Usage

Simplest usage:

mbfirewall.exe add-mbbrowser

Enable logging usage:

mbfirewall.exe --enable-log add-mbbrowser

# Working details

# Installation path detection

MBfirewall reads MBbrowser install path from the registry: HKEY_CURRENT_USER\\SOFTWARE\\MBbrowser\\Path

If the registry does not contain this path, the command will fail with a clear error message.

# Program file detection

MBfirewall checks whether the following program files exist:

Program file Path location Description
mbbrowser.exe {install_path}\mbbrowser.exe MBbrowser main program
cdp.exe {install_path}\cdp.exe Chrome DevTools Protocol
mbservice.exe {install_path}\mbservice.exe MBbrowser background service
apiserver.exe {install_path}\apiserver.exe API server
chrome.exe {install_path}\MBbrowser\chrome.exe Chrome core
chrome_proxy.exe {install_path}\MBbrowser\chrome_proxy.exe Chrome proxy
chrome_pwa_launcher.exe {install_path}\MBbrowser\chrome_pwa_launcher.exe Chrome PWA launcher
chromedriver.exe {install_path}\MBbrowser\chromedriver.exe Browser automation driver
notification_helper.exe {install_path}\MBbrowser\notification_helper.exe Notification helper

Intelligent handling:

  • If a file does not exist, it will be skipped and processing continues for other files
  • Warnings are shown but do not block other configurations

# Rule configuration

Each program will have two rules added:

  1. Inbound rule: allow external access to the program
  2. Outbound rule: allow the program to access external networks

Protocol and port configuration:

Program Protocol Ports Notes
mbbrowser.exe any * Main program needs full network access
cdp.exe tcp 9222 CDP debug service port
mbservice.exe any * Background service needs full network access
apiserver.exe tcp 80,443 API server standard ports
chrome.exe tcp 80,443 Web access standard ports
chrome_proxy.exe tcp 80,443 Web access standard ports
chrome_pwa_launcher.exe tcp 80,443 Web access standard ports
chromedriver.exe tcp 9515 ChromeDriver default port
notification_helper.exe tcp 80,443 Notification service ports

# Execution result display

Success example:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Execution Results
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Successfully added all 18 rules
Added firewall rules for the following programs:
  • mbbrowser.exe
  • cdp.exe
  • mbservice.exe
  • apiserver.exe
  • chrome.exe
  • chrome_proxy.exe
  • chrome_pwa_launcher.exe
  • chromedriver.exe
  • notification_helper.exe
Each program had inbound and outbound rules added