Skip to main content
Glama
Heht571
by Heht571

check_firewall_config

Verify firewall rules and open ports on remote servers to identify security vulnerabilities and ensure proper network access controls.

Instructions

检查防火墙配置和开放端口

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
hostnameYes
usernameYes
passwordNo
portNo
timeoutNo

Implementation Reference

  • Primary handler implementation for the 'check_firewall_config' MCP tool. Performs detailed SSH-based checks for UFW, firewalld, iptables status, rules, and open ports.
    def check_firewall_config(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        timeout: int = 30
    ) -> dict:
        """检查防火墙配置和开放端口"""
        result = {"status": "unknown", "firewall": {"active": False, "type": "unknown"}, "open_ports": [], "rules": [], "error": ""}
    
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 检查UFW状态(Ubuntu/Debian)
                ufw_command = "which ufw > /dev/null && ufw status || echo 'ufw not found'"
                stdin, stdout, stderr = ssh.exec_command(ufw_command, timeout=timeout)
                ufw_output = stdout.read().decode().strip()
    
                # 检查firewalld状态(CentOS/RHEL)
                firewalld_command = "which firewall-cmd > /dev/null && firewall-cmd --state || echo 'firewalld not found'"
                stdin, stdout, stderr = ssh.exec_command(firewalld_command, timeout=timeout)
                firewalld_output = stdout.read().decode().strip()
    
                # 检查iptables状态
                iptables_command = "which iptables > /dev/null && iptables -L -n || echo 'iptables not found'"
                stdin, stdout, stderr = ssh.exec_command(iptables_command, timeout=timeout)
                iptables_output = stdout.read().decode().strip()
    
                # 确定防火墙类型和状态
                if "Status: active" in ufw_output:
                    result["firewall"]["type"] = "ufw"
                    result["firewall"]["active"] = True
    
                    # 获取UFW规则
                    ufw_rules_command = "ufw status numbered"
                    stdin, stdout, stderr = ssh.exec_command(ufw_rules_command, timeout=timeout)
                    ufw_rules = stdout.read().decode().strip()
    
                    # 解析UFW规则和开放端口
                    for line in ufw_rules.split('\n'):
                        if "ALLOW" in line or "DENY" in line:
                            result["rules"].append(line.strip())
                            # 提取端口
                            port_match = re.search(r'(\d+)/tcp', line)
                            if port_match:
                                result["open_ports"].append(port_match.group(1))
    
                elif "running" in firewalld_output:
                    result["firewall"]["type"] = "firewalld"
                    result["firewall"]["active"] = True
    
                    # 获取firewalld区域和规则
                    zones_command = "firewall-cmd --list-all-zones"
                    stdin, stdout, stderr = ssh.exec_command(zones_command, timeout=timeout)
                    zones_output = stdout.read().decode().strip()
    
                    # 解析firewalld规则
                    current_zone = None
                    for line in zones_output.split('\n'):
                        if line.endswith("(active)"):
                            current_zone = line.split()[0]
                        if current_zone and "ports:" in line:
                            ports = line.split("ports:")[1].strip()
                            for port in ports.split():
                                if "/" in port:
                                    result["open_ports"].append(port.split("/")[0])
                                    result["rules"].append(f"{current_zone} zone: {port}")
    
                elif "Chain INPUT" in iptables_output:
                    result["firewall"]["type"] = "iptables"
                    result["firewall"]["active"] = True
    
                    # 解析iptables规则
                    for line in iptables_output.split('\n'):
                        if "ACCEPT" in line and "dpt:" in line:
                            port_match = re.search(r'dpt:(\d+)', line)
                            if port_match:
                                result["open_ports"].append(port_match.group(1))
                                result["rules"].append(line.strip())
    
                else:
                    result["firewall"]["type"] = "none"
                    result["firewall"]["active"] = False
                    result["rules"].append("未检测到活动的防火墙")
    
                # 如果没有检测到防火墙规则,尝试使用netstat或ss检查开放端口
                if not result["open_ports"]:
                    ports_command = "ss -tuln || netstat -tuln"
                    stdin, stdout, stderr = ssh.exec_command(ports_command, timeout=timeout)
                    ports_output = stdout.read().decode().strip()
    
                    for line in ports_output.split('\n'):
                        if "LISTEN" in line:
                            port_match = re.search(r':(\d+)', line)
                            if port_match:
                                result["open_ports"].append(port_match.group(1))
    
                # 去重开放端口
                result["open_ports"] = list(set(result["open_ports"]))
                result["status"] = "success"
    
        except Exception as e:
            result["status"] = "error"
            result["error"] = str(e)
    
        return result
  • Secondary handler for SSE version of 'check_firewall_config'. Simpler check for firewall services status via SSH.
    def check_firewall_config(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        timeout: int = 30
    ) -> dict:
        """检查防火墙配置"""
        result = {"status": "unknown", "firewall_info": {}, "error": ""}
    
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 检查常见的防火墙服务
                firewall_services = ["ufw", "firewalld", "iptables"]
                firewall_info = {}
    
                for fw in firewall_services:
                    if fw == "ufw":
                        stdin, stdout, stderr = ssh.exec_command("ufw status", timeout=timeout)
                        output = stdout.read().decode().strip()
                        if "Status: active" in output:
                            firewall_info["ufw"] = {
                                "active": True,
                                "rules": output.split('\n')[1:] if len(output.split('\n')) > 1 else []
                            }
                        else:
                            firewall_info["ufw"] = {"active": False}
    
                    elif fw == "firewalld":
                        stdin, stdout, stderr = ssh.exec_command("firewall-cmd --state", timeout=timeout)
                        output = stdout.read().decode().strip()
                        if output == "running":
                            # 获取区域信息
                            stdin, stdout, stderr = ssh.exec_command("firewall-cmd --list-all", timeout=timeout)
                            zones_output = stdout.read().decode().strip()
                            firewall_info["firewalld"] = {
                                "active": True,
                                "config": zones_output
                            }
                        else:
                            firewall_info["firewalld"] = {"active": False}
    
                    elif fw == "iptables":
                        stdin, stdout, stderr = ssh.exec_command("iptables -L", timeout=timeout)
                        output = stdout.read().decode().strip()
                        # 简单检查是否有规则
                        has_rules = len(output.split('\n')) > 6  # 基本的链定义通常有6行
                        firewall_info["iptables"] = {
                            "active": has_rules,
                            "rules": output.split('\n')
                        }
    
                result["firewall_info"] = firewall_info
                result["status"] = "success"
    
        except Exception as e:
            result["status"] = "error"
            result["error"] = str(e)
    
        return result
  • Registration of the check_firewall_config handler in the MCP tools dictionary and dynamic @mcp.tool() decoration in server_monitor.
    tools_dict = {
        'get_memory_info': get_memory_info,
        'remote_server_inspection': remote_server_inspection,
        'get_system_load': get_system_load,
        'monitor_processes': monitor_processes,
        'check_service_status': check_service_status,
        'get_os_details': get_os_details,
        'check_ssh_risk_logins': check_ssh_risk_logins,
        'check_firewall_config': check_firewall_config,
        'security_vulnerability_scan': security_vulnerability_scan,
        'backup_critical_files': backup_critical_files,
        'inspect_network': inspect_network,
        'analyze_logs': analyze_logs,
        'list_docker_containers': list_docker_containers,
        'list_docker_images': list_docker_images,
        'list_docker_volumes': list_docker_volumes,
        'get_container_logs': get_container_logs,
        'monitor_container_stats': monitor_container_stats,
        'check_docker_health': check_docker_health
    }
    
    # 使用装饰器动态注册所有工具
    for name, func in tools_dict.items():
        mcp.tool()(func)
  • Tool dispatch registration in SSE server's @app.call_tool() handler for check_firewall_config.
    elif name == "check_firewall_config":
        required_args = ["hostname", "username"]
        for arg in required_args:
            if arg not in arguments:
                raise ValueError(f"Missing required argument '{arg}'")
    
        result = check_firewall_config(
            hostname=arguments["hostname"],
            username=arguments["username"],
            password=arguments.get("password", ""),
            port=arguments.get("port", 22),
            timeout=arguments.get("timeout", 30)
        )
  • JSON schema definition for the check_firewall_config tool parameters and description.
    {"name": "check_firewall_config", "description": "检查防火墙配置和开放端口", "parameters": [
        {"name": "hostname", "type": "str", "default": None},
        {"name": "username", "type": "str", "default": None},
        {"name": "password", "type": "str", "default": ""},
        {"name": "port", "type": "int", "default": 22},
        {"name": "timeout", "type": "int", "default": 30}
    ]},
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It states the tool checks configuration and ports, but doesn't disclose behavioral traits such as whether it performs read-only operations (likely, but not confirmed), authentication requirements (implied by username/password parameters but not explained), potential side effects, or output format. This leaves significant gaps for an agent to understand how to invoke it safely.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence in Chinese ('检查防火墙配置和开放端口') that directly states the purpose without unnecessary words. It's appropriately sized and front-loaded, with zero waste, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (a tool with 5 parameters for checking firewall configurations, likely involving remote access), no annotations, no output schema, and 0% schema coverage, the description is incomplete. It doesn't provide enough context for an agent to understand the tool's behavior, inputs, or outputs, making it inadequate for safe and effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning parameters like hostname, username, password, port, and timeout are undocumented in the schema. The description adds no parameter semantics—it doesn't explain what these inputs mean (e.g., hostname for target server, password for authentication) or how they affect the check. This fails to compensate for the low coverage, leaving parameters ambiguous.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description '检查防火墙配置和开放端口' (Check firewall configuration and open ports) clearly states the tool's purpose with a specific verb ('check') and resource ('firewall configuration and open ports'), but it doesn't distinguish this from sibling tools like 'inspect_network' or 'security_vulnerability_scan', which might have overlapping functionality. The purpose is understandable but lacks sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., SSH access implied by parameters), exclusions, or compare it to siblings like 'inspect_network' or 'security_vulnerability_scan'. Usage is implied through the action but not explicitly stated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Heht571/ops-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server