Website Security Checker Tool

<#
.SYNOPSIS
Website Security Checker Tool

.DESCRIPTION
This script analyzes a website for various security aspects and provides a report.

.NOTES
File Name      : WebsiteSecurityChecker.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, Internet connectivity
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\WebsiteSecurityChecker.ps1
#>

# Import required modules
Add-Type -AssemblyName System.Net.Http

# Global variables
$script:reportPath = "$env:USERPROFILE\Desktop\Website_Security_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
$script:httpClient = New-Object System.Net.Http.HttpClient

function Show-Menu {
    Clear-Host
    Write-Host "=== Website Security Checker Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze Website"
    Write-Host "2. View Last Report"
    Write-Host "3. Exit"
}

function Analyze-Website {
    $url = Read-Host "Enter the website URL to analyze (include http:// or https://)"
    
    if (-not ($url -match "^https?://")) {
        Write-Host "Invalid URL. Please include http:// or https://" -ForegroundColor Red
        return
    }

    Write-Host "`nAnalyzing $url..." -ForegroundColor Yellow

    try {
        $results = @{
            URL = $url
            SSLImplementation = Check-SSLImplementation $url
            HTTPSRedirect = Check-HTTPSRedirect $url
            SecurityHeaders = Check-SecurityHeaders $url
            ContentSecurityPolicy = Check-ContentSecurityPolicy $url
            XFrameOptions = Check-XFrameOptions $url
            XSSProtection = Check-XSSProtection $url
            HSTS = Check-HSTS $url
            ServerInformation = Check-ServerInformation $url
            Cookies = Check-Cookies $url
            OpenPorts = Check-OpenPorts $url
        }

        Generate-Report $results
    }
    catch {
        Write-Host "Error analyzing website: $_" -ForegroundColor Red
    }
}

function Check-SSLImplementation($url) {
    if ($url.StartsWith("https://")) {
        try {
            $request = [System.Net.WebRequest]::Create($url)
            $request.AllowAutoRedirect = $false
            $response = $request.GetResponse()
            $cert = $response.GetResponseStream().GetType().GetField("m_HttpResponseStream", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance).GetValue($response.GetResponseStream()).GetType().GetField("m_Socket", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance).GetValue($response.GetResponseStream().GetType().GetField("m_HttpResponseStream", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance).GetValue($response.GetResponseStream())).RemoteCertificate

            return @{
                Implemented = $true
                Issuer = $cert.Issuer
                ExpirationDate = $cert.GetExpirationDateString()
                Protocol = $response.ProtocolVersion
            }
        }
        catch {
            return @{
                Implemented = $false
                Error = $_.Exception.Message
            }
        }
        finally {
            if ($response) { $response.Close() }
        }
    }
    else {
        return @{
            Implemented = $false
            Error = "Not using HTTPS"
        }
    }
}

function Check-HTTPSRedirect($url) {
    if ($url.StartsWith("http://")) {
        try {
            $request = [System.Net.WebRequest]::Create($url)
            $request.AllowAutoRedirect = $false
            $response = $request.GetResponse()
            $statusCode = [int]$response.StatusCode
            $location = $response.GetResponseHeader("Location")

            return @{
                Redirects = ($statusCode -ge 300 -and $statusCode -lt 400)
                StatusCode = $statusCode
                Location = $location
            }
        }
        catch {
            return @{
                Redirects = $false
                Error = $_.Exception.Message
            }
        }
        finally {
            if ($response) { $response.Close() }
        }
    }
    else {
        return @{
            Redirects = "N/A (Already using HTTPS)"
        }
    }
}

function Check-SecurityHeaders($url) {
    try {
        $response = $script:httpClient.GetAsync($url).Result
        $headers = $response.Headers
        return @{
            "X-Content-Type-Options" = $headers.GetValues("X-Content-Type-Options")
            "X-XSS-Protection" = $headers.GetValues("X-XSS-Protection")
            "X-Frame-Options" = $headers.GetValues("X-Frame-Options")
            "Strict-Transport-Security" = $headers.GetValues("Strict-Transport-Security")
            "Content-Security-Policy" = $headers.GetValues("Content-Security-Policy")
            "Referrer-Policy" = $headers.GetValues("Referrer-Policy")
        }
    }
    catch {
        return @{
            Error = $_.Exception.Message
        }
    }
}

function Check-ContentSecurityPolicy($url) {
    $headers = Check-SecurityHeaders $url
    return $headers."Content-Security-Policy"
}

function Check-XFrameOptions($url) {
    $headers = Check-SecurityHeaders $url
    return $headers."X-Frame-Options"
}

function Check-XSSProtection($url) {
    $headers = Check-SecurityHeaders $url
    return $headers."X-XSS-Protection"
}

function Check-HSTS($url) {
    $headers = Check-SecurityHeaders $url
    return $headers."Strict-Transport-Security"
}

function Check-ServerInformation($url) {
    try {
        $response = $script:httpClient.GetAsync($url).Result
        return $response.Headers.GetValues("Server")
    }
    catch {
        return "Unable to retrieve server information"
    }
}

function Check-Cookies($url) {
    try {
        $response = $script:httpClient.GetAsync($url).Result
        $cookies = $response.Headers.GetValues("Set-Cookie")
        $secureCookies = $cookies | Where-Object { $_ -match "Secure" }
        $httpOnlyCookies = $cookies | Where-Object { $_ -match "HttpOnly" }
        return @{
            TotalCookies = $cookies.Count
            SecureCookies = $secureCookies.Count
            HttpOnlyCookies = $httpOnlyCookies.Count
        }
    }
    catch {
        return @{
            Error = $_.Exception.Message
        }
    }
}

function Check-OpenPorts($url) {
    $uri = [System.Uri]$url
    $hostname = $uri.Host
    $commonPorts = @(80, 443, 8080, 8443)
    $openPorts = @()

    foreach ($port in $commonPorts) {
        try {
            $tcpClient = New-Object System.Net.Sockets.TcpClient
            $connect = $tcpClient.BeginConnect($hostname, $port, $null, $null)
            $wait = $connect.AsyncWaitHandle.WaitOne(1000, $false)
            if ($wait) {
                $tcpClient.EndConnect($connect)
                $openPorts += $port
            }
        }
        catch {}
        finally {
            if ($tcpClient -ne $null) { $tcpClient.Close() }
        }
    }

    return $openPorts
}

function Generate-Report($results) {
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website Security Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
        h1, h2 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .good { color: green; }
        .warning { color: orange; }
        .bad { color: red; }
    </style>
</head>
<body>
    <h1>Website Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>URL: $($results.URL)</p>

    <h2>SSL Implementation</h2>
    <table>
        <tr><th>Implemented</th><td>$(if ($results.SSLImplementation.Implemented) { "<span class='good'>Yes</span>" } else { "<span class='bad'>No</span>" })</td></tr>
        <tr><th>Issuer</th><td>$($results.SSLImplementation.Issuer)</td></tr>
        <tr><th>Expiration Date</th><td>$($results.SSLImplementation.ExpirationDate)</td></tr>
        <tr><th>Protocol</th><td>$($results.SSLImplementation.Protocol)</td></tr>
    </table>

    <h2>HTTPS Redirect</h2>
    <table>
        <tr><th>Redirects to HTTPS</th><td>$(if ($results.HTTPSRedirect.Redirects -eq $true) { "<span class='good'>Yes</span>" } elseif ($results.HTTPSRedirect.Redirects -eq $false) { "<span class='bad'>No</span>" } else { $results.HTTPSRedirect.Redirects })</td></tr>
        <tr><th>Status Code</th><td>$($results.HTTPSRedirect.StatusCode)</td></tr>
        <tr><th>Redirect Location</th><td>$($results.HTTPSRedirect.Location)</td></tr>
    </table>

    <h2>Security Headers</h2>
    <table>
        <tr><th>X-Content-Type-Options</th><td>$(if ($results.SecurityHeaders."X-Content-Type-Options") { "<span class='good'>$($results.SecurityHeaders."X-Content-Type-Options")</span>" } else { "<span class='bad'>Not Set</span>" })</td></tr>
        <tr><th>X-XSS-Protection</th><td>$(if ($results.SecurityHeaders."X-XSS-Protection") { "<span class='good'>$($results.SecurityHeaders."X-XSS-Protection")</span>" } else { "<span class='bad'>Not Set</span>" })</td></tr>
        <tr><th>X-Frame-Options</th><td>$(if ($results.SecurityHeaders."X-Frame-Options") { "<span class='good'>$($results.SecurityHeaders."X-Frame-Options")</span>" } else { "<span class='bad'>Not Set</span>" })</td></tr>
        <tr><th>Strict-Transport-Security</th><td>$(if ($results.SecurityHeaders."Strict-Transport-Security") { "<span class='good'>$($results.SecurityHeaders."Strict-Transport-Security")</span>" } else { "<span class='bad'>Not Set</span>" })</td></tr>
        <tr><th>Content-Security-Policy</th><td>$(if ($results.SecurityHeaders."Content-Security-Policy") { "<span class='good'>Set</span>" } else { "<span class='warning'>Not Set</span>" })</td></tr>
        <tr><th>Referrer-Policy</th><td>$(if ($results.SecurityHeaders."Referrer-Policy") { "<span class='good'>$($results.SecurityHeaders."Referrer-Policy")</span>" } else { "<span class='warning'>Not Set</span>" })</td></tr>
    </table>

    <h2>Server Information</h2>
    <p>$($results.ServerInformation)</p>

    <h2>Cookies</h2>
    <table>
        <tr><th>Total Cookies</th><td>$($results.Cookies.TotalCookies)</td></tr>
        <tr><th>Secure Cookies</th><td>$($results.Cookies.SecureCookies)</td></tr>
        <tr><th>HttpOnly Cookies</th><td>$($results.Cookies.HttpOnlyCookies)</td></tr>
    </table>

    <h2>Open Ports</h2>
    <p>$($results.OpenPorts -join ", ")</p>

    <h2>Recommendations</h2>
    <ul>
        $(if (-not $results.SSLImplementation.Implemented) { "<li class='bad'>Implement SSL/TLS to secure communications.</li>" })
        $(if ($results.HTTPSRedirect.Redirects -eq $false) { "<li class='warning'>Implement HTTPS redirect for all HTTP traffic.</li>" })
        $(if (-not $results.SecurityHeaders."X-Content-Type-Options") { "<li class='warning'>Set X-Content-Type-Options header to prevent MIME type sniffing.</li>" })
        $(if (-not $results.SecurityHeaders."X-XSS-Protection") { "<li class='warning'>Set X-XSS-Protection header to enable browser's XSS filter.</li>" })
        $(if (-not $results.SecurityHeaders."X-Frame-Options") { "<li class='warning'>Set X-Frame-Options header to prevent clickjacking attacks.</li>" })
        $(if (-not $results.SecurityHeaders."Strict-Transport-Security") { "<li class='warning'>Implement HTTP Strict Transport Security (HSTS) to enforce HTTPS connections.</li>" })
        $(if (-not $results.SecurityHeaders."Content-Security-Policy") { "<li class='warning'>Implement Content Security Policy to prevent XSS and data injection attacks.</li>" })
        $(if ($results.Cookies.TotalCookies -gt $results.Cookies.SecureCookies) { "<li class='warning'>Ensure all cookies are set with the Secure flag.</li>" })
        $(if ($results.Cookies.TotalCookies -gt $results.Cookies.HttpOnlyCookies) { "<li class='warning'>Ensure all cookies are set with the HttpOnly flag.</li>" })
        $(if ($results.OpenPorts.Count -gt 2) { "<li class='warning'>Consider closing unnecessary open ports to reduce attack surface.</li>" })
    </ul>
</body>
</html>
"@

    $reportContent | Out-File -FilePath $script:reportPath
    Write-Host "Report generated and saved to: $script:reportPath" -ForegroundColor Green
}

function View-LastReport {
    if (Test-Path $script:reportPath) {
        Start-Process $script:reportPath
    } else {
        Write-Host "No report found. Please analyze a website first." -ForegroundColor Yellow
    }
}

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-3)"

    switch ($choice) {
        "1" { Analyze-Website }
        "2" { View-LastReport }
        "3" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "3") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "3")

# Cleanup
$script:httpClient.Dispose()

This Website Security Checker Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various security aspects of a website:
    • SSL/TLS implementation
    • HTTPS redirect
    • Security headers (X-Content-Type-Options, X-XSS-Protection, X-Frame-Options, etc.)
    • Content Security Policy
    • HTTP Strict Transport Security (HSTS)
    • Server information disclosure
    • Cookie security (Secure and HttpOnly flags)
    • Open ports check
  3. A report generation function that creates an HTML report with the analysis results and recommendations.
  4. Option to view the last generated report.

Key features:

  • Analyzes important website security elements
  • Provides a visual HTML report with color-coded results and recommendations
  • Checks for proper SSL/TLS implementation and HTTPS usage
  • Analyzes security headers and their configurations
  • Examines cookie security settings
  • Performs a basic open ports check
  • Offers suggestions for improving website security based on best practices

This tool is particularly useful for:

  • Website owners who want to perform a basic security check
  • Web developers ensuring they’ve implemented basic security best practices
  • IT security professionals performing initial security assessments
  • Anyone learning about web security and wanting to analyze real websites

To use this script effectively:

  1. Run the script in PowerShell
  2. Choose to analyze a website by entering its URL
  3. Review the generated HTML report
  4. Use the recommendations to improve the website’s security

Please note that this is a basic security checker and doesn’t cover all aspects of web security. For a comprehensive security analysis, you would need to consider many more factors and potentially use more advanced tools and techniques. However, this script provides a good starting point for identifying common security issues and misconfigurations.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *