simple-port-checker 1.1.2
A comprehensive tool for checking firewall ports, L7 protection services, SSL/TLS certificate analysis, and OWASP Top 10 vulnerability scanning
License: MIT
Requires Python: >=3.12
Keywords: certificate, certificate-analysis, firewall, l7-protection, network, pki, port-scanner, security, ssl, tls, waf

# Simple Port Checker   
[![Docker Hub](https://img.shields.io/docker/pulls/htunnthuthu/simple-port-checker)](https://hub.docker.com/r/htunnthuthu/simple-port-checker) [![Docker Image Version](https://img.shields.io/docker/v/htunnthuthu/simple-port-checker?label=docker%20version)](https://hub.docker.com/r/htunnthuthu/simple-port-checker/tags)

[![PyPI - Version](https://img.shields.io/pypi/v/simple-port-checker)](https://pypi.org/project/simple-port-checker/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/simple-port-checker)](https://pypistats.org/packages/simple-port-checker) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/simple-port-checker)](https://pypi.org/project/simple-port-checker/) [![PyPI Stats](https://img.shields.io/badge/PyPI%20Stats-simple--port--checker-blue)](https://pypistats.org/packages/simple-port-checker)

A comprehensive Python tool for checking firewall ports, detecting L7 protection services (WAF, CDN, etc.), testing mTLS authentication, and scanning for OWASP Top 10 2021 vulnerabilities. Available as both a Python package and Docker container.

## Features

- ✅ **Port Scanning**: Check well-known firewall ports and services
- 🛡️ **L7 Protection Detection**: Identify WAF/CDN services (F5, AWS WAF, Azure, Cloudflare, Microsoft HTTPAPI, etc.)
- 🔐 **mTLS Authentication**: Check mutual TLS support and certificate requirements
- 🔒 **SSL/TLS Certificate Analysis**: Comprehensive certificate chain analysis and validation
- 🏛️ **Certificate Authority Identification**: "Who signed my cert?" functionality with trust chain visualization
- ⚠️ **Missing Intermediate Detection**: Identify incomplete certificate chains affecting browser compatibility
- 🔑 **Hybrid Identity Detection**: Check for Azure AD/ADFS integration and federation endpoints
- 🔍 **OWASP Top 10 2021 Scanner**: Automated vulnerability detection with remediation guidance (NEW!)
- 🛡️ **Security Header Analysis**: Grade HTTP security headers (HSTS, CSP, X-Frame-Options, etc.) (NEW!)
- 📄 **Multi-Format Reporting**: Export scan results to PDF, JSON, or CSV with tech-specific remediation (NEW!)
- 🌐 **DNS Trace**: Advanced DNS CNAME chain analysis and IP protection detection
- 🚀 **Async Support**: High-performance concurrent scanning
- 📊 **Rich Output**: Beautiful terminal output with progress bars and certificate analysis tables
- 🔧 **Unified CLI**: All functionality accessible through a single command interface
- 📦 **Pip Installable**: Available on PyPI
- 🐳 **Docker Ready**: Pre-built Docker images on Docker Hub
- 🐍 **Type Hints**: Full type hint support for better IDE integration
- 🏗️ **Production Ready**: Follows Python packaging best practices

## Installation

### From PyPI (recommended)
```bash
pip install simple-port-checker
```

### From Docker Hub

Docker images are available on [Docker Hub](https://hub.docker.com/r/htunnthuthu/simple-port-checker) with automated builds from this repository.

```bash
# Quick start - run directly without installation
docker run --rm htunnthuthu/simple-port-checker:latest google.com 443

# Use specific version
docker run --rm htunnthuthu/simple-port-checker:v0.5.3 example.com --ports 80,443

# Run L7 protection check
docker run --rm htunnthuthu/simple-port-checker:latest l7-check example.com

# Run SSL/TLS certificate analysis
docker run --rm htunnthuthu/simple-port-checker:latest cert-check example.com

# Run full scan with all features
docker run --rm htunnthuthu/simple-port-checker:latest full-scan example.com

# Use latest tag for most recent features
docker pull htunnthuthu/simple-port-checker:latest

# Available tags: latest, v0.5.1, v0.5.0, v0.4.2, v0.4.1, v0.4.0, v0.3.0, and other version tags
```

**Docker Image Features:**
- ✅ **Lightweight**: Based on Alpine Linux for minimal size
- 🔒 **Secure**: Non-root user, minimal dependencies
- 🏷️ **Multi-arch**: Supports AMD64 and ARM64 architectures  
- 🔄 **Auto-updated**: Images built automatically from main branch
- 📋 **Comprehensive**: All CLI features available in container

### From Source
```bash
git clone https://github.com/htunnthuthu/simple-port-checker.git
cd simple-port-checker
pip install -e .
```

## Quick Start

### Command Line Usage

```bash
# Basic port scan
port-checker scan example.com

# Scan specific ports
port-checker scan example.com --ports 80,443,8080

# Check L7 protection
port-checker l7-check example.com

# SSL/TLS Certificate Analysis (NEW!)
port-checker cert-check example.com
port-checker cert-chain github.com  
port-checker cert-info google.com

# DNS trace analysis
port-checker dns-trace example.com

# L7 check with DNS tracing
port-checker l7-check example.com --trace-dns

# Full scan with L7 detection
port-checker full-scan example.com

# OWASP Top 10 2021 Security Scan (NEW!)
port-checker owasp-scan example.com

# Deep scan with active probing and PDF report
port-checker owasp-scan example.com --deep -f pdf -o security-report.pdf

# Scan specific OWASP categories with tech-specific remediation
port-checker owasp-scan example.com -c A02,A05,A06 -t nginx --verbose

# Check for hybrid identity and ADFS (NEW!)
port-checker hybrid-identity example.com

# Scan multiple targets
port-checker scan example.com google.com --output results.json

# Run as Python module
python -m simple_port_checker scan example.com

# Check mTLS support
port-checker mtls-check example.com

# Check mTLS with client certificates
port-checker mtls-check example.com --client-cert client.crt --client-key client.key

# Generate test certificates for mTLS testing
port-checker mtls-gen-cert test-client.example.com

# Validate certificate files
port-checker mtls-validate-cert client.crt client.key

# Check multiple targets for mTLS support
port-checker mtls-check example.com test.example.com --concurrent 5
```

### Docker Usage

```bash
# Basic port scan
docker run --rm htunnthuthu/simple-port-checker:latest scan example.com

# Scan with specific ports
docker run --rm htunnthuthu/simple-port-checker:latest scan example.com --ports 80,443,8080

# L7 protection detection
docker run --rm htunnthuthu/simple-port-checker:latest l7-check example.com --trace-dns

# SSL/TLS Certificate Analysis
docker run --rm htunnthuthu/simple-port-checker:latest cert-check github.com
docker run --rm htunnthuthu/simple-port-checker:latest cert-chain google.com
docker run --rm htunnthuthu/simple-port-checker:latest cert-info example.com

# Full comprehensive scan
docker run --rm htunnthuthu/simple-port-checker:latest full-scan example.com

# mTLS testing
docker run --rm htunnthuthu/simple-port-checker:latest mtls-check example.com

# Save results to host (mount volume)
docker run --rm -v $(pwd):/app/output htunnthuthu/simple-port-checker:latest scan example.com --output /app/output/results.json

# Use specific version
docker run --rm htunnthuthu/simple-port-checker:v0.5.1 scan example.com
```

### Python API Usage

```python
import asyncio
from simple_port_checker import PortChecker, L7Detector, CertificateAnalyzer

# Initialize scanner
scanner = PortChecker()

async def main():
    # Scan ports
    results = await scanner.scan_host("blog.htunnthuthu.tech", ports=[80, 443, 8080])
    print(f"Open ports: {len([p for p in results.ports if p.is_open])}")

    # Detect L7 protection
    detector = L7Detector()
    protection = await detector.detect("blog.htunnthuthu.tech")
    if protection.primary_protection:
        service = protection.primary_protection.service.value
        confidence = protection.primary_protection.confidence
        print(f"L7 Protection: {service} ({confidence:.0%})")
    else:
        print("No L7 protection detected")
    
    # Analyze SSL/TLS certificate
    cert_analyzer = CertificateAnalyzer()
    cert_chain = await cert_analyzer.analyze_certificate_chain("blog.htunnthuthu.tech", 443)
    print(f"Certificate Subject: {cert_chain.server_cert.subject}")
    print(f"Issuer: {cert_chain.server_cert.issuer}")
    print(f"Valid: {cert_chain.server_cert.is_valid_now}")
    print(f"Chain Complete: {cert_chain.chain_complete}")

# Run the async function
asyncio.run(main())
```

### mTLS Authentication Checking

```python
import asyncio
from simple_port_checker import MTLSChecker

async def check_mtls():
    checker = MTLSChecker()
    
    # Basic mTLS support check
    result = await checker.check_mtls("example.com")
    print(f"Supports mTLS: {result.supports_mtls}")
    print(f"Requires client cert: {result.requires_client_cert}")
    
    # Check with client certificates
    result = await checker.check_mtls(
        "example.com", 
        client_cert_path="client.crt",
        client_key_path="client.key"
    )
    print(f"Handshake successful: {result.handshake_successful}")
    
    # Batch check multiple targets
    targets = [("example.com", 443), ("test.com", 8443)]
    results = await checker.batch_check_mtls(targets)
    
    for result in results:
        print(f"{result.target}: mTLS={result.supports_mtls}")

asyncio.run(check_mtls())
```

# Hybrid Identity Detection

## Overview

The Hybrid Identity feature detects Azure AD/ADFS integration and federation endpoints for domains. It uses the same method as Azure Portal to discover ADFS endpoints by querying the Azure AD realm API, making it highly reliable for identifying hybrid identity configurations.

This is essential for:

- **🔍 Security Audits**: Identify federation services and authentication mechanisms
- **📋 Migration Planning**: Assess current identity setup before cloud migrations
- **🛠️ Troubleshooting**: Verify ADFS accessibility and configuration
- **🎯 Identity Discovery**: Discover authentication mechanisms for domains
- **☁️ Cloud Integration**: Understand Azure AD and on-premises integration

## What It Checks

| Check | Description |
|-------|-------------|
| 🎯 **Azure AD Flow** | Queries Azure AD realm API (most reliable method - same as Azure Portal) |
| 🔒 **ADFS Endpoints** | Checks `/adfs/ls` and related paths |
| 📜 **Federation Metadata** | WS-Federation metadata endpoints |
| ☁️ **Azure AD Integration** | Redirects to Microsoft login |
| 🔑 **OpenID Config** | `.well-known/openid-configuration` |
| 🌐 **DNS Records** | Microsoft verification, MX records, ADFS subdomains |

## Command Line Usage

### Basic Hybrid Identity Checking

```bash
# Check single domain for hybrid identity
port-checker hybrid-identity example.com

# Check multiple domains
port-checker hybrid-identity company1.com company2.com company3.com

# From file
port-checker hybrid-identity $(cat domains.txt)

# With verbose output for detailed analysis
port-checker hybrid-identity example.com --verbose

# Save results to JSON
port-checker hybrid-identity example.com --output hybrid-results.json
```

### Advanced Options

```bash
# Custom timeout (useful for slow networks)
port-checker hybrid-identity example.com --timeout 15

# Control concurrency for batch checks
port-checker hybrid-identity domain1.com domain2.com --concurrent 5

# Comprehensive check with all options
port-checker hybrid-identity example.com \
  --verbose \
  --timeout 15 \
  --output results.json
```

### Docker Usage

```bash
# Basic hybrid identity check
docker run --rm htunnthuthu/simple-port-checker:latest hybrid-identity example.com

# Multiple domains with output
docker run --rm -v $(pwd):/app/output \
  htunnthuthu/simple-port-checker:latest \
  hybrid-identity company1.com company2.com \
  --output /app/output/hybrid-results.json \
  --verbose
```

## Python API Usage

```python
import asyncio
from simple_port_checker import HybridIdentityChecker

async def check_hybrid_identity():
    """Basic hybrid identity check."""
    checker = HybridIdentityChecker(timeout=15.0)
    
    # Check single domain
    result = await checker.check("example.com")
    
    print(f"Domain: {result.fqdn}")
    print(f"Hybrid Identity: {'✅ Detected' if result.has_hybrid_identity else '❌ Not Found'}")
    
    if result.has_adfs:
        print(f"\nADFS Configuration:")
        print(f"  Endpoint: {result.adfs_endpoint}")
        print(f"  Status: {result.adfs_status_code}")
    
    if result.federation_metadata_found:
        print("  Federation Metadata: ✅ Found")
    
    if result.azure_ad_detected:
        print("  Azure AD Integration: ✅ Detected")
    
    if result.openid_config_found:
        print("  OpenID Configuration: ✅ Found")
    
    # DNS indicators
    if result.dns_records:
        print(f"\nDNS Records:")
        if 'microsoft_verification' in result.dns_records:
            print("  Microsoft Verification: ✅ Found")
        if 'microsoft_mail' in result.dns_records:
            print("  Microsoft 365 Mail: ✅ Detected")
        if 'adfs_subdomains' in result.dns_records:
            print(f"  ADFS Subdomains: {', '.join(result.dns_records['adfs_subdomains'])}")
    
    print(f"\nResponse Time: {result.response_time:.2f}s")
    
    # Error handling
    if result.error:
        print(f"Error: {result.error}")

async def batch_hybrid_identity_check():
    """Check multiple domains for hybrid identity."""
    checker = HybridIdentityChecker()
    
    domains = [
        "company1.com",
        "company2.com",
        "company3.com",
    ]
    
    print("Checking hybrid identity for multiple domains...\n")
    results = await checker.batch_check(domains, max_concurrent=5)
    
    # Summary statistics
    hybrid_count = sum(1 for r in results if r.has_hybrid_identity)
    adfs_count = sum(1 for r in results if r.has_adfs)
    
    print(f"\nSummary:")
    print(f"  Total Domains: {len(results)}")
    print(f"  Hybrid Identity Found: {hybrid_count}")
    print(f"  ADFS Endpoints Found: {adfs_count}")
    
    # Detailed results
    print(f"\nDetailed Results:")
    for result in results:
        status = "✅" if result.has_hybrid_identity else "❌"
        adfs = f" (ADFS: {result.adfs_endpoint})" if result.adfs_endpoint else ""
        print(f"  {status} {result.fqdn}{adfs}")

async def production_hybrid_identity_check():
    """Production-ready hybrid identity checking with error handling."""
    checker = HybridIdentityChecker(timeout=10.0)
    
    domains = ["example.com", "test.com", "company.com"]
    
    results = []
    for domain in domains:
        try:
            result = await checker.check(domain)
            results.append(result)
            
            if result.error:
                print(f"❌ {domain}: {result.error}")
                continue
            
            if result.has_hybrid_identity:
                print(f"✅ {domain}: Hybrid Identity Detected")
                if result.adfs_endpoint:
                    print(f"   ADFS: {result.adfs_endpoint}")
            else:
                print(f"ℹ️  {domain}: Cloud-only (no hybrid identity)")
                
        except Exception as e:
            print(f"❌ {domain}: Exception - {e}")
    
    return results

# Run examples
asyncio.run(check_hybrid_identity())
asyncio.run(batch_hybrid_identity_check())
asyncio.run(production_hybrid_identity_check())
```

## Key Innovation

**Uses the same method as Azure Portal to discover ADFS endpoints!**

When you login to Azure Portal with `user@domain.com`:
1. Portal checks: `login.microsoftonline.com/common/userrealm/user@domain.com`
2. Gets ADFS endpoint from Azure AD configuration
3. Redirects to that ADFS endpoint

This tool does the **exact same thing** ✨, making it the most reliable method for ADFS discovery.

## Common Results

### Hybrid Identity Found
```
Status: ✅ Hybrid Identity Detected
ADFS Endpoint: ✅ Found
  Endpoint URL: https://adfs.company.com/adfs/ls
  Status Code: 200
Azure AD Integration: ✅ Detected
Federation Metadata: ✅ Found
```

### Cloud-Only (No Hybrid)
```
Status: ⚠️  No Hybrid Identity Found
ADFS Endpoint: ❌ Not Found
Federation Metadata: ❌ Not Found
Azure AD Integration: ❌ Not Detected
```

## Use Cases

1. **Security Audits**: Identify all domains with federation services
2. **Migration Planning**: Assess current identity infrastructure before migrations
3. **Troubleshooting**: Verify ADFS endpoints are accessible
4. **Compliance**: Ensure identity configurations meet requirements
5. **Discovery**: Map out authentication mechanisms across multiple domains

## Related Documentation

- Quick Reference: `HYBRID_IDENTITY_QUICKREF.md`
- Implementation Details: `IMPLEMENTATION_HYBRID_IDENTITY.md`
- Full API Docs: `docs/hybrid-identity.md`
- API Reference: `docs/api.md`

---

# OWASP Top 10 2021 Vulnerability Scanner

## Overview

The OWASP Top 10 2021 vulnerability scanner provides comprehensive security assessment for web applications and APIs. It detects common security vulnerabilities, provides severity-based risk scoring, and offers technology-specific remediation guidance.

This is essential for:

- **🔍 Security Assessments**: Automated detection of OWASP Top 10 2021 vulnerabilities
- **📊 Risk Scoring**: Severity-based grading system (A-F) with automatic critical failure detection
- **🛡️ Security Headers**: Analysis of HTTP security headers (HSTS, CSP, X-Frame-Options, etc.)
- **🔧 Remediation**: Tech-specific fix guidance for Apache, Nginx, IIS, Cloudflare
- **📄 Reporting**: Professional PDF reports, JSON/CSV export for integration
- **🎯 Compliance**: OWASP compliance verification with CWE mapping
- **⚡ Safe Mode**: Passive-only scanning (default) that won't trigger security alerts
- **🚀 Deep Mode**: Active probing for comprehensive vulnerability detection

## What It Scans

### OWASP Top 10 2021 Categories

| Category | Name | Safe Mode | Deep Mode | Detection Method |
|----------|------|-----------|-----------|------------------|
| **A01** | Broken Access Control | ❌ | ✅ | Authorization testing |
| **A02** | Cryptographic Failures | ✅ | ✅ | SSL/TLS analysis, HSTS, cookie flags |
| **A03** | Injection | ❌ | ✅ | Payload testing |
| **A04** | Insecure Design | ❌ | ✅ | Architecture analysis |
| **A05** | Security Misconfiguration | ✅ | ✅ | Header analysis, server disclosure |
| **A06** | Vulnerable Components | ✅ | ✅ | Version detection |
| **A07** | Authentication Failures | ✅ | ✅ | Session management, cookie security |
| **A08** | Software/Data Integrity | ❌ | ✅ | Integrity checks |
| **A09** | Logging/Monitoring | 🚫 | 🚫 | Not externally testable |
| **A10** | Server-Side Request Forgery | ❌ | ✅ | SSRF testing |

### Scan Modes

**🛡️ Safe Mode (Default)**
- Passive-only checks that won't trigger security alerts
- Scans: A02, A05, A06, A07
- Perfect for production environments
- No active probing or payload injection

**🚀 Deep Mode**
- Active vulnerability probing
- Scans: All testable categories (excludes A09)
- Requires explicit authorization
- May trigger security monitoring systems

### Severity Scoring

| Severity | Points | Impact | Auto-Grade |
|----------|--------|--------|------------|
| **CRITICAL** | 15 | Immediate exploitation risk | Auto F-grade for A02 |
| **HIGH** | 10 | Significant security impact | - |
| **MEDIUM** | 5 | Moderate risk | - |
| **LOW** | 1 | Minor issue | - |

**Grading Scale**: A (0-10), B (11-25), C (26-50), D (51-100), F (>100 or critical crypto failures)

## OWASP Scan Workflow

```mermaid
sequenceDiagram
    participant CLI as CLI/API
    participant Scanner as OwaspScanner
    participant Headers as SecurityHeaderChecker
    participant Cert as CertificateAnalyzer
    participant Remediation as RemediationDB
    participant Export as Exporters
    
    CLI->>Scanner: owasp-scan target
    activate Scanner
    
    Note over Scanner: Initialize scan mode<br/>(safe/deep)
    
    Scanner->>Headers: Check security headers
    activate Headers
    Headers-->>Scanner: Header analysis results
    deactivate Headers
    
    Scanner->>Cert: Analyze SSL/TLS
    activate Cert
    Cert-->>Scanner: Certificate chain & grade
    deactivate Cert
    
    Note over Scanner: Run category checks<br/>(A02, A05, A06, A07)
    
    Scanner->>Scanner: Calculate severity scores
    Scanner->>Scanner: Assign grade (A-F)
    
    Scanner->>Remediation: Get tech-specific fixes
    activate Remediation
    Remediation-->>Scanner: Remediation guidance
    deactivate Remediation
    
    Scanner-->>CLI: OwaspScanResult
    deactivate Scanner
    
    CLI->>Export: Format output
    activate Export
    Export-->>CLI: PDF/JSON/CSV report
    deactivate Export
```

## Command Line Usage

### Basic OWASP Scanning

```bash
# Safe mode scan (default - passive only)
simple-port-checker owasp-scan example.com

# Deep scan with active probing (requires authorization)
simple-port-checker owasp-scan example.com --deep

# Scan with verbose output showing all findings
simple-port-checker owasp-scan example.com --verbose

# Quiet mode - grade summary only
simple-port-checker owasp-scan example.com --quiet
```

### Category-Specific Scanning

```bash
# Scan specific OWASP categories
simple-port-checker owasp-scan example.com -c A02,A05,A06

# Scan only cryptographic failures
simple-port-checker owasp-scan example.com -c A02 --verbose

# Custom category set
simple-port-checker owasp-scan example.com -c A02,A05,A07 --deep
```

### Technology-Specific Remediation

```bash
# Get Nginx-specific remediation guidance
simple-port-checker owasp-scan example.com -t nginx --verbose

# Apache server remediation
simple-port-checker owasp-scan example.com -t apache -f pdf -o report.pdf

# IIS server remediation
simple-port-checker owasp-scan example.com -t iis --verbose

# Cloudflare CDN remediation
simple-port-checker owasp-scan example.com -t cloudflare

# Generic remediation (default)
simple-port-checker owasp-scan example.com -t generic
```

### Multi-Format Reporting

```bash
# Console output (default)
simple-port-checker owasp-scan example.com

# Professional PDF report with remediation
simple-port-checker owasp-scan example.com -f pdf -o security-report.pdf

# JSON export for automation/integration
simple-port-checker owasp-scan example.com -f json -o results.json

# CSV for spreadsheet analysis
simple-port-checker owasp-scan example.com -f csv -o findings.csv

# JSON with remediation guidance
simple-port-checker owasp-scan example.com -f json -o results.json -t nginx
```

### Severity Filtering

```bash
# Show only critical findings
simple-port-checker owasp-scan example.com --severity CRITICAL

# High and above
simple-port-checker owasp-scan example.com --severity HIGH --verbose

# Medium and above
simple-port-checker owasp-scan example.com --severity MEDIUM

# All findings (default)
simple-port-checker owasp-scan example.com --verbose
```

### Batch Scanning

```bash
# Scan multiple targets
simple-port-checker owasp-scan site1.com site2.com site3.com

# With deep mode and PDF reports
simple-port-checker owasp-scan api.example.com admin.example.com \
  --deep -f pdf -o batch-report.pdf

# From file
simple-port-checker owasp-scan $(cat targets.txt) --verbose
```

### Advanced Options

```bash
# Custom timeout for slow networks
simple-port-checker owasp-scan example.com --timeout 20

# Complete assessment with all options
simple-port-checker owasp-scan example.com \
  --deep \
  -t nginx \
  -f pdf \
  -o comprehensive-report.pdf \
  --verbose \
  --timeout 15
```

### Docker Usage

```bash
# Basic OWASP scan
docker run --rm htunnthuthu/simple-port-checker:latest \
  owasp-scan example.com

# Deep scan with PDF report (save to host)
docker run --rm -v $(pwd):/app/output \
  htunnthuthu/simple-port-checker:latest \
  owasp-scan example.com \
  --deep -f pdf -o /app/output/security-report.pdf

# Multiple targets with tech-specific remediation
docker run --rm htunnthuthu/simple-port-checker:latest \
  owasp-scan api.example.com admin.example.com \
  -t nginx --verbose
```

## Python API Usage

### Basic OWASP Scanning

```python
import asyncio
from simple_port_checker import OwaspScanner

async def basic_owasp_scan():
    """Perform basic OWASP Top 10 scan."""
    scanner = OwaspScanner(mode="safe", timeout=15.0)
    
    # Scan target
    result = await scanner.scan("example.com", port=443, tech_stack="nginx")
    
    # Display results
    print(f"Target: {result.target}:{result.port}")
    print(f"Overall Grade: {result.overall_grade}")
    print(f"Total Score: {result.total_score}")
    print(f"Scan Mode: {result.scan_mode.value}")
    print(f"Duration: {result.duration:.2f}s")
    
    # Show findings by severity
    if result.critical_findings:
        print(f"\n⚠️  CRITICAL ({len(result.critical_findings)} findings):")
        for finding in result.critical_findings:
            print(f"  [{finding.category}] {finding.title}")
            print(f"  {finding.description}")
    
    if result.high_findings:
        print(f"\n🔴 HIGH ({len(result.high_findings)} findings):")
        for finding in result.high_findings:
            print(f"  [{finding.category}] {finding.title}")
    
    # Category analysis
    for cat_id in ["A02", "A05", "A06", "A07"]:
        cat_result = result.categories.get(cat_id)
        if cat_result and cat_result.scanned:
            print(f"\n{cat_id}: {cat_result.category_name}")
            print(f"  Grade: {cat_result.grade}")
            print(f"  Score: {cat_result.score}")
            print(f"  Findings: {len(cat_result.findings)}")

asyncio.run(basic_owasp_scan())
```

### Deep Scan with Reporting

```python
import asyncio
from simple_port_checker import OwaspScanner
from simple_port_checker.utils import OwaspPdfExporter, export_to_json, export_to_csv

async def comprehensive_owasp_assessment():
    """Complete OWASP assessment with multi-format reporting."""
    # Deep mode scanner
    scanner = OwaspScanner(mode="deep", timeout=15.0)
    
    # Scan target
    result = await scanner.scan(
        "example.com",
        port=443,
        tech_stack="nginx"
    )
    
    print(f"Security Assessment: {result.target}")
    print(f"Grade: {result.overall_grade} ({result.total_score} points)")
    print(f"Total Findings: {len(result.all_findings)}")
    
    # Export to multiple formats
    
    # PDF report with remediation
    pdf_exporter = OwaspPdfExporter()
    pdf_exporter.export(
        result,
        "security-report.pdf",
        tech_stack="nginx",
        include_remediation=True
    )
    print("✓ PDF: security-report.pdf")
    
    # JSON for automation
    export_to_json(
        result,
        "results.json",
        tech_stack="nginx",
        include_remediation=True
    )
    print("✓ JSON: results.json")
    
    # CSV for spreadsheet
    export_to_csv(result, "findings.csv")
    print("✓ CSV: findings.csv")

asyncio.run(comprehensive_owasp_assessment())
```

### Batch Scanning

```python
import asyncio
from simple_port_checker import OwaspScanner

async def batch_owasp_scan():
    """Scan multiple targets for OWASP vulnerabilities."""
    scanner = OwaspScanner(mode="safe")
    
    targets = [
        ("example.com", 443),
        ("api.example.com", 443),
        ("admin.example.com", 443)
    ]
    
    # Batch scan with concurrency control
    batch_result = await scanner.batch_scan(
        targets,
        tech_stack="nginx",
        max_concurrent=3
    )
    
    print(f"Scanned: {batch_result.total_scanned} targets")
    print(f"Failed: {batch_result.failed_count}")
    
    # Summary by grade
    grade_counts = {}
    for result in batch_result.results:
        grade = result.overall_grade
        grade_counts[grade] = grade_counts.get(grade, 0) + 1
    
    print("\nGrade Distribution:")
    for grade in sorted(grade_counts.keys()):
        print(f"  {grade}: {grade_counts[grade]} targets")
    
    # Detailed results
    for result in batch_result.results:
        critical_count = len(result.critical_findings)
        high_count = len(result.high_findings)
        
        status = "⚠️" if critical_count > 0 else "✅" if result.overall_grade in ["A", "B"] else "🔸"
        print(f"\n{status} {result.target}: Grade {result.overall_grade}")
        if critical_count > 0:
            print(f"   CRITICAL: {critical_count} findings")
        if high_count > 0:
            print(f"   HIGH: {high_count} findings")

asyncio.run(batch_owasp_scan())
```

### Category-Specific Scanning

```python
import asyncio
from simple_port_checker import OwaspScanner

async def category_specific_scan():
    """Scan specific OWASP categories only."""
    # Custom categories
    scanner = OwaspScanner(
        enabled_categories=["A02", "A05", "A06"],
        timeout=15.0
    )
    
    result = await scanner.scan("example.com", tech_stack="apache")
    
    print(f"Scanned Categories: {', '.join(result.categories.keys())}")
    
    for cat_id, cat_result in result.categories.items():
        if cat_result.scanned:
            print(f"\n{cat_id}: {cat_result.category_name}")
            print(f"  Grade: {cat_result.grade}")
            print(f"  Findings: {len(cat_result.findings)}")
            
            for finding in cat_result.findings:
                print(f"    - [{finding.severity.value}] {finding.title}")

asyncio.run(category_specific_scan())
```

### Accessing Remediation

```python
import asyncio
from simple_port_checker import OwaspScanner
from simple_port_checker.utils import get_remediation

async def scan_with_remediation():
    """Scan and access remediation guidance."""
    scanner = OwaspScanner(mode="safe")
    result = await scanner.scan("example.com", tech_stack="nginx")
    
    # Get remediation for each finding
    for finding in result.all_findings:
        print(f"\n[{finding.severity.value}] {finding.category}: {finding.title}")
        print(f"Evidence: {finding.evidence}")
        
        # Get tech-specific remediation
        remediation = get_remediation(finding.category, tech_stack="nginx")
        
        if remediation:
            print(f"\nRemediation:")
            print(f"  Description: {remediation.description}")
            
            print(f"\n  Steps:")
            for i, step in enumerate(remediation.steps, 1):
                print(f"    {i}. {step}")
            
            # Tech-specific code example
            if "nginx" in remediation.code_examples:
                print(f"\n  Nginx Configuration:")
                print(f"    {remediation.code_examples['nginx']}")
            
            print(f"\n  References:")
            for ref in remediation.references:
                print(f"    - {ref}")

asyncio.run(scan_with_remediation())
```

## Output Examples

### Console Output (Verbose)

```
╭───────────────────── Security Scan Report ──────────────────────╮
│ OWASP Top 10 2021 Security Assessment                           │
│ Target: https://example.com                                     │
│ Scan Mode: SAFE                                                 │
│ Duration: 2.35s                                                 │
╰─────────────────────────────────────────────────────────────────╯

Overall Security Grade: D
Total Score: 46
Total Findings: 7

A02: Cryptographic Failures
Grade: B
   [HIGH] Missing HSTS Header
   Evidence: Strict-Transport-Security header not found

A05: Security Misconfiguration
Grade: D
   [HIGH] Missing Content-Security-Policy Header
   Evidence: Content-Security-Policy header not found
   
   [MEDIUM] Missing X-Frame-Options Header
   Evidence: X-Frame-Options header not found
   
   [LOW] Information Disclosure via Server Header
   Evidence: Server: cloudflare
```

### PDF Report Contents

- **Cover Page**: Overall grade, scan metadata
- **Executive Summary**: Findings breakdown by severity
- **Category Analysis**: Detailed results per OWASP category
- **Findings**: Title, description, evidence, severity, CWE IDs
- **Remediation**: Tech-specific code examples and steps
- **References**: OWASP documentation links

## Use Cases

1. **Security Assessments**: Automated OWASP Top 10 compliance checking
2. **DevSecOps Integration**: CI/CD pipeline security gates
3. **Compliance Reporting**: Generate professional security reports
4. **Penetration Testing**: Initial reconnaissance and vulnerability discovery
5. **Bug Bounty**: Automated finding discovery and documentation
6. **Security Training**: Learn OWASP vulnerabilities hands-on

## Related Documentation

- Comprehensive Guide: `docs/owasp-scanner.md`
- API Examples: `examples/owasp_scan_examples.py`
- API Reference: `docs/api.md` (OWASP section)
- Remediation Database: `src/simple_port_checker/utils/owasp_remediation.py`

---

# mTLS Authentication Checking

## Overview

The mTLS (Mutual TLS) feature provides comprehensive testing and validation of mutual TLS authentication configurations. This is essential for:

- **🔒 Zero Trust Security**: Verify mutual authentication in zero-trust architectures
- **📋 Compliance Audits**: Ensure mTLS requirements are properly implemented
- **🛡️ API Security**: Test client certificate authentication for APIs
- **🔍 Security Assessments**: Identify services requiring mutual authentication
- **📊 Certificate Management**: Analyze and validate certificate configurations

## mTLS Command Line Usage

### Basic mTLS Checking

```bash
# Check if a service supports mTLS
port-checker mtls-check api.example.com

# Check mTLS on custom port
port-checker mtls-check api.example.com --port 8443

# Check with verbose output for detailed information
port-checker mtls-check api.example.com --verbose

# Check multiple targets concurrently
port-checker mtls-check api1.example.com api2.example.com --concurrent 10

# Save results to JSON
port-checker mtls-check api.example.com --output mtls-results.json
```

### Client Certificate Authentication

```bash
# Generate test certificates for mTLS testing
port-checker mtls-gen-cert client.example.com
# Creates: client.crt and client.key

# Validate certificate and key files
port-checker mtls-validate-cert client.crt client.key

# Test mTLS with client certificates
port-checker mtls-check api.example.com \
  --client-cert client.crt \
  --client-key client.key

# Test with custom CA bundle
port-checker mtls-check api.example.com \
  --client-cert client.crt \
  --client-key client.key \
  --ca-bundle /path/to/ca-bundle.pem
```

### Advanced Options

```bash
# Disable SSL verification (for testing)
port-checker mtls-check internal-api.company.com --no-verify

# Custom timeout and concurrency
port-checker mtls-check api.example.com \
  --timeout 30 \
  --concurrent 5

# Batch check with different configurations
port-checker mtls-check \
  api1.example.com:443 \
  api2.example.com:8443 \
  internal.example.com:9443 \
  --client-cert client.crt \
  --client-key client.key \
  --verbose \
  --output comprehensive-mtls-audit.json
```

## mTLS Python API Usage

```python
import asyncio
from simple_port_checker import MTLSChecker

async def basic_mtls_check():
    """Basic mTLS support checking."""
    checker = MTLSChecker(timeout=10)
    
    # Check single target
    result = await checker.check_mtls("api.example.com")
    
    print(f"Target: {result.target}:{result.port}")
    print(f"Supports mTLS: {result.supports_mtls}")
    print(f"Requires client cert: {result.requires_client_cert}")
    print(f"Handshake successful: {result.handshake_successful}")
    
    if result.server_cert_info:
        cert = result.server_cert_info
        print(f"Server cert: {cert.subject}")
        print(f"Valid until: {cert.not_valid_after}")

async def mtls_with_client_certs():
    """mTLS testing with client certificates."""
    checker = MTLSChecker()
    
    # Test with client certificates
    result = await checker.check_mtls(
        "api.example.com",
        client_cert_path="client.crt",
        client_key_path="client.key"
    )
    
    print(f"mTLS handshake: {'✓' if result.handshake_successful else '✗'}")
    print(f"TLS version: {result.tls_version}")
    print(f"Cipher suite: {result.cipher_suite}")

async def batch_mtls_check():
    """Batch mTLS checking with progress tracking."""
    checker = MTLSChecker()
    
    targets = [
        "api1.example.com",
        "api2.example.com", 
        ("internal-api.company.com", 8443)
    ]
    
    def progress_callback(completed, total, result):
        print(f"Progress: {completed}/{total} - {result.target}: {result.supports_mtls}")
    
    results = await checker.batch_check_mtls(
        targets,
        max_concurrent=5,
        progress_callback=progress_callback
    )
    
    # Analyze results
    mtls_supported = sum(1 for r in results if r.supports_mtls)
    print(f"mTLS supported: {mtls_supported}/{len(results)} targets")

async def production_mtls_audit():
    """Production-ready mTLS audit with comprehensive error handling."""
    checker = MTLSChecker(
        timeout=15,
        max_retries=2,
        retry_delay=1.0,
        enable_logging=True
    )
    
    targets = [
        "api.example.com",
        "secure-api.example.com",
        "internal-api.company.com"
    ]
    
    results = []
    for target in targets:
        try:
            result = await checker.check_mtls(target)
            results.append(result)
            
            # Log important findings
            if result.requires_client_cert:
                print(f"⚠️  {target} REQUIRES client certificates")
            elif result.supports_mtls:
                print(f"ℹ️  {target} supports mTLS (optional)")
            else:
                print(f"ℹ️  {target} no mTLS support")
                
        except Exception as e:
            print(f"❌ Error checking {target}: {e}")
    
    # Get performance metrics
    metrics = checker.get_metrics()
    print(f"\nMetrics: {metrics['successful_connections']}/{metrics['total_requests']} successful")
    print(f"Average time: {metrics['total_time']/metrics['total_requests']:.3f}s")

# Run examples
asyncio.run(basic_mtls_check())
asyncio.run(mtls_with_client_certs())
asyncio.run(batch_mtls_check())
asyncio.run(production_mtls_audit())
```

## Architecture & Flow

The following sequence diagram illustrates the end-to-end flow of Simple Port Checker:

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant PortChecker
    participant L7Detector
    participant Target as Target Host
    participant DNS
    participant HTTP as HTTP/HTTPS
    
    %% Port Scanning Flow
    rect rgb(200, 255, 200)
        Note over User, HTTP: Port Scanning Phase
        User->>+CLI: port-checker scan target.com
        CLI->>+PortChecker: scan_host(target.com, ports)
        
        PortChecker->>+DNS: Resolve hostname
        DNS-->>-PortChecker: IP address
        
        par Port 80
            PortChecker->>+Target: TCP Connect :80
            Target-->>-PortChecker: Connection response
        and Port 443  
            PortChecker->>+Target: TCP Connect :443
            Target-->>-PortChecker: Connection response
        and Port 22
            PortChecker->>+Target: TCP Connect :22
            Target-->>-PortChecker: Connection response
        end
        
        PortChecker->>+Target: Banner grabbing
        Target-->>-PortChecker: Service banners
        
        PortChecker-->>-CLI: ScanResult
        CLI-->>-User: Rich formatted output
    end
    
    %% L7 Protection Detection Flow  
    rect rgb(200, 200, 255)
        Note over User, HTTP: L7 Protection Detection Phase
        User->>+CLI: port-checker l7-check target.com
        CLI->>+L7Detector: detect(target.com)
        
        L7Detector->>+HTTP: HTTPS Request
        HTTP-->>-L7Detector: Response + Headers
        
        L7Detector->>L7Detector: Analyze Headers<br/>(CF-