A comprehensive Python-based tool that analyzes Linux iptables
firewall rules, detects redundant or conflicting rules, suggests optimization strategies, and provides interactive visualizations with beautiful CLI graphics for better security management.
- Redundant Rule Detection: Identifies duplicate rules that can be removed
- Conflict Resolution: Finds rules that contradict each other
- Performance Optimization: Suggests rule reordering for better efficiency
- Security Analysis: Detects potential security vulnerabilities
- Unreachable Rule Detection: Finds rules that will never be executed
- Priority-based Suggestions: Categorizes recommendations by importance (π₯Critical, π¨High,
β οΈ Medium, π‘Low) - Risk Assessment: Evaluates the risk level of each recommendation
- Impact Analysis: Estimates performance and security improvements
- Implementation Guidance: Provides step-by-step instructions
- Colorful Progress Bars: Visual score representation for security and efficiency
- ASCII Bar Charts: Issue distribution visualization
- Severity Pie Charts: Visual breakdown of issue severity levels
- Priority Charts: Recommendation priorities with icons and colors
- Impact Gauges: Visual optimization benefits display
- Professional Styling: VS Code-like syntax highlighting with emojis
- Interactive Rule Flow Diagrams: Visualize packet flow through rules
- Dependency Graphs: Show relationships between chains and rules
- Security Dashboards: Real-time security and efficiency scores
- Rule Coverage Heatmaps: Analyze protocol and port coverage
- Optimization Impact Charts: Visualize potential improvements
- Enhanced CLI: Beautiful terminal interface with charts and colors
- Web Interface: User-friendly Streamlit-based GUI with interactive features
- Python API: Integrate into your own applications
- Python 3.8 or higher
- Linux system with
iptables
(for live analysis) - Administrator privileges (for applying changes)
- Clone the repository:
git clone https://github.com/your-username/firewall-optimizer.git
cd firewall-optimizer
- Install dependencies:
pip install -r requirements.txt
python main.py analyze
python main.py optimize
python main.py visualize
python main.py webapp
That's it! The tool includes sample data, so you can start exploring immediately!
Our enhanced CLI provides a beautiful terminal experience with:
- π₯ Colorful Startup Banner with ASCII art
- π Progress Bars for security and efficiency scores
- π Bar Charts showing issue distribution
- π₯§ Pie Charts for severity level breakdown
- π― Priority Visualization for recommendations
- β‘ Impact Gauges showing optimization benefits
- π Color-coded Output for easy reading
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β π₯ AI-Powered Firewall Rule Optimizer π₯ β
β β
β Analyze β’ Optimize β’ Visualize β’ Secure β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββ
π Score Overview
ββββββββββββββββββββββββββββββββββββββββ
Security Score.......... ββββββββββββββββββββββββββββββ 54.0%
Efficiency Score........ ββββββββββββββββββββββββββββββββ 5.0%
ββββββββββββββββββββββββββββββββββββββββ
π Issues Distribution
ββββββββββββββββββββββββββββββββββββββββ
Conflicting............. ββββββββββββββββββββββββββββββββ 15
Unreachable............. ββββββββββββββββββββββββββββββ 13
Inefficient Order....... ββββββββββββββββββββββββ 11
Security Risk........... ββββ 2
π Run in your browser:
python main.py webapp
π§ AI-Powered Analysis Dashboard
π Real-time Visualizations of Issues and Priorities
π Rule Flow Diagrams & Dependency Mapping
python main.py analyze
python main.py analyze --input /path/to/iptables-rules.txt
python main.py analyze --input system
python main.py analyze --output report.json --format json
# Generate recommendations with visual priority charts
python main.py optimize
# Optimize specific configuration
python main.py optimize --input /path/to/rules.txt
# Save optimized rules
python main.py optimize --input rules.txt --output optimized.txt
# Apply to system with backup (requires root)
sudo python main.py optimize --input system --apply --backup
# Create all interactive visualizations
python main.py visualize
# Specific visualization types
python main.py visualize --type flow # Rule flow diagram
python main.py visualize --type issues # Issues dashboard
python main.py visualize --type graph # Network topology
# Launch web app (default: localhost:8501)
python main.py webapp
# Custom port and host
python main.py webapp --port 8080 --host 0.0.0.0
python main.py backup --input system --description "Before optimization"
python main.py restore --backup /path/to/backup.json
Launch the interactive web interface:
python main.py webapp
Then open your browser to http://localhost:8501
Features:
- π Upload firewall configuration files or use sample data
- π Real-time analysis with colorful charts and metrics
- π Interactive visualizations and dashboards
- πΎ Backup and restore functionality
- βοΈ Configurable analysis settings
- π€ Export reports in multiple formats
Our CLI features beautiful terminal graphics with:
- π¨ VS Code-like syntax highlighting with colors
- π ASCII progress bars and charts
- π₯ Emoji-rich output for better readability
- π Visual data representation right in your terminal
For complete command documentation, see COMMANDS.md - a comprehensive guide with:
- π All available commands and options
- π‘ Usage examples and best practices
- π¨ CLI features and visual elements
- π§ Advanced configuration options
- π¨ Safety features and troubleshooting
# Analyze a configuration file
python main.py analyze --input /etc/iptables/rules.v4
# Analyze current system rules
python main.py analyze --input system
# Save analysis to file
python main.py analyze --input rules.txt --output analysis.json --format json
# Generate recommendations
python main.py optimize --input rules.txt
# Generate and save optimized rules
python main.py optimize --input rules.txt --output optimized_rules.txt
# Apply optimizations (with backup)
python main.py optimize --input system --apply --backup
python main.py visualize --input rules.txt --output ./reports
python main.py visualize --input rules.txt --output ./reports --type flow
python main.py backup --input system --description "Before optimization"
python main.py restore --backup backup_20250126_143022.json --apply
from optimizer import (
IptablesParser, FirewallAnalyzer,
FirewallRecommender, FirewallVisualizer
)
# Initialize components
parser = IptablesParser()
analyzer = FirewallAnalyzer()
recommender = FirewallRecommender()
visualizer = FirewallVisualizer()
# Load and parse configuration
with open('rules.txt', 'r') as f:
rules_content = f.read()
config = parser.parse_iptables_save(rules_content)
# Analyze configuration
analysis = analyzer.analyze_configuration(config)
print(f"Security Score: {analysis.security_score:.1f}/100")
print(f"Issues Found: {len(analysis.issues)}")
# Generate recommendations
plan = recommender.generate_recommendations(config, analysis)
print(f"Recommendations: {len(plan.recommendations)}")
# Create visualizations
flow_chart = visualizer.create_rule_flow_diagram(config)
dashboard = visualizer.create_issue_dashboard(analysis)
# Show interactive plots
flow_chart.show()
dashboard.show()
- COMMANDS.md - Comprehensive command documentation with examples
- Use
python main.py --help
for general help - Use
python main.py <command> --help
for command-specific help
- Beautiful Visual Output: ASCII progress bars, charts, and colored text
- Instant Feedback: No configuration needed - works with sample data
- Professional Styling: VS Code-like syntax highlighting with emojis
- Smart Graphics: Charts adjust to terminal width automatically
- Cross-Platform: Works on Windows, macOS, and Linux
- Comprehensive: Analysis, optimization, visualization, and web interface
- Detects 47+ different types of firewall issues
- Provides actionable recommendations for each issue
- Calculates security and efficiency scores
- Identifies unreachable and redundant rules
- Beautiful terminal graphics without external dependencies
- Real-time progress indicators during analysis
- Color-coded severity levels (π΄Critical, π‘Medium, π’Low)
- Interactive web charts with Plotly integration
- Automatic backup creation before any changes
- Dry-run mode by default (no accidental modifications)
- Comprehensive logging and audit trails
- Linux system integration with iptables
firewall-optimizer/
β
βββ data/ # Sample data and test files
β βββ sample_rules.txt # Sample iptables rules
β
βββ optimizer/ # Core optimizer package
β βββ __init__.py # Package initialization
β βββ parser.py # Iptables rule parser
β βββ analyzer.py # Rule analysis engine
β βββ recommender.py # Optimization recommender
β βββ visualizer.py # Visualization components
β βββ utils.py # Utility functions
β
βββ web_ui/ # Streamlit web interface
β βββ app.py # Main web application
β
βββ main.py # Command line interface
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ .github/
βββ copilot-instructions.md # Copilot customization
The optimizer can be configured through YAML configuration files:
# optimizer_config.yaml
backup:
enabled: true
directory: './backups'
max_backups: 10
auto_backup_before_changes: true
analysis:
check_redundant_rules: true
check_conflicting_rules: true
check_rule_ordering: true
check_unreachable_rules: true
check_security_issues: true
confidence_threshold: 0.8
security:
allow_system_modifications: false
require_sudo_confirmation: true
validate_rules_before_apply: true
visualization:
default_theme: 'plotly_white'
save_format: 'html'
include_interactive: true
FIREWALL ANALYSIS RESULTS
============================================================
Overall Scores:
Security Score: 78.5/100
Efficiency Score: 85.2/100
Statistics:
Total Rules: 23
Total Chains: 6
Total Tables: 3
Accept Rules: 8
Drop Rules: 12
Reject Rules: 1
Issues Found (4):
Redundant (2 issues):
β’ Redundant rule found: duplicate of rule at line 15
β Remove the duplicate rule to improve performance
β’ Redundant rule found: duplicate of rule at line 22
β Remove the duplicate rule to improve performance
Security Risk (1 issues):
β’ Administrative port 22 open to all sources
β Restrict access to administrative ports to specific source IPs
Inefficient Order (1 issues):
β’ Specific rule at line 18 comes after general rule at line 12
β Move more specific rules before general ones for better performance
- Dry Run Mode: All operations default to dry run mode
- Automatic Backups: Creates backups before any modifications
- Rule Validation: Validates rules before applying changes
- Confirmation Prompts: Requires explicit confirmation for system changes
- Rollback Capability: Can restore from backups if needed
- Always test in dry run mode first
- Create backups before making changes
- Validate optimized rules in a test environment
- Review all recommendations before applying
- Keep the original configuration as a backup
Issue Type | Before | After | Impact |
---|---|---|---|
Redundancy | -A INPUT -p tcp --dport 22 -j ACCEPT (duplicated) |
Single occurrence | Reduced rule count |
Conflict | Allow port 80, then deny port 80 | Resolved based on policy | Predictable behavior |
Inefficiency | Broad ACCEPT before specific DROP | Reordered for security | Better performance |
Security | SSH open to 0.0.0.0/0 | Restricted to specific IPs | Reduced attack surface |
Run the example analysis with sample data:
# Test with sample rules
python main.py analyze --input data/sample_rules.txt
# Test web interface
python main.py webapp
# Test visualization generation
python main.py visualize --input data/sample_rules.txt --output ./test_reports
streamlit
- Web interface frameworkpandas
- Data manipulation and analysisnumpy
- Numerical computingmatplotlib
- Static plottingplotly
- Interactive plottingnetworkx
- Graph analysisseaborn
- Statistical visualizationpyparsing
- Text parsingpyyaml
- YAML configurationclick
- Command line interface
scikit-learn
- Machine learning (for advanced analysis)xgboost
- Gradient boosting (for ML features)dash
- Alternative web frameworkflask
- Lightweight web framework
We welcome contributions! Please see our contributing guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
# Clone the repository
git clone https://github.com/your-username/firewall-optimizer.git
cd firewall-optimizer
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install development dependencies
pip install -r requirements.txt
pip install -e .
# Run tests
python -m pytest tests/
# Run linting
black optimizer/
flake8 optimizer/
mypy optimizer/
This project is licensed under the MIT License - see the LICENSE file for details.
- iptables - The Linux firewall utility that makes this project possible
- Streamlit - For providing an excellent web framework for data applications
- Plotly - For interactive visualization capabilities
- NetworkX - For graph analysis and visualization
- The Python Community - For the amazing ecosystem of tools and libraries
- π§ Email: [email protected]
- π Issues: GitHub Issues
- π¬ Discussions: GitHub Discussions
β Star this repository if you find it useful!
Made with β€οΈ by the Akshay Kale