How to Scan Configuration Files for Security Issues in Python
Automatically scan configuration files for common security mistakes using regex rules in Python.
Python code
47 linesimport re
import os
from pathlib import Path
SECURITY_RULES = [
(r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
(r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
(r'debug\s*=\s*True', 'Debug mode enabled'),
(r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin enabled'),
]
def scan_config_file(filepath: str) -> list[tuple[int, str, str]]:
issues = []
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
for pattern, description in SECURITY_RULES:
if re.search(pattern, line.strip()):
issues.append((line_num, line.strip()[:60], description))
break
except (FileNotFoundError, PermissionError) as e:
issues.append((0, str(e), 'File access error'))
return issues
def scan_directory(directory: str) -> dict[str, list[tuple[int, str, str]]]:
results = {}
for path in Path(directory).rglob('*'):
if path.is_file() and not path.name.startswith('.'):
issues = scan_config_file(str(path))
if issues:
results[str(path)] = issues
return results
if __name__ == '__main__':
config_dir = 'sample_configs'
os.makedirs(config_dir, exist_ok=True)
with open(f'{config_dir}/app.conf', 'w') as f:
f.write('# INSECURE_SSL enabled = False\n')
f.write('password = secret123\n')
f.write('debug = True\n')
with open(f'{config_dir}/ssh_config', 'w') as f:
f.write('PermitRootLogin yes\n')
findings = scan_directory(config_dir)
for filepath, issues in sorted(findings.items()):
print(f"File: {filepath}")
for line_num, line_snippet, desc in issues:
print(f" Line {line_num}: '{line_snippet}' → {desc}")
Output
File: sample_configs/app.conf
Line 1: '# INSECURE_SSL enabled = False' → Insecure comment starts with # INSECURE_
Line 2: 'password = secret123' → Hardcoded password
Line 3: 'debug = True' → Debug mode enabled
File: sample_configs/ssh_config
Line 1: 'PermitRootLogin yes' → PermitRootLogin enabled
How it works
The script defines a list of security rules as regex patterns and descriptions. It scans each file line by line using re.search for matches. The scan_config_file function handles file access errors gracefully with try-except. scan_directory walks through a directory recursively using pathlib.Path.rglob to collect issues from all files. Results are output per file with the line number and matching snippet.
Common mistakes
- Not using `errors='ignore'` when reading files with unknown encoding, causing UnicodeDecodeError.
- Using `re.match` instead of `re.search` to only check start of line, missing patterns mid-line.
- Forgetting to handle permission errors, which stops the scan on restricted files.
Variations
- Use `fnmatch` patterns to filter only specific file extensions like .conf or .ini.
- Implement a CLI with `argparse` to accept custom rules or directories.
Real-world use cases
- CI/CD pipeline step that catches hardcoded secrets before merging code into production.
- DevOps tool that audits configurations across thousands of servers for compliance.
- Security scanner integrated into an IDE to flag insecure settings during development.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.