Skip to content

Sherin-SEF-AI/nmap-agent

Repository files navigation

Nmap Automation with AI Integration

A comprehensive Python application for automated network scanning using nmap with intelligent AI integration via Ollama. This tool provides intelligent command generation, result analysis, and automated decision-making for network security assessments.

⚠️ LEGAL WARNING

IMPORTANT: This tool is designed for authorized network security testing only.

Before using this tool, you MUST:

  1. OWN THE NETWORK you are scanning, OR
  2. HAVE EXPLICIT WRITTEN PERMISSION from the network owner, OR
  3. BE AUTHORIZED by your organization to perform security assessments

UNAUTHORIZED SCANNING MAY BE ILLEGAL and could result in:

  • Criminal charges
  • Civil lawsuits
  • Network disruption
  • Legal penalties

By using this tool, you acknowledge that you have proper authorization and will use it responsibly and ethically.

Features

🤖 AI-Powered Intelligence

  • Natural Language to Nmap Commands: AI generates optimized nmap commands based on scan objectives
  • Intelligent Result Analysis: AI analyzes scan results for security insights and recommendations
  • Automated Decision Making: AI determines next scanning actions based on discovered information
  • Risk Assessment: Automated risk scoring and prioritization of findings

🔒 Security & Safety

  • Target Authorization: Strict network range validation and authorization checks
  • Command Validation: Security validation and sanitization of all nmap commands
  • Rate Limiting: Built-in rate limiting and timing controls
  • Audit Logging: Comprehensive logging of all scanning activities
  • Timeout Protection: Scan timeout controls to prevent resource exhaustion

🔄 Automation Workflow

  • Multi-Phase Scanning: Discovery → Port Scan → Service Scan → Vulnerability Scan
  • Adaptive Scanning: Adjusts scanning strategy based on discovered information
  • Progress Tracking: Real-time progress monitoring and reporting
  • Error Recovery: Robust error handling and recovery mechanisms

📊 Result Management

  • Multiple Output Formats: JSON, XML, CSV, and text output formats
  • Structured Analysis: Parsed and structured scan results
  • Risk Assessment: Automated risk scoring and categorization
  • Executive Summaries: AI-generated executive summaries and recommendations

Installation

Prerequisites

  • Python 3.8 or higher
  • Nmap installed and accessible in PATH
  • Ollama installed and running locally

Setup

  1. Clone the repository:

    git clone <repository-url>
    cd nmap-auto
  2. Install Python dependencies:

    pip install -r requirements.txt
  3. Install and configure Ollama:

    # Install Ollama (follow instructions at https://ollama.ai)
    curl -fsSL https://ollama.ai/install.sh | sh
    
    # Pull the AI model
    ollama pull llama3.2
    
    # Start Ollama service
    ollama serve
  4. Verify nmap installation:

    nmap --version
  5. Configure the application:

    • Edit config.yaml to set your preferred settings
    • Ensure allowed networks are configured for your environment
    • Set appropriate scan timeouts and limits

Configuration

The application uses config.yaml for configuration. Key settings include:

Network Security

allowed_networks:
  - "192.168.0.0/16"  # Your local network
  - "10.0.0.0/8"      # Private network

AI Configuration

ollama_model: "llama3.2"
ollama_url: "http://localhost:11434/api/generate"
ollama_timeout: 30

Scan Settings

scan_timeout: 3600        # Maximum scan duration
max_scan_phases: 5        # Limit on automation phases
phase_delay: 30           # Delay between phases
allow_aggressive_scans: false

Output Settings

output_settings:
  formats: ["json", "xml", "txt"]
  directory: "./scan_results"
  timestamp_format: "%Y%m%d_%H%M%S"

Usage

Command Line Interface

Single Target Scan

# Basic discovery scan
python main.py --target 192.168.1.1

# Specific scan type
python main.py --target 192.168.1.1 --scan-type port_scan

# Network range scan
python main.py --range 192.168.1.0/24 --scan-type discovery

Automated Multi-Phase Scan

# Full automated scan
python main.py --target 192.168.1.1 --automated

# Automated scan with custom initial type
python main.py --target example.com --automated --scan-type port_scan

Configuration and Testing

# View current configuration
python main.py --config

# Test AI connection
python main.py --test-ai

Interactive Mode

Run without arguments to enter interactive mode:

python main.py

The interactive menu provides:

  1. Single Target Scan
  2. Network Range Scan
  3. Automated Multi-Phase Scan
  4. View Configuration
  5. Test AI Connection
  6. Exit

Programmatic Usage

from nmap_automation import NmapAutomation

# Initialize automation
automation = NmapAutomation()

# Run automated scan
results = automation.run_automated_scan("192.168.1.1", "discovery")

# Run single scan
command = automation.generate_scan_command("192.168.1.1", "port_scan")
stdout, stderr, return_code = automation.execute_scan(command)
results = automation.analyze_results(stdout, "port_scan")

Scan Types

Discovery Scan

  • Purpose: Basic host discovery and network mapping
  • Speed: Fast (-T4 timing)
  • Ports: Top 1000 ports
  • Scripts: Default scripts only

Port Scan

  • Purpose: Comprehensive port enumeration
  • Speed: Moderate (-T4 timing)
  • Ports: All ports (-p-)
  • Scripts: Default scripts

Service Scan

  • Purpose: Service and version detection
  • Speed: Slower (-T3 timing)
  • Ports: All ports
  • Scripts: Banner and version detection

Vulnerability Scan

  • Purpose: Vulnerability assessment
  • Speed: Slow (-T2 timing)
  • Ports: All ports
  • Scripts: Vulnerability scripts
  • Authorization: Requires explicit authorization

Output Formats

JSON Output

Structured data with all scan information:

{
  "hosts": [
    {
      "addresses": [{"type": "ipv4", "address": "192.168.1.1"}],
      "status": "up",
      "ports": [
        {
          "port": 22,
          "protocol": "tcp",
          "state": "open",
          "service": {
            "name": "ssh",
            "product": "OpenSSH",
            "version": "8.2p1"
          }
        }
      ]
    }
  ],
  "risk_assessment": {
    "overall_risk": "MEDIUM",
    "high_risk_ports": [...],
    "recommendations": [...]
  },
  "ai_analysis": {
    "summary": "Network analysis complete",
    "key_findings": [...],
    "security_concerns": [...]
  }
}

CSV Output

Tabular format for easy analysis:

Host,Port,Protocol,State,Service,Product,Version
192.168.1.1,22,tcp,open,ssh,OpenSSH,8.2p1
192.168.1.1,80,tcp,open,http,nginx,1.18.0

Text Output

Human-readable format:

Nmap Scan Results
==================================================

Host: 192.168.1.1
Status: up
OS: Linux 5.4.0-42-generic
Ports:
  22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2
  80/tcp open http nginx 1.18.0

Security Features

Target Validation

  • IP address format validation
  • Network range validation (CIDR notation)
  • Domain name validation
  • Allowed network range checking

Command Security

  • Command sanitization to prevent injection attacks
  • Blacklisted command patterns
  • Dangerous option detection
  • Shell metacharacter filtering

Authorization Controls

  • Network range restrictions
  • Scan type authorization requirements
  • Rate limiting and timing controls
  • Comprehensive audit logging

Safety Measures

  • Scan timeout protection
  • Process monitoring and cleanup
  • Error handling and recovery
  • Resource usage limits

Testing

Run the test suite:

# Run all tests
python -m unittest discover tests

# Run specific test file
python -m unittest tests.test_config

# Run with coverage
pip install coverage
coverage run -m unittest discover tests
coverage report

Troubleshooting

Common Issues

AI Connection Failed

Error: AI service unavailable

Solution: Ensure Ollama is running and accessible at http://localhost:11434

Nmap Not Found

Error: Command 'nmap' not found

Solution: Install nmap and ensure it's in your PATH

Permission Denied

Error: Permission denied

Solution: Run with appropriate permissions or use sudo for privileged scans

Target Not Allowed

Error: Target not in allowed network ranges

Solution: Update config.yaml to include the target network range

Log Files

  • Application Logs: ./logs/nmap_automation.log
  • CLI Logs: nmap_automation_cli.log
  • Scan Results: ./scan_results/

Debug Mode

Enable debug logging by modifying config.yaml:

logging_configuration:
  level: "DEBUG"

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This tool is provided for educational and authorized security testing purposes only. The authors are not responsible for any misuse or illegal activities. Users must ensure they have proper authorization before scanning any network.

Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review the logs for error details
  3. Ensure all prerequisites are met
  4. Create an issue with detailed information

Remember: Always scan responsibly and only with proper authorization!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages