mirror of
https://github.com/Jerryplusy/AI-powered-switches.git
synced 2025-10-14 01:39:18 +00:00
85 lines
2.9 KiB
Python
85 lines
2.9 KiB
Python
import re
|
|
from typing import Dict, List, Tuple
|
|
from ..utils.exceptions import SwitchConfigException
|
|
|
|
|
|
class ConfigValidator:
|
|
@staticmethod
|
|
def validate_vlan_config(config: Dict) -> Tuple[bool, str]:
|
|
"""验证VLAN配置"""
|
|
if 'vlan_id' not in config:
|
|
return False, "Missing VLAN ID"
|
|
|
|
vlan_id = config['vlan_id']
|
|
if not (1 <= vlan_id <= 4094):
|
|
return False, f"Invalid VLAN ID {vlan_id}. Must be 1-4094"
|
|
|
|
if 'name' in config and len(config['name']) > 32:
|
|
return False, "VLAN name too long (max 32 chars)"
|
|
|
|
return True, "Valid VLAN config"
|
|
|
|
@staticmethod
|
|
def validate_interface_config(config: Dict) -> Tuple[bool, str]:
|
|
"""验证接口配置"""
|
|
required_fields = ['interface', 'ip_address']
|
|
for field in required_fields:
|
|
if field not in config:
|
|
return False, f"Missing required field: {field}"
|
|
|
|
# 验证IP地址格式
|
|
ip_pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$'
|
|
if not re.match(ip_pattern, config['ip_address']):
|
|
return False, "Invalid IP address format"
|
|
|
|
# 验证接口名称格式
|
|
interface_pattern = r'^(GigabitEthernet|FastEthernet|Eth)\d+/\d+/\d+$'
|
|
if not re.match(interface_pattern, config['interface']):
|
|
return False, "Invalid interface name format"
|
|
|
|
return True, "Valid interface config"
|
|
|
|
@staticmethod
|
|
def check_security_risks(commands: List[str]) -> List[str]:
|
|
"""检查潜在安全风险"""
|
|
risky_commands = []
|
|
dangerous_patterns = [
|
|
r'no\s+aaa', # 禁用认证
|
|
r'enable\s+password', # 明文密码
|
|
r'service\s+password-encryption', # 弱加密
|
|
r'ip\s+http\s+server', # 启用HTTP服务
|
|
r'no\s+ip\s+http\s+secure-server' # 禁用HTTPS
|
|
]
|
|
|
|
for cmd in commands:
|
|
for pattern in dangerous_patterns:
|
|
if re.search(pattern, cmd, re.IGNORECASE):
|
|
risky_commands.append(cmd)
|
|
break
|
|
|
|
return risky_commands
|
|
|
|
@staticmethod
|
|
def validate_full_config(config: Dict) -> Tuple[bool, List[str]]:
|
|
"""全面验证配置"""
|
|
errors = []
|
|
|
|
if 'type' not in config:
|
|
errors.append("Missing configuration type")
|
|
return False, errors
|
|
|
|
if config['type'] == 'vlan':
|
|
valid, msg = ConfigValidator.validate_vlan_config(config)
|
|
if not valid:
|
|
errors.append(msg)
|
|
elif config['type'] == 'interface':
|
|
valid, msg = ConfigValidator.validate_interface_config(config)
|
|
if not valid:
|
|
errors.append(msg)
|
|
|
|
if 'commands' in config:
|
|
risks = ConfigValidator.check_security_risks(config['commands'])
|
|
if risks:
|
|
errors.append(f"Potential security risks detected: {', '.join(risks)}")
|
|
|
|
return len(errors) == 0, errors |