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.txtpython main.py analyzepython main.py optimizepython main.py visualizepython main.py webappThat'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 analyzepython main.py analyze --input /path/to/iptables-rules.txtpython main.py analyze --input systempython 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.0python main.py backup --input system --description "Before optimization"python main.py restore --backup /path/to/backup.jsonLaunch the interactive web interface:
python main.py webappThen 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 --backuppython main.py visualize --input rules.txt --output ./reportspython main.py visualize --input rules.txt --output ./reports --type flowpython main.py backup --input system --description "Before optimization"python main.py restore --backup backup_20250126_143022.json --applyfromoptimizerimport ( IptablesParser, FirewallAnalyzer, FirewallRecommender, FirewallVisualizer ) # Initialize componentsparser=IptablesParser() analyzer=FirewallAnalyzer() recommender=FirewallRecommender() visualizer=FirewallVisualizer() # Load and parse configurationwithopen('rules.txt', 'r') asf: rules_content=f.read() config=parser.parse_iptables_save(rules_content) # Analyze configurationanalysis=analyzer.analyze_configuration(config) print(f"Security Score: {analysis.security_score:.1f}/100") print(f"Issues Found: {len(analysis.issues)}") # Generate recommendationsplan=recommender.generate_recommendations(config, analysis) print(f"Recommendations: {len(plan.recommendations)}") # Create visualizationsflow_chart=visualizer.create_rule_flow_diagram(config) dashboard=visualizer.create_issue_dashboard(analysis) # Show interactive plotsflow_chart.show() dashboard.show()- COMMANDS.md - Comprehensive command documentation with examples
- Use
python main.py --helpfor general help - Use
python main.py <command> --helpfor 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.yamlbackup: enabled: truedirectory: './backups'max_backups: 10auto_backup_before_changes: trueanalysis: check_redundant_rules: truecheck_conflicting_rules: truecheck_rule_ordering: truecheck_unreachable_rules: truecheck_security_issues: trueconfidence_threshold: 0.8security: allow_system_modifications: falserequire_sudo_confirmation: truevalidate_rules_before_apply: truevisualization: default_theme: 'plotly_white'save_format: 'html'include_interactive: trueFIREWALL 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_reportsstreamlit- 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

.png?raw=true)
