Tests¶
Package Tests provides security test implementations for HTTP response analysis. This file contains the CSP (Content Security Policy) test that analyzes Content-Security-Policy header configuration to assess protection against XSS, data injection, and other web vulnerabilities.
Package Tests provides security test implementations for HTTP response analysis. This file contains the Cookie Security test that analyzes Set-Cookie headers for security best practices including HttpOnly, Secure, SameSite attributes, expiration times, and potential session fixation vulnerabilities.
Package Tests provides security test implementations for HTTP response analysis. This file contains the Cross-Origin security headers test that analyzes Cross-Origin-Embedder-Policy (COEP), Cross-Origin-Resource-Policy (CORP), and Cross-Origin-Opener-Policy (COOP) headers to assess protection against cross-origin attacks and isolation vulnerabilities.
Package Tests provides security test implementations for HTTP response analysis. This file contains the HSTS (HTTP Strict Transport Security) test that checks for proper HSTS header configuration to prevent protocol downgrade attacks.
Package Tests provides security testing functionality for Engine-AntiGinx.
HTTPSTest Module¶
This module implements HTTPS protocol verification to ensure secure communication channels. It validates whether websites enforce encrypted HTTPS connections instead of insecure HTTP, which is critical for protecting data in transit.
Security Importance:
HTTPS (HTTP Secure) uses TLS/SSL encryption to:
- Encrypt data transmission preventing eavesdropping
- Authenticate the server preventing man-in-the-middle attacks
- Ensure data integrity preventing tampering
- Meet compliance requirements (PCI DSS, GDPR, HIPAA)
HTTP vs HTTPS:
HTTP: No encryption, data sent in plaintext → High threat
HTTPS: TLS/SSL encryption, secure transmission → No threat
Threat Assessment:
- ThreatLevel.None: Website uses HTTPS with proper encryption
- ThreatLevel.High: Website uses HTTP exposing data to interception
This test is typically the first security check performed as it validates the fundamental security posture of a web application.
Integration:
This test is registered in the test registry and executed by the job runner during security scanning operations.
Package Tests provides security test implementations for HTTP response analysis. This file contains the JavaScript Obfuscation test that detects obfuscated JavaScript code which may indicate malicious activity, code hiding, or security evasion techniques.
Package Tests provides security test implementations for HTTP response analysis. This file contains the Permissions-Policy test that checks for proper browser feature access control configuration to prevent abuse of sensitive browser APIs.
Package Tests provides security test implementations for HTTP response analysis. This file contains the Referrer-Policy test that checks for proper referrer information control configuration to prevent information leakage and protect user privacy.
Package Tests provides security test implementations for HTTP response analysis. This file contains the SSLCertificateSecurityTest that analyzes the SSL/TLS certificate of the target website for security best practices, such as validity, expiration, and use of strong cryptographic algorithms.
Package Tests provides security testing functionality for Engine-AntiGinx.
ServerHeaderTest Module¶
This module analyzes HTTP response headers to identify information disclosure vulnerabilities where servers expose technology stack details. Such exposure provides attackers with reconnaissance data useful for targeted attacks.
Security Context:
Information disclosure through HTTP headers violates the principle of security through obscurity and assists attackers in:
- Identifying specific software versions with known vulnerabilities
- Crafting targeted exploits for detected technologies
- Mapping the technology stack for attack surface analysis
- Accelerating reconnaissance phases of security assessments
Analyzed Headers:
- Server: Web server type and version (Apache, Nginx, IIS)
- X-Powered-By: Application framework (PHP, Express, Django)
- X-AspNet-Version: ASP.NET framework version
- X-AspNetMvc-Version: ASP.NET MVC version
- X-Framework: Custom framework identifiers
- X-Generator: Content management systems (WordPress, Drupal)
- X-Drupal-Cache: Drupal CMS indicator
- X-Mod-Pagespeed: Google PageSpeed module
- X-Varnish: Varnish Cache presence
- X-Served-By: CDN or hosting service information
- X-Cache: Caching layer details
- X-Runtime: Application runtime information
CVE Integration:
This test integrates with the NIST NVD (National Vulnerability Database) to:
- Query known vulnerabilities for detected technologies
- Assess severity based on CVSS scores
- Elevate threat levels when high-severity CVEs exist
- Provide contextual vulnerability intelligence
Threat Assessment Algorithm:
Base Level (by exposure count):
0 exposures → None
1-2 exposures → Info
3-4 exposures → Low
5+ exposures → Medium
CVE Enhancement:
High severity CVE present → Critical
6+ medium severity CVEs → High
1-5 medium severity CVEs → Medium
11+ low severity CVEs → Medium
1-10 low severity CVEs → Low
Heuristic Enhancement:
Debug/test/dev identifiers → Critical
Common web servers exposed → High
Best Practices:
To mitigate information disclosure:
- Remove or customize Server headers
- Disable X-Powered-By and version headers
- Use reverse proxies to normalize header output
- Implement header security policies
- Regular security audits of exposed headers
Package Tests provides the core testing framework for security analysis of HTTP responses. This file defines fundamental types including ThreatLevel enumeration, TestResult structure, and the ResponseTest interface that all security tests must implement.
The framework enables:
- Standardized security threat classification (None to Critical)
- Structured test results with metadata
- Extensible test implementations
- JSON serialization for reporting
Package Tests provides security test implementations for HTTP response analysis. This file contains the X-Content-Type-Options test that checks for proper MIME type sniffing protection to prevent content-type confusion attacks.
Package Tests provides security test implementations for HTTP response analysis. This file contains the X-Frame-Options test that checks for proper clickjacking protection by analyzing X-Frame-Options and Content-Security-Policy frame directives.
Index¶
- Variables
- func aggregateSecurityIssues(analysis *CookieSecurityAnalysis)
- func analyzeCrossOriginHeaders(coepHeader, corpHeader, coopHeader string) map[string]interface{}
- func analyzeDirectiveSecurity(analysis *CSPAnalysis)
- func analyzeHSTSHeader(hstsHeader string) map[string]interface{}
- func analyzeIndividualCookieSecurity(detail *CookieSecurityDetail, cookie *http.Cookie, headers []string, index int)
- func analyzePermissionsPolicyHeader(permissionsPolicyHeader string) map[string]interface{}
- func analyzeReferrerPolicyHeader(referrerPolicyHeader string) map[string]interface{}
- func analyzeXContentTypeOptionsHeader(xContentTypeHeader string) map[string]interface{}
- func assessEmbeddingCapability(xframeDirective, cspFrameValue string, xframeValid bool) string
- func calculateCookieSecurityScore(analysis *CookieSecurityAnalysis)
- func calculateIndividualCookieScore(detail CookieSecurityDetail) int
- func calculateObfuscationScore(analysis *JSObfuscationAnalysis)
- func calculatePolicyStrength(analysis *CSPAnalysis)
- func checkMissingDirectives(analysis *CSPAnalysis)
- func containsHash(values []string) bool
- func containsNonce(values []string) bool
- func detectBase64Encoding(analysis *JSObfuscationAnalysis, content string)
- func detectCharCodeObfuscation(analysis *JSObfuscationAnalysis, content string)
- func detectDynamicExecution(analysis *JSObfuscationAnalysis, content string)
- func detectEncodedStrings(analysis *JSObfuscationAnalysis, content string)
- func detectEscapeSequences(analysis *JSObfuscationAnalysis, content string)
- func detectMaliciousIndicators(analysis *JSObfuscationAnalysis, content string)
- func detectSuspiciousPatterns(analysis *JSObfuscationAnalysis, content string)
- func detectTechnologies(headerName string, headerValue string) map[string]string
- func determineCSPProtectionLevel(analysis *CSPAnalysis)
- func determineObfuscationLevel(analysis *JSObfuscationAnalysis)
- func determineProtectionLevel(xframeDirective, cspFrameValue string, xframeValid bool) string
- func evaluateDirectiveCompliance(analysis *CSPAnalysis, directiveName string, values []string)
- func extractFrameAncestorsValue(cspHeader string) string
- func extractMaxAge(hstsHeader string) int
- func extractScriptContent(html string) []string
- func extractVersion(headerValue, technology string) string
- func formatDuration(d time.Duration) string
- func formatMaxAge(seconds int) string
- func generateCSPDescription(analysis CSPAnalysis) string
- func generateCookieDescription(analysis CookieSecurityAnalysis) string
- func generateCrossOriginDescription(metadata map[string]interface{}) string
- func generateDescription(protectionLevel string, hasXFrame, hasCSP bool, canBeEmbedded string) string
- func generateHSTSDescription(metadata map[string]interface{}) string
- func generateObfuscationDescription(analysis JSObfuscationAnalysis) string
- func generatePermissionsPolicyDescription(metadata map[string]interface{}) string
- func generateReferrerPolicyDescription(metadata map[string]interface{}) string
- func generateServerExposureDescription(analysis *ServerHeaderAnalysis) string
- func generateXContentTypeOptionsDescription(metadata map[string]interface{}) string
- func getSameSiteString(sameSite http.SameSite) string
- func hasOnlyBroadSources(cspLower string) bool
- func hasSpecificDomains(cspLower string) bool
- func isAllowlistRestricted(allowlist string) bool
- func isPredictableValue(value string) bool
- func isSessionCookie(cookie *http.Cookie) bool
- type CSPAnalysis
- func analyzeCSPHeader(cspHeader string) CSPAnalysis
- type CookieSecurityAnalysis
- func analyzeCookieSecurity(cookies []*http.Cookie, headers http.Header) CookieSecurityAnalysis
- type CookieSecurityDetail
- func analyzeSingleCookie(cookie *http.Cookie, setCookieHeaders []string, index int) CookieSecurityDetail
- type CrossOriginAnalysis
- type JSObfuscationAnalysis
- func analyzeJSObfuscation(content string) JSObfuscationAnalysis
- type ResponseTest
- func NewCSPTest() *ResponseTest
- func NewCookieSecurityTest() *ResponseTest
- func NewCrossOriginTest() *ResponseTest
- func NewHSTSTest() *ResponseTest
- func NewHTTPSTest() *ResponseTest
- func NewJSObfuscationTest() *ResponseTest
- func NewPermissionsPolicyTest() *ResponseTest
- func NewReferrerPolicyTest() *ResponseTest
- func NewSSLCertificateSecurityTest() *ResponseTest
- func NewServerHeaderTest() *ResponseTest
- func NewXContentTypeOptionsTest() *ResponseTest
- func NewXFrameTest() *ResponseTest
- func (brt *ResponseTest) GetDescription() string
- func (brt *ResponseTest) GetId() string
- func (brt *ResponseTest) GetName() string
- func (rt *ResponseTest) Run(params ResponseTestParams) TestResult
- type ResponseTestParams
- type ServerHeaderAnalysis
- func analyzeServerHeaders(headers map[string]string) *ServerHeaderAnalysis
- type TestResult
- type TestResultWrapper
- type ThreatLevel
- func evaluateCSPThreatLevel(analysis CSPAnalysis) ThreatLevel
- func evaluateCookieThreatLevel(analysis CookieSecurityAnalysis) ThreatLevel
- func evaluateCrossOriginThreatLevel(metadata map[string]interface{}) ThreatLevel
- func evaluateHSTSThreatLevel(metadata map[string]interface{}) ThreatLevel
- func evaluateObfuscationThreat(analysis JSObfuscationAnalysis) ThreatLevel
- func evaluatePermissionsPolicyThreatLevel(metadata map[string]interface{}) ThreatLevel
- func evaluateReferrerPolicyThreatLevel(metadata map[string]interface{}) ThreatLevel
- func evaluateServerExposureThreatLevel(analysis *ServerHeaderAnalysis) ThreatLevel
- func evaluateXContentTypeOptionsThreatLevel(metadata map[string]interface{}) ThreatLevel
- func mapCVEThreatLevel(assessment CVE.VulnerabilityAssessment) ThreatLevel
- func (t ThreatLevel) MarshalJSON() ([]byte, error)
- func (t ThreatLevel) String() string
Variables¶
cspBroadSources contains CSP sources that allow broad access and don't represent specific domain restrictions.
cspKeywords contains CSP keywords that are not domain restrictions.
func aggregateSecurityIssues¶
aggregateSecurityIssues creates high-level security issue summaries
func analyzeCrossOriginHeaders¶
analyzeCrossOriginHeaders parses and analyzes all three cross-origin security headers to determine the overall security posture and isolation effectiveness.
Parameters:
- coepHeader: Cross-Origin-Embedder-Policy header value
- corpHeader: Cross-Origin-Resource-Policy header value
- coopHeader: Cross-Origin-Opener-Policy header value
Returns:
- map[string]interface{}: Structured metadata containing cross-origin security analysis
func analyzeDirectiveSecurity¶
analyzeDirectiveSecurity checks each directive for security issues
func analyzeHSTSHeader¶
analyzeHSTSHeader parses the Strict-Transport-Security header value and extracts configuration directives into a structured metadata map. This function performs case-insensitive parsing to handle various header formats.
Parsed directives:
- max-age: The time (in seconds) that the browser should remember to access the site using HTTPS
- includeSubDomains: Whether the HSTS policy applies to all subdomains
- preload: Whether the site is eligible for HSTS preload list inclusion
The function handles various header formats including:
- "max-age=31536000; includeSubDomains; preload"
- "max-age=31536000"
- "MAX-AGE=31536000; INCLUDESUBDOMAINS" (case-insensitive)
Parameters:
- hstsHeader: Raw Strict-Transport-Security header value from HTTP response
Returns:
- map[string]interface{}: Structured metadata containing:
- "include_subdomains" (bool): includeSubDomains directive present
- "preload" (bool): preload directive present
- "max_age" (int): max-age value in seconds (0 if missing/invalid)
- "directives" ([]string): List of present optional directives
Example:
header := "max-age=31536000; includeSubDomains; preload"
metadata := analyzeHSTSHeader(header)
// Returns: {
// "include_subdomains": true,
// "preload": true,
// "max_age": 31536000,
// "directives": ["includeSubDomains", "preload"]
// }
func analyzeIndividualCookieSecurity¶
func analyzeIndividualCookieSecurity(detail *CookieSecurityDetail, cookie *http.Cookie, headers []string, index int)
analyzeIndividualCookieSecurity identifies specific security issues
func analyzePermissionsPolicyHeader¶
func analyzeReferrerPolicyHeader¶
analyzeReferrerPolicyHeader parses the Referrer-Policy header value and extracts policy directives into a structured metadata map. This function handles multiple comma-separated values and normalizes case variations.
Parsed information:
- policies: List of referrer policy directives from the header
- effective_policy: The policy that will be applied (last valid one)
- policy_count: Number of policies specified
- has_unsafe: Whether unsafe policies are present
The function handles various header formats including:
- "strict-origin-when-cross-origin"
- "no-referrer, strict-origin-when-cross-origin" (multiple policies)
- "SAME-ORIGIN" (case-insensitive)
- "no-referrer , origin" (with spaces)
Parameters:
- referrerPolicyHeader: Raw Referrer-Policy header value from HTTP response
Returns:
- map[string]interface{}: Structured metadata containing:
- policies: []string - List of policy directives
- effective_policy: string - The effective policy (last valid one)
- policy_count: int - Number of policies specified
- has_unsafe: bool - Whether unsafe policies (unsafe-url) are present
- invalid_policies: []string - List of unrecognized policy values
Example:
metadata1 := analyzeReferrerPolicyHeader("strict-origin-when-cross-origin")
// Returns: {policies: ["strict-origin-when-cross-origin"], effective_policy: "strict-origin-when-cross-origin", ...}
metadata2 := analyzeReferrerPolicyHeader("no-referrer, unsafe-url")
// Returns: {policies: ["no-referrer", "unsafe-url"], effective_policy: "unsafe-url", has_unsafe: true, ...}
func analyzeXContentTypeOptionsHeader¶
analyzeXContentTypeOptionsHeader parses the X-Content-Type-Options header value
func assessEmbeddingCapability¶
assessEmbeddingCapability determines whether the page can be embedded in an iframe based on the configured frame protection headers.
Parameters:
- xframeDirective: X-Frame-Options directive value
- cspFrameValue: CSP frame-ancestors directive value
- xframeValid: Whether X-Frame-Options syntax is valid
Returns:
- string: Embedding capability (blocked, same-origin, limited, allowed)
func calculateCookieSecurityScore¶
calculateCookieSecurityScore calculates overall security score (0-100)
func calculateIndividualCookieScore¶
calculateIndividualCookieScore calculates security score for a single cookie
func calculateObfuscationScore¶
calculateObfuscationScore calculates overall obfuscation score (0-100)
func calculatePolicyStrength¶
calculatePolicyStrength calculates a numerical strength score (0-100)
func checkMissingDirectives¶
checkMissingDirectives identifies important missing CSP directives
func containsHash¶
func containsNonce¶
CSP-specific utility functions
func detectBase64Encoding¶
detectBase64Encoding detects Base64 encoded strings
func detectCharCodeObfuscation¶
detectCharCodeObfuscation detects String.fromCharCode obfuscation
func detectDynamicExecution¶
detectDynamicExecution detects eval, Function, and similar dynamic code execution
func detectEncodedStrings¶
detectEncodedStrings detects various string encoding methods
func detectEscapeSequences¶
detectEscapeSequences detects hex and unicode escape sequences
func detectMaliciousIndicators¶
detectMaliciousIndicators detects patterns strongly associated with malicious code
func detectSuspiciousPatterns¶
detectSuspiciousPatterns detects patterns commonly associated with obfuscation
func detectTechnologies¶
detectTechnologies identifies specific technologies and their versions from HTTP header values.
This function uses pattern matching and heuristics to recognize common web servers, application frameworks, content management systems, and infrastructure components based on the header name and value.
Detection Strategy:
The function employs a switch-case approach for each header type:
- Server: Detects web servers (Apache, Nginx, IIS, Cloudflare, etc.)
- X-Powered-By: Identifies frameworks (Express, Django, PHP, Laravel, etc.)
- X-AspNet-Version: Captures ASP.NET version directly
- X-AspNetMvc-Version: Captures ASP.NET MVC version directly
- X-Generator: Detects CMS (Drupal, WordPress)
- Other headers: Various specialized detections
Version Extraction:
When possible, versions are extracted using the extractVersion() function which parses patterns like "nginx/1.18.0" or "PHP/7.4.3".
Recognized Technologies:
Web Servers:
- Apache, Nginx, Microsoft IIS, Cloudflare, Gunicorn, Uvicorn
Frameworks:
- Express.js, Django, ASP.NET, PHP, Laravel, Ruby on Rails, Flask, Spring Framework
CMS:
- Drupal, WordPress
Infrastructure:
- Google PageSpeed, Varnish Cache, Dynamic Runtime
Parameters:
- headerName: The HTTP header name (e.g., "Server", "X-Powered-By")
- headerValue: The actual value of the header
Returns:
- map[string]string: Map of detected technologies to their versions
- Keys are technology names (e.g., "Nginx", "PHP")
- Values are versions if detected, or empty string/generic indicator
Example:
// Web server detection
tech := detectTechnologies("Server", "nginx/1.18.0 (Ubuntu)")
// Returns: {"Nginx": "1.18.0"}
// Framework detection
tech := detectTechnologies("X-Powered-By", "PHP/7.4.3")
// Returns: {"PHP": "7.4.3"}
// Multiple technologies in one header
tech := detectTechnologies("Server", "Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f")
// Returns: {"Apache": "2.4.41"}
// Version-less detection
tech := detectTechnologies("X-Powered-By", "Express")
// Returns: {"Express.js": ""}
Note:
Case-insensitive matching is used to handle variations in header formatting. Not all technologies can have versions extracted; some return empty strings.
func determineCSPProtectionLevel¶
determineCSPProtectionLevel sets overall protection assessment
func determineObfuscationLevel¶
determineObfuscationLevel categorizes obfuscation severity
func determineProtectionLevel¶
determineProtectionLevel assesses the overall frame protection strength based on configured headers and directives.
Parameters:
- xframeDirective: X-Frame-Options directive value
- cspFrameValue: CSP frame-ancestors directive value
- xframeValid: Whether X-Frame-Options syntax is valid
Returns:
- string: Protection level (excellent, good, limited, weak, vulnerable)
func evaluateDirectiveCompliance¶
evaluateDirectiveCompliance assesses individual directive configurations
func extractFrameAncestorsValue¶
extractFrameAncestorsValue parses the Content-Security-Policy header to extract the frame-ancestors directive value.
Parameters:
- cspHeader: Complete CSP header value
Returns:
- string: frame-ancestors directive value or empty string if not found
func extractMaxAge¶
extractMaxAge extracts and parses the max-age directive value from the HSTS header. The max-age directive specifies the duration (in seconds) that the browser should remember to access the site exclusively over HTTPS.
The function performs case-insensitive parsing and handles various formats:
- "max-age=31536000"
- "MAX-AGE=31536000"
- "max-age=31536000; includeSubDomains"
Parsing process:
- Split header by semicolon to separate directives
- Trim whitespace from each directive
- Look for "max-age=" prefix (case-insensitive)
- Extract numeric value after the equals sign
- Convert to integer
Parameters:
- hstsHeader: Raw Strict-Transport-Security header value
Returns:
- int: max-age value in seconds, or 0 if not found or invalid
Example:
age1 := extractMaxAge("max-age=31536000; includeSubDomains") // Returns: 31536000
age2 := extractMaxAge("includeSubDomains; preload") // Returns: 0
age3 := extractMaxAge("max-age=invalid") // Returns: 0
func extractScriptContent¶
extractScriptContent extracts JavaScript from script tags
func extractVersion¶
extractVersion attempts to extract version information from HTTP header values using pattern recognition for common version formatting conventions.
This function parses header values to isolate version numbers following technology names, handling various separator styles and formats commonly used in HTTP headers.
Supported Version Patterns:
- Slash separator: "nginx/1.18.0"
- Hyphen separator: "PHP-7.4.3"
- Direct placement: "Apache 2.4.41"
- Version prefix: "v1.18.0" or "V1.18.0"
Algorithm:
- Convert to lowercase for case-insensitive matching
- Locate the technology name within the header value
- Examine characters after the technology name
- Identify version start (first digit or after separator)
- Extract consecutive version characters (digits, dots, hyphens)
- Return the isolated version string
Version Character Rules:
- Digits (0-9): Valid version characters
- Dots (.): Valid separators (1.18.0)
- Hyphens (-): Valid for pre-release versions (1.0.0-beta)
- Any other character: Terminates version extraction
Parameters:
- headerValue: The complete HTTP header value (e.g., "nginx/1.18.0 (Ubuntu)")
- technology: The technology name to locate (e.g., "nginx")
Returns:
- string: Extracted version number, or empty string if not found
Example:
// Standard slash format
version := extractVersion("nginx/1.18.0 (Ubuntu)", "nginx")
// Returns: "1.18.0"
// Hyphen separator
version := extractVersion("PHP-7.4.3", "PHP")
// Returns: "7.4.3"
// Version prefix
version := extractVersion("Apache v2.4.41", "Apache")
// Returns: "2.4.41"
// Direct placement
version := extractVersion("IIS 10.0", "IIS")
// Returns: "10.0"
// No version found
version := extractVersion("Cloudflare", "Cloudflare")
// Returns: ""
// Complex header
version := extractVersion("Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f", "Apache")
// Returns: "2.4.41"
Note:
This function uses case-insensitive matching for robustness. It only extracts the first version number encountered after the technology name.
func formatDuration¶
formatDuration formats a duration in human-readable format
func formatMaxAge¶
formatMaxAge converts a max-age value in seconds to a human-readable duration string. The function automatically selects the most appropriate time unit (years, months, days, hours, or seconds) based on the magnitude of the value.
Conversion logic:
- ≥ 1 year (31,536,000 sec): Express in years
- ≥ 1 month (2,592,000 sec): Express in months
- ≥ 1 day (86,400 sec): Express in days
- ≥ 1 hour (3,600 sec): Express in hours
- \< 1 hour: Express in seconds
Singular/plural handling:
- Uses singular form for value of 1 (e.g., "1 year", "1 day")
- Uses plural form for all other values (e.g., "2 years", "30 days")
Parameters:
- seconds: max-age value in seconds
Returns:
- string: Human-readable duration with appropriate unit
Examples:
formatMaxAge(31536000) // Returns: "1 year max-age"
formatMaxAge(63072000) // Returns: "2 years max-age"
formatMaxAge(2592000) // Returns: "1 month max-age"
formatMaxAge(7776000) // Returns: "3 months max-age"
formatMaxAge(86400) // Returns: "1 day max-age"
formatMaxAge(259200) // Returns: "3 days max-age"
formatMaxAge(3600) // Returns: "1 hour max-age"
formatMaxAge(7200) // Returns: "2 hours max-age"
formatMaxAge(300) // Returns: "300 seconds max-age"
func generateCSPDescription¶
generateCSPDescription creates a detailed description of CSP findings
func generateCookieDescription¶
generateCookieDescription creates detailed description of findings
func generateCrossOriginDescription¶
generateCrossOriginDescription creates a detailed description of the cross-origin security headers analysis results, including findings and recommendations.
Parameters:
- metadata: Analyzed cross-origin headers metadata
Returns:
- string: Comprehensive description of cross-origin security status
func generateDescription¶
func generateDescription(protectionLevel string, hasXFrame, hasCSP bool, canBeEmbedded string) string
generateDescription creates a description based on protection analysis
func generateHSTSDescription¶
generateHSTSDescription creates a human-readable description of the HSTS configuration analysis including the configuration details and security assessment. The description provides actionable information about the HSTS implementation quality.
Description components:
- Human-readable max-age duration (e.g., "1 year", "6 months", "30 days")
- List of present directives (includeSubDomains, preload)
- Security assessment (Excellent, Good, Acceptable, or Weak)
- Recommendations for improvement when applicable
Special cases handled:
- max-age = 0 or missing: "HSTS header present but missing or invalid max-age directive"
- Weak configuration: Includes suggestion to increase max-age
Parameters:
- metadata: Parsed HSTS header metadata containing max_age, directives, and flags
Returns:
- string: Formatted description for the TestResult
Example outputs:
// Excellent configuration
"HSTS header configured with 1 year max-age and includes: includeSubDomains, preload - Excellent security configuration"
// Good configuration
"HSTS header configured with 2 years max-age and includes: includeSubDomains - Good security configuration"
// Weak configuration
"HSTS header configured with 30 days max-age - Weak security configuration, consider increasing max-age"
// Missing max-age
"HSTS header present but missing or invalid max-age directive"
func generateObfuscationDescription¶
generateObfuscationDescription creates detailed description
func generatePermissionsPolicyDescription¶
generatePermissionsPolicyDescription creates a human-readable description of the Permissions-Policy analysis results.
func generateReferrerPolicyDescription¶
generateReferrerPolicyDescription creates a human-readable description of the Referrer-Policy analysis results, including findings, risks, and recommendations.
The description covers:
- Current policy configuration assessment
- Privacy and security implications
- Information leakage risks
- Specific recommendations for improvement
- Policy conflicts or configuration warnings
Parameters:
- metadata: Parsed referrer policy metadata from analyzeReferrerPolicyHeader
Returns:
- string: Detailed human-readable description of findings and recommendations
Example output:
"Referrer-Policy configured with 'strict-origin-when-cross-origin' - excellent privacy
protection that balances security with functionality. This W3C recommended policy sends
full URL for same-origin requests and only origin for cross-origin requests..."
func generateServerExposureDescription¶
generateServerExposureDescription creates a human-readable description of server header information disclosure findings.
This function synthesizes the analysis results into clear, concise descriptions suitable for security reports, console output, and API responses. It provides context about the exposure scope and identified technologies.
Description Format:
No Exposure:
- "No server technology information disclosed in headers - good security practice"
With Exposure:
- Pattern: "{count} header(s) expose server information. Detected technologies: {tech_list}"
- Single: "1 header exposes server information. Detected technologies: Nginx"
- Multiple: "5 headers expose server information. Detected technologies: Apache, PHP, OpenSSL"
Description Components:
- Exposure Count: Quantifies how many headers reveal information
- Technology List: Comma-separated list of detected technologies
- Grammar: Proper singular/plural handling ("header" vs "headers")
Parameters:
- analysis: ServerHeaderAnalysis containing exposure and technology data
Returns:
- string: Human-readable description of findings
Example:
// No exposure scenario
analysis := &ServerHeaderAnalysis{
total_exposures: 0,
technologies: []string{},
}
desc := generateServerExposureDescription(analysis)
// Returns: "No server technology information disclosed in headers - good security practice"
// Single exposure
analysis := &ServerHeaderAnalysis{
total_exposures: 1,
technologies: []string{"Cloudflare"},
}
desc := generateServerExposureDescription(analysis)
// Returns: "1 header exposes server information. Detected technologies: Cloudflare"
// Multiple exposures
analysis := &ServerHeaderAnalysis{
total_exposures: 3,
technologies: []string{"Apache", "PHP", "OpenSSL"},
}
desc := generateServerExposureDescription(analysis)
// Returns: "3 headers expose server information. Detected technologies: Apache, PHP, OpenSSL"
Usage Context:
These descriptions appear in:
- TestResult.Description field for test results
- CLI reporter output for console display
- Backend reporter API payloads
- Security audit reports
- Log files and monitoring systems
Note:
The description provides high-level summary information. Detailed header values and version information are available in the ServerHeaderAnalysis metadata structure.
func generateXContentTypeOptionsDescription¶
generateXContentTypeOptionsDescription creates a human-readable description
func getSameSiteString¶
getSameSiteString converts SameSite enum to string
func hasOnlyBroadSources¶
hasOnlyBroadSources checks if the CSP frame-ancestors value contains only broad scheme sources (https:, http:, *) without specific domains. Values like "https:" alone allow all HTTPS sources, providing minimal real protection.
Parameters:
- cspLower: Lowercase CSP frame-ancestors value
Returns:
- bool: true if value only contains broad sources without specific domains
func hasSpecificDomains¶
hasSpecificDomains checks if the CSP frame-ancestors value contains specific domain restrictions (not just scheme sources, wildcards, or CSP keywords).
Parameters:
- cspLower: Lowercase CSP frame-ancestors value
Returns:
- bool: true if value contains at least one specific domain
func isAllowlistRestricted¶
isAllowlistRestricted determines if an allowlist value represents a restricted/safe configuration. According to the Permissions-Policy specification:
- "()" means disabled for all origins (restricted)
- "(self)" means allowed only for same-origin (restricted/safe)
- "" empty value means disabled (restricted)
- `(self "https://example.com" "https://other.com")` means allowed for self and specific origins (potentially dangerous), where additional origins must be quoted strings with full URLs
func isPredictableValue¶
isPredictableValue checks if cookie value appears predictable
func isSessionCookie¶
isSessionCookie determines if a cookie is likely a session cookie
type CSPAnalysis¶
CSPAnalysis represents the parsed and analyzed CSP configuration
type CSPAnalysis struct {
HasCSP bool `json:"hasCSP"`
Directives map[string][]string `json:"directives"`
SecurityIssues []string `json:"securityIssues"`
MissingDirectives []string `json:"missingDirectives"`
UnsafeDirectives []string `json:"unsafeDirectives"`
ProtectionLevel string `json:"protectionLevel"`
RecommendedActions []string `json:"recommendedActions"`
DirectiveCompliance map[string]string `json:"directiveCompliance"`
PolicyStrength int `json:"policyStrength"` // 0-100 score
CriticalVulns []string `json:"criticalVulns"`
}
func analyzeCSPHeader¶
analyzeCSPHeader performs comprehensive analysis of the CSP header configuration
type CookieSecurityAnalysis¶
CookieSecurityAnalysis represents the comprehensive cookie security assessment
type CookieSecurityAnalysis struct {
TotalCookies int `json:"totalCookies"`
CookieDetails []CookieSecurityDetail `json:"cookieDetails"`
SecurityIssues []string `json:"securityIssues"`
CriticalIssues []string `json:"criticalIssues"`
MissingHttpOnly int `json:"missingHttpOnly"`
MissingSecure int `json:"missingSecure"`
MissingSameSite int `json:"missingSameSite"`
LongExpiration int `json:"longExpiration"`
SessionCookies int `json:"sessionCookies"`
InsecureSession bool `json:"insecureSession"`
FixationRisk bool `json:"fixationRisk"`
OverallSecurityScore int `json:"overallSecurityScore"` // 0-100
}
func analyzeCookieSecurity¶
analyzeCookieSecurity performs comprehensive analysis of all cookies
type CookieSecurityDetail¶
CookieSecurityDetail represents security analysis for a single cookie
type CookieSecurityDetail struct {
Name string `json:"name"`
HasHttpOnly bool `json:"hasHttpOnly"`
HasSecure bool `json:"hasSecure"`
SameSite string `json:"sameSite"`
MaxAge int `json:"maxAge"`
ExpiresIn string `json:"expiresIn"`
IsSessionCookie bool `json:"isSessionCookie"`
SecurityIssues []string `json:"securityIssues"`
SecurityScore int `json:"securityScore"` // 0-100
PredictableValue bool `json:"predictableValue"`
}
func analyzeSingleCookie¶
func analyzeSingleCookie(cookie *http.Cookie, setCookieHeaders []string, index int) CookieSecurityDetail
analyzeSingleCookie performs detailed security analysis of a single cookie
type CrossOriginAnalysis¶
CrossOriginAnalysis represents the parsed and analyzed cross-origin security headers configuration
type CrossOriginAnalysis struct {
HasCOEP bool `json:"hasCOEP"`
HasCORP bool `json:"hasCORP"`
HasCOOP bool `json:"hasCOOP"`
COEPValue string `json:"coepValue"`
CORPValue string `json:"corpValue"`
COOPValue string `json:"coopValue"`
SecurityIssues []string `json:"securityIssues"`
ConfiguredHeaders []string `json:"configuredHeaders"`
MissingHeaders []string `json:"missingHeaders"`
ProtectionLevel string `json:"protectionLevel"`
RecommendedActions []string `json:"recommendedActions"`
IsolationEffective bool `json:"isolationEffective"`
}
type JSObfuscationAnalysis¶
JSObfuscationAnalysis represents the comprehensive obfuscation analysis
type JSObfuscationAnalysis struct {
HasObfuscation bool `json:"hasObfuscation"`
ObfuscationScore int `json:"obfuscationScore"` // 0-100
ObfuscationPatterns []string `json:"obfuscationPatterns"`
SuspiciousPatterns []string `json:"suspiciousPatterns"`
MaliciousIndicators []string `json:"maliciousIndicators"`
EncodingMethods []string `json:"encodingMethods"`
DynamicExecution int `json:"dynamicExecution"` // Count of eval/Function calls
EncodedStrings int `json:"encodedStrings"` // Count of encoded strings
CharCodeUsage int `json:"charCodeUsage"` // String.fromCharCode usage
HexEscapes int `json:"hexEscapes"` // \x escape sequences
UnicodeEscapes int `json:"unicodeEscapes"` // \u escape sequences
Base64Strings int `json:"base64Strings"` // Base64 encoded strings
ObfuscationLevel string `json:"obfuscationLevel"` // none, light, moderate, heavy, extreme
Certainty int `json:"certainty"` // 0-100
}
func analyzeJSObfuscation¶
analyzeJSObfuscation performs comprehensive JavaScript obfuscation analysis
type ResponseTest¶
ResponseTest defines a security test that analyzes an HTTP response for vulnerabilities, misconfigurations, or security issues. It provides the structure and execution interface for all security tests in the framework.
The structure uses composition with a function field for flexible test implementation:
- Allows inline test definition without separate structs
- Enables closure-based tests with captured context
- Simplifies test registration and discovery
- Supports both simple and complex test logic
Each test should:
- Analyze specific security aspects (HTTPS, HSTS, headers, etc.)
- Return structured TestResult with appropriate ThreatLevel
- Include detailed Metadata for findings
- Provide actionable Description for remediation
Fields:
- Id: Unique identifier for test registration and selection (e.g., "https", "hsts")
- Name: Human-readable test name for display
- Description: Detailed explanation of what the test checks
- RunTest: Function that executes the test logic
type ResponseTest struct {
Id string // Unique test identifier (e.g., "https", "hsts", "csp")
Name string // Human-readable test name
Description string // Detailed test description
RunTest func(params ResponseTestParams) TestResult // Test execution function
}
func NewCSPTest¶
NewCSPTest creates a new ResponseTest that analyzes Content Security Policy (CSP) header configuration. CSP is a security mechanism that helps prevent cross-site scripting (XSS), data injection attacks, and other code injection vulnerabilities by controlling which resources the browser is allowed to load for a given page.
The test evaluates:
- Presence of Content-Security-Policy header
- Critical directive configurations (default-src, script-src, object-src, etc.)
- Unsafe directive values ('unsafe-inline', 'unsafe-eval', '*')
- Missing security-critical directives
- Policy syntax and validity
Threat level assessment:
- None (0): Excellent - Comprehensive CSP with strict directives, no unsafe values
- Info (1): Good - Well-configured CSP with minor improvements possible
- Low (2): Acceptable - Basic CSP present with some weaknesses
- Medium (3): Weak - CSP present but with significant security issues
- High (4): Poor - CSP present but severely misconfigured or ineffective
- Critical (5): Missing - No CSP header found, vulnerable to injection attacks
Security implications:
- Missing CSP: Vulnerable to XSS, data injection, and clickjacking attacks
- unsafe-inline: Allows inline scripts/styles, negating XSS protection
- unsafe-eval: Permits eval() and similar functions, enabling code injection
- Wildcard (*): Allows loading from any source, undermining security
- Missing object-src: May allow Flash/plugin-based attacks
- Missing base-uri: Vulnerable to base tag injection attacks
Standards compliance:
- Content Security Policy Level 2 (W3C Recommendation)
- Content Security Policy Level 3 (W3C Working Draft)
Returns:
- *ResponseTest: Configured CSP test ready for execution
Example usage:
cspTest := NewCSPTest()
result := cspTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed CSP configuration analysis
func NewCookieSecurityTest¶
NewCookieSecurityTest creates a new ResponseTest that analyzes cookie security configurations. Cookies are critical for session management and authentication, making their security paramount. Improperly configured cookies can lead to session hijacking, XSS exploitation, CSRF attacks, and session fixation vulnerabilities.
The test evaluates:
- HttpOnly flag (prevents JavaScript access to cookies)
- Secure flag (ensures transmission only over HTTPS)
- SameSite attribute (protects against CSRF attacks)
- Expiration times (Max-Age/Expires values)
- Cookie predictability and session fixation risks
- Cookie name patterns indicating sensitive data
Threat level assessment:
- None (0): All cookies properly secured with HttpOnly, Secure, SameSite, and reasonable expiration
- Info (1): Minor issues like long expiration times but critical flags present
- Low (2): Some cookies missing non-critical security attributes
- Medium (3): Cookies missing important security flags (HttpOnly or Secure)
- High (4): Multiple security issues or session cookies without protection
- Critical (5): Session cookies completely unsecured or high fixation risk
Security implications:
- Missing HttpOnly: Vulnerable to XSS-based cookie theft
- Missing Secure: Cookies can be intercepted over HTTP (MITM attacks)
- Missing SameSite: Vulnerable to CSRF attacks
- Long expiration: Extended window for cookie theft/replay attacks
- Predictable values: Session fixation and prediction attacks
Returns:
- *ResponseTest: Configured cookie security test ready for execution
Example usage:
cookieTest := NewCookieSecurityTest()
result := cookieTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed cookie security analysis
func NewCrossOriginTest¶
NewCrossOriginTest creates a new ResponseTest that analyzes Cross-Origin security headers configuration. These headers provide defense-in-depth protection against cross-origin attacks, Spectre-like vulnerabilities, and help enforce browser-level isolation boundaries.
The test evaluates:
- Cross-Origin-Embedder-Policy (COEP): Controls cross-origin resource embedding
- Cross-Origin-Resource-Policy (CORP): Controls cross-origin resource access
- Cross-Origin-Opener-Policy (COOP): Controls cross-origin window opener access
- Header value validation and security implications
- Combination effectiveness for comprehensive isolation
Threat level assessment:
- None (0): Excellent - All three headers properly configured with strict values
- Info (1): Good - Two headers configured with secure values
- Low (2): Acceptable - One header configured or less strict configuration
- Medium (3): Weak - Headers present but with permissive values
- High (4): Poor - No cross-origin security headers found
Security implications:
- Missing COEP: Vulnerable to cross-origin resource embedding attacks
- Missing CORP: Resources can be accessed cross-origin without restrictions
- Missing COOP: Vulnerable to cross-origin opener attacks and window references
- Permissive values: Reduced isolation effectiveness
- No headers: Full exposure to cross-origin attacks and Spectre-like vulnerabilities
Standards compliance:
- Cross-Origin-Embedder-Policy (W3C Draft)
- Cross-Origin-Resource-Policy (W3C Recommendation)
- Cross-Origin-Opener-Policy (W3C Draft)
Returns:
- *ResponseTest: Configured cross-origin security test ready for execution
Example usage:
crossOriginTest := NewCrossOriginTest()
result := crossOriginTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed cross-origin security analysis
func NewHSTSTest¶
NewHSTSTest creates a new ResponseTest that analyzes HTTP Strict Transport Security (HSTS) header configuration. HSTS is a security mechanism that forces browsers to interact with websites exclusively over HTTPS, protecting against protocol downgrade attacks and cookie hijacking.
The test evaluates:
- Presence of Strict-Transport-Security header
- max-age directive value (minimum recommended: 6 months, ideal: 1+ year)
- includeSubDomains directive (protects all subdomains)
- preload directive (enables HSTS preload list inclusion)
Threat level assessment:
- None (0): Excellent - max-age ≥ 1 year + includeSubDomains + preload
- Info (1): Good - max-age ≥ 1 year + includeSubDomains
- Low (2): Acceptable - max-age ≥ 6 months
- Medium (3): Weak - max-age present but \< 6 months
- Medium (3): Missing - No HSTS header found
- High (4): Invalid - HSTS header present but missing/invalid max-age
Security implications:
- Missing HSTS: Vulnerable to SSL stripping attacks, protocol downgrades, and MITM attacks
- Short max-age: Limited protection window, requires frequent policy refreshes
- No includeSubDomains: Subdomains remain vulnerable to attacks
- No preload: Not eligible for browser HSTS preload lists
Returns:
- *ResponseTest: Configured HSTS test ready for execution
Example usage:
hstsTest := NewHSTSTest()
result := hstsTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed configuration analysis
func NewHTTPSTest¶
NewHTTPSTest creates a new security test that verifies HTTPS protocol usage. This test checks whether the target website enforces encrypted HTTPS connections or allows insecure HTTP communication.
Test Behavior:
The test examines the URL scheme of the HTTP response to determine the protocol:
- If scheme is "https": Returns ThreatLevel.None (secure)
- If scheme is "http": Returns ThreatLevel.High (insecure)
Security Implications:
HTTP connections transmit data in plaintext, making them vulnerable to:
- Packet sniffing and eavesdropping
- Man-in-the-middle (MITM) attacks
- Data tampering and injection
- Session hijacking
- Credential theft
HTTPS provides:
- End-to-end encryption (TLS/SSL)
- Server authentication via certificates
- Data integrity verification
- Protection against passive and active attacks
Certainty:
This test always returns 100% certainty as protocol detection is deterministic based on the URL scheme in the HTTP response object.
Returns:
- *ResponseTest: Configured test instance ready for execution
Example:
// Create the HTTPS test
httpsTest := NewHTTPSTest()
// Execute against target (via Runner)
params := ResponseTestParams{
Response: httpResponse,
Url: "https://example.com",
}
result := httpsTest.Run(params)
// Secure site (HTTPS)
// result.ThreatLevel = None
// result.Description = "Connection is secured with HTTPS protocol..."
// Insecure site (HTTP)
// result.ThreatLevel = High
// result.Description = "Connection uses insecure HTTP protocol..."
Related Tests:
- HSTSTest: Validates HTTP Strict Transport Security headers
- ServerHeaderTest: Analyzes server headers for security issues
func NewJSObfuscationTest¶
NewJSObfuscationTest creates a new ResponseTest that analyzes JavaScript code for obfuscation. Obfuscated JavaScript is often used by attackers to hide malicious payloads, evade detection, or make reverse engineering difficult. While legitimate sites may use minification, heavy obfuscation is a red flag for potential security threats.
The test evaluates:
- Encoded strings (Base64, hex, unicode escape sequences)
- Character substitution patterns
- Excessive use of eval(), Function(), or similar dynamic execution
- String concatenation obfuscation
- Highly compressed or minimized code patterns
- Suspicious variable/function naming patterns
- Code that decodes or decrypts itself at runtime
Threat level assessment:
- None (0): No obfuscation detected, clean JavaScript code
- Info (1): Minor minification or basic optimization detected
- Low (2): Some obfuscation patterns but likely legitimate (e.g., webpack bundles)
- Medium (3): Moderate obfuscation with multiple suspicious patterns
- High (4): Heavy obfuscation with clear intent to hide functionality
- Critical (5): Extremely obfuscated code with malicious indicators
Security implications:
- Obfuscated code can hide malicious payloads (keyloggers, data exfiltration)
- May indicate compromised website or injected malware
- Can evade security scanners and code review
- Often used in drive-by download attacks
- May hide cryptocurrency miners or ad fraud scripts
Detection patterns:
- Base64 encoded strings followed by decode/atob
- Hex escape sequences (\x41\x42\x43)
- Unicode escape sequences (\u0041\u0042\u0043)
- eval() with encoded or constructed strings
- String.fromCharCode() with numeric arrays
- Excessive string concatenation
- Self-modifying or self-decrypting code
Returns:
- *ResponseTest: Configured JavaScript obfuscation test ready for execution
Example usage:
jsObfTest := NewJSObfuscationTest()
result := jsObfTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed obfuscation analysis
func NewPermissionsPolicyTest¶
NewPermissionsPolicyTest creates a new ResponseTest that analyzes Permissions-Policy header configuration. The Permissions-Policy header controls which browser features and APIs can be used by the page and its embedded content, replacing the deprecated Feature-Policy.
The test evaluates:
- Presence of Permissions-Policy header
- Dangerous permissions that should be restricted
- Overly permissive wildcard (*) usage
- Common security-sensitive features
Threat level assessment:
- None (0): Excellent - Comprehensive policy with restricted dangerous features
- Info (1): Good - Policy present with minor issues
- Low (2): Acceptable - Basic policy with some unrestricted features
- Medium (3): Weak - Policy present but allows dangerous features
- High (4): Missing - No policy header found
Security implications:
- Missing header: All features available to page and embedded content
- Unrestricted dangerous features: Risk of abuse (camera, microphone, geolocation)
- Wildcard usage: Overly permissive access to sensitive APIs
Returns:
- *ResponseTest: Configured Permissions-Policy test ready for execution
func NewReferrerPolicyTest¶
NewReferrerPolicyTest creates a new ResponseTest that analyzes Referrer-Policy header configuration. The Referrer-Policy header controls how much referrer information (sent via the Referer header) should be included with requests made from your site. Proper configuration prevents information leakage and protects user privacy.
The test evaluates:
- Presence of Referrer-Policy header
- Policy directive values and their security implications
- Multiple policy values and their precedence
- Insecure policy configurations
Threat level assessment:
- None (0): Excellent - strict-origin-when-cross-origin, strict-origin, or no-referrer
- Info (1): Good - origin-when-cross-origin or origin
- Low (2): Acceptable - same-origin
- Medium (3): Weak - no-referrer-when-downgrade (default behavior)
- High (4): Vulnerable - unsafe-url or missing header with default behavior
Security implications:
- Missing header: Uses browser default (typically no-referrer-when-downgrade)
- unsafe-url: Full URL sent as referrer to all origins (including HTTP)
- origin/origin-when-cross-origin: May leak origin information unnecessarily
- no-referrer: Maximum privacy but may break some functionality
- strict-origin-when-cross-origin: Recommended balance of security and functionality
Policy values and security levels:
- no-referrer: Excellent - No referrer information sent
- no-referrer-when-downgrade: Medium - Default, leaks info on HTTPS→HTTP
- origin: Info - Only origin sent, reasonable privacy
- origin-when-cross-origin: Info - Full URL for same-origin, origin for cross-origin
- same-origin: Low - Full URL for same-origin only
- strict-origin: Excellent - Origin only, no referrer on downgrade
- strict-origin-when-cross-origin: Excellent - Recommended by W3C
- unsafe-url: High - Always sends full URL (insecure)
Returns:
- *ResponseTest: Configured Referrer-Policy test ready for execution
Example usage:
referrerTest := NewReferrerPolicyTest()
result := referrerTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed policy analysis
func NewSSLCertificateSecurityTest¶
NewSSLCertificateSecurityTest creates a new ResponseTest that analyzes the SSL/TLS certificate of the target website for security best practices.
The test evaluates:
- Certificate validity (not expired, not yet valid)
- Use of strong signature algorithms (e.g., SHA-256+)
- Key length (2048 bits or higher recommended)
- Certificate chain completeness
- Hostname match
Threat level assessment:
- None (0): Certificate is valid, strong, and not expiring soon
- Info (1): Certificate is valid but expiring within 30 days
- Medium (3): Weak signature algorithm or short key length
- High (4): Certificate expired, not yet valid, or hostname mismatch
- Critical (5): No certificate, self-signed, or invalid chain
Returns:
- *ResponseTest: Configured SSL certificate security test ready for execution
func NewServerHeaderTest¶
NewServerHeaderTest creates a new security test that analyzes HTTP response headers for server technology information disclosure vulnerabilities.
This test examines 12 common HTTP headers that frequently expose sensitive information about the server technology stack, frameworks, and hosting infrastructure. It performs technology detection, version extraction, and CVE vulnerability assessment.
Test Workflow:
- Extract Target Headers: Collect values from 12 predefined headers
- Analyze Headers: Identify exposed headers and detect technologies
- CVE Assessment: Query NIST NVD for known vulnerabilities
- Threat Evaluation: Calculate threat level based on exposure and CVEs
- Generate Report: Create human-readable description
Detected Technologies:
Web Servers:
- Apache, Nginx, Microsoft IIS, Cloudflare, Gunicorn, Uvicorn
Application Frameworks:
- Express.js, Django, ASP.NET, PHP, Laravel, Ruby on Rails, Flask, Spring Framework
Content Management Systems:
- Drupal, WordPress
Infrastructure:
- Google PageSpeed, Varnish Cache, Dynamic Runtime
Security Impact:
Information disclosure enables:
- Vulnerability scanning with version-specific exploit databases
- Targeted attack preparation based on known weaknesses
- Technology stack fingerprinting
- Reduced attacker reconnaissance time
The test assigns higher threat levels when:
- Multiple headers expose information (5+ = Medium)
- Technologies have known high-severity CVEs (Critical)
- Debug/test/dev indicators present (Critical)
- Common web servers revealed (High)
Certainty:
This test reports 95% certainty as header analysis is highly reliable, but some false positives may occur from customized or obfuscated headers.
Returns:
- *ResponseTest: Configured test instance ready for execution
Example:
// Create the server header test
headerTest := NewServerHeaderTest()
// Execute against target (via Runner)
params := ResponseTestParams{
Response: httpResponse,
Url: "https://example.com",
}
result := headerTest.Run(params)
// No exposure (secure)
// result.ThreatLevel = None
// result.Description = "No server technology information disclosed..."
// Multiple exposures (insecure)
// result.ThreatLevel = High
// result.Description = "5 headers expose server information. Detected: Apache/2.4.41, PHP/7.4.3..."
// result.Metadata = ServerHeaderAnalysis{...}
CVE Integration Example:
// If Apache 2.4.41 is detected and has known CVEs:
// - Query NVD API for "Apache" vulnerabilities
// - Assess severity levels (High/Medium/Low)
// - Elevate threat level to Critical if high-severity CVEs found
Related Tests:
- HTTPSTest: Validates encrypted connections
- HSTSTest: Checks HTTP Strict Transport Security enforcement
func NewXContentTypeOptionsTest¶
NewXContentTypeOptionsTest creates a new ResponseTest that analyzes X-Content-Type-Options header configuration. The X-Content-Type-Options header prevents browsers from MIME-sniffing a response away from the declared content-type, which helps prevent XSS attacks and other security issues.
The test evaluates:
- Presence of X-Content-Type-Options header
- Correct "nosniff" directive value
- Case sensitivity and formatting
Threat level assessment:
- None (0): Excellent - X-Content-Type-Options: nosniff properly configured
- High (4): Missing - No header found, vulnerable to MIME sniffing attacks
- Medium (3): Invalid - Header present but with incorrect value
Security implications:
- Missing header: Browsers may MIME-sniff content leading to XSS vulnerabilities
- Invalid value: Header ignored by browsers, same risk as missing
- Correct "nosniff": Prevents MIME type sniffing attacks
Returns:
- *ResponseTest: Configured X-Content-Type-Options test ready for execution
func NewXFrameTest¶
NewXFrameTest creates a new ResponseTest that analyzes X-Frame-Options header and CSP frame directives to assess clickjacking protection. Clickjacking attacks embed target pages in iframes to trick users into performing unintended actions on the embedded content.
The test evaluates:
- Presence of X-Frame-Options header (legacy protection)
- X-Frame-Options directive values (DENY, SAMEORIGIN, ALLOW-FROM)
- Content-Security-Policy frame-ancestors directive (modern protection)
- Conflicting or invalid configurations
Threat level assessment:
- None (0): Excellent - CSP frame-ancestors 'none' or X-Frame-Options DENY
- Info (1): Good - CSP frame-ancestors 'self' or X-Frame-Options SAMEORIGIN
- Low (2): Limited - X-Frame-Options ALLOW-FROM (deprecated and limited browser support)
- Medium (3): Weak - Only CSP frame-ancestors with specific domains (partial protection)
- High (4): Vulnerable - Missing both X-Frame-Options and CSP frame-ancestors
- High (4): Invalid - Present but with invalid/malformed directives
Security implications:
- Missing protection: Vulnerable to clickjacking attacks, UI redressing, and iframe abuse
- ALLOW-FROM directive: Deprecated and not supported in modern browsers
- Conflicting headers: May lead to inconsistent protection across browsers
- Invalid values: Browsers may ignore protection, leaving site vulnerable
Standards compliance:
- X-Frame-Options: RFC 7034 (legacy, but widely supported)
- CSP frame-ancestors: CSP Level 2 (modern, preferred approach)
Returns:
- *ResponseTest: Configured X-Frame-Options test ready for execution
Example usage:
xframeTest := NewXFrameTest()
result := xframeTest.Run(ResponseTestParams{Response: httpResponse})
// Result includes threat level and detailed iframe embedding analysis
func (*ResponseTest) GetDescription¶
GetDescription returns the detailed description of what the test analyzes. This method provides read-only access to the test's purpose and functionality.
Returns:
- string: The test's detailed description
func (*ResponseTest) GetId¶
GetId returns the unique identifier of the test used for registration and lookup. This method provides read-only access to the test's ID.
Returns:
- string: The test's unique identifier
func (*ResponseTest) GetName¶
GetName returns the human-readable name of the test for display purposes. This method provides read-only access to the test's display name.
Returns:
- string: The test's display name
func (*ResponseTest) Run¶
Run executes the test logic against the provided HTTP response parameters and returns the security analysis results. This is the main entry point for test execution.
The method validates that RunTest is implemented before execution and panics if not, ensuring tests are properly configured before use.
Parameters:
- params: ResponseTestParams containing the HTTP response to analyze
Returns:
- TestResult: Structured results including threat level and findings
Panics:
- string: "Run method not implemented" if RunTest function is nil
Example:
test := NewHTTPSTest()
params := ResponseTestParams{Response: httpResponse}
result := test.Run(params)
fmt.Printf("Threat Level: %v\n", result.ThreatLevel)
type ResponseTestParams¶
ResponseTestParams encapsulates the parameters passed to a ResponseTest for execution. It provides the HTTP response object that tests analyze to detect security issues, misconfigurations, and vulnerabilities.
The structure enables:
- Clean test interface with extensibility
- Sharing of HTTP response across multiple tests
- Future addition of context or configuration parameters
The Response object contains:
- HTTP headers (security headers, server information, etc.)
- Status code
- Request details (URL, method, original request)
- Body content (if read by test)
type ResponseTestParams struct {
Response *http.Response // HTTP response to analyze for security issues
}
type ServerHeaderAnalysis¶
ServerHeaderAnalysis represents the comprehensive analysis results of HTTP headers for server technology information disclosure.
This structure aggregates data about exposed headers, detected technologies, and their potential security implications. It serves as metadata for test results and provides detailed insights for security reporting.
Fields:
- exposed_headers: List of header names that revealed information
- technologies: Detected technology stack components (deduplicated)
- total_exposures: Count of headers exposing information
- header_details: Map of header names to their actual values
- technology_stack: Map of detected technologies to their versions
Example structure:
{
exposed_headers: ["Server", "X-Powered-By"],
technologies: ["Nginx", "PHP"],
total_exposures: 2,
header_details: {
"Server": "nginx/1.18.0",
"X-Powered-By": "PHP/7.4.3"
},
technology_stack: {
"Nginx": "1.18.0",
"PHP": "7.4.3"
}
}
type ServerHeaderAnalysis struct {
exposed_headers []string
technologies []string
total_exposures int
header_details map[string]string
technology_stack map[string]string
}
func analyzeServerHeaders¶
analyzeServerHeaders examines HTTP headers for technology disclosure patterns and constructs a comprehensive analysis of exposed information.
This function processes the collected headers to identify:
- Which headers expose information
- What technologies are revealed
- Version information when available
- Overall exposure count
The analysis involves:
- Filtering out empty headers
- Recording exposed header names
- Detecting technologies from header values
- Extracting version information
- Building technology stack mapping
- Deduplicating technology entries
Technology Detection:
For each non-empty header, the function calls detectTechnologies() which uses pattern matching to identify specific software, frameworks, and services.
Parameters:
- headers: Map of header names to their values from HTTP response
Returns:
- *ServerHeaderAnalysis: Comprehensive analysis structure with:
- exposed_headers: List of header names containing information
- technologies: Deduplicated list of detected technologies
- total_exposures: Count of exposed headers
- header_details: Original header name-value pairs
- technology_stack: Technology-to-version mapping
Example:
headers := map[string]string{
"Server": "nginx/1.18.0",
"X-Powered-By": "PHP/7.4.3",
"X-Cache": "", // Empty, will be filtered
}
analysis := analyzeServerHeaders(headers)
// analysis.exposed_headers = ["Server", "X-Powered-By"]
// analysis.technologies = ["Nginx", "PHP"]
// analysis.total_exposures = 2
// analysis.technology_stack = {"Nginx": "1.18.0", "PHP": "7.4.3"}
type TestResult¶
TestResult represents the comprehensive output of a security test execution. It encapsulates all information about the test findings including classification, confidence level, detailed metadata, and human-readable descriptions.
The structure is designed for:
- JSON serialization for API reporting
- Human-readable console output
- Automated processing and aggregation
- Detailed forensic analysis
Fields provide multiple levels of detail:
- Name: Test identifier for categorization
- Certainty: Confidence percentage (0-100) in the finding
- ThreatLevel: Security classification (None to Critical)
- Metadata: Test-specific data (headers, configurations, CVEs, etc.)
- Description: Human-readable explanation of findings
type TestResult struct {
Name string `json:"Name"` // Test name for identification
Certainty int `json:"Certainty"` // Confidence percentage (0-100)
ThreatLevel ThreatLevel `json:"ThreatLevel"` // Security threat classification
Metadata any `json:"Metadata"` // Test-specific detailed data
Description string `json:"Description"` // Human-readable findings explanation
}
type TestResultWrapper¶
TestResultWrapper represents fully structured response sent to the backend Fields:
- Target: Given target
- TestId: id related to full scan
- Result: Core data of test
- EndFlag: Check if engine finished its job
type TestResultWrapper struct {
Target string `json:"target"`
TestId string `json:"testId"`
Result TestResult `json:"result"`
EndFlag bool `json:"endFlag"`
}
type ThreatLevel¶
ThreatLevel represents the security threat classification for test results. It provides a standardized scale from None (no threat) to Critical (severe vulnerability) aligned with industry security standards and risk assessment frameworks.
The enumeration enables:
- Consistent threat classification across all tests
- Priority-based vulnerability triage
- Risk-based decision making
- Compliance with security reporting standards
ThreatLevel enumeration constants representing increasing levels of security concern. These levels align with CVSS severity ratings and common security frameworks.
Level definitions:
- None (0): No security issues detected, configuration meets best practices
- Info (1): Informational findings, no immediate security impact
- Low (2): Minor security issues with low exploitability or impact
- Medium (3): Moderate security concerns requiring attention
- High (4): Serious vulnerabilities with significant security impact
- Critical (5): Severe vulnerabilities requiring immediate remediation
const (
None ThreatLevel = iota // 0 - No security issues
Info // 1 - Informational findings
Low // 2 - Low severity issues
Medium // 3 - Medium severity issues
High // 4 - High severity vulnerabilities
Critical // 5 - Critical vulnerabilities
)
func evaluateCSPThreatLevel¶
evaluateCSPThreatLevel determines the threat level based on CSP analysis
func evaluateCookieThreatLevel¶
evaluateCookieThreatLevel determines threat level based on analysis
func evaluateCrossOriginThreatLevel¶
evaluateCrossOriginThreatLevel determines the security threat level based on cross-origin headers configuration and their security implications.
Parameters:
- metadata: Analyzed cross-origin headers metadata
Returns:
- ThreatLevel: Security threat level based on configuration
func evaluateHSTSThreatLevel¶
evaluateHSTSThreatLevel determines the security threat level based on HSTS configuration quality. It applies industry best practices and security standards to classify the HSTS implementation strength.
Threat level classification:
-
None (0): Excellent configuration
-
max-age ≥ 1 year (31,536,000 seconds)
-
includeSubDomains present
-
preload present
-
Meets HSTS preload list requirements
-
Maximum protection against protocol downgrade attacks
-
Info (1): Good configuration
-
max-age ≥ 1 year
-
includeSubDomains present
-
Strong protection, but not preload-eligible
-
Low (2): Acceptable configuration
-
max-age ≥ 6 months (15,552,000 seconds)
-
Provides reasonable protection
-
Should consider increasing max-age
-
Medium (3): Weak configuration
-
max-age present but \< 6 months
-
Limited protection window
-
Requires frequent policy refreshes
-
Vulnerable during gaps
-
High (4): Invalid or critically weak
-
max-age = 0 or missing
-
HSTS effectively disabled
-
No protection against protocol downgrades
Security standards reference:
- OWASP recommends minimum max-age of 1 year
- HSTS preload list requires: max-age ≥ 1 year + includeSubDomains + preload
- RFC 6797 specifies HSTS behavior and directives
Parameters:
- metadata: Parsed HSTS header metadata from analyzeHSTSHeader
Returns:
- ThreatLevel: Security classification (None, Info, Low, Medium, or High)
Example:
metadata := map[string]interface{}{
"max_age": 31536000,
"include_subdomains": true,
"preload": true,
}
level := evaluateHSTSThreatLevel(metadata) // Returns: None (Excellent)
func evaluateObfuscationThreat¶
evaluateObfuscationThreat determines threat level
func evaluatePermissionsPolicyThreatLevel¶
evaluatePermissionsPolicyThreatLevel determines the security threat level based on Permissions-Policy configuration.
func evaluateReferrerPolicyThreatLevel¶
evaluateReferrerPolicyThreatLevel determines the security threat level based on Referrer-Policy configuration quality. It applies privacy and security best practices to classify the referrer policy implementation strength.
Threat level classification:
-
None (0): Excellent configuration
-
strict-origin-when-cross-origin (W3C recommended)
-
strict-origin (strong privacy)
-
no-referrer (maximum privacy)
-
Info (1): Good configuration
-
origin-when-cross-origin (reasonable balance)
-
origin (basic privacy protection)
-
Low (2): Acceptable configuration
-
same-origin (limited privacy protection)
-
Medium (3): Weak configuration
-
no-referrer-when-downgrade (browser default)
-
Multiple conflicting policies
-
Configurations relying solely on browser default behavior
-
High (4): Vulnerable configuration
-
unsafe-url (always sends full URL)
-
Invalid/unrecognized policies only
-
Malformed header
The assessment considers:
- Privacy protection level
- Information leakage potential
- Cross-origin data exposure
- Protocol downgrade behavior
- Policy conflicts and precedence
Parameters:
- metadata: Parsed referrer policy metadata from analyzeReferrerPolicyHeader
Returns:
- ThreatLevel: Security classification (None, Info, Low, Medium, or High)
Example:
metadata := map[string]interface{}{
"effective_policy": "strict-origin-when-cross-origin",
"has_unsafe": false,
}
level := evaluateReferrerPolicyThreatLevel(metadata)
// Returns: None (excellent configuration)
func evaluateServerExposureThreatLevel¶
evaluateServerExposureThreatLevel calculates the security threat level based on server header information disclosure and known vulnerabilities.
This function implements a sophisticated threat assessment algorithm that combines:
- Quantitative exposure analysis (number of headers revealing information)
- CVE vulnerability assessment from NIST NVD database
- Heuristic pattern matching for high-risk configurations
Three-Layer Assessment:
Layer 1: Base Threat (Exposure Count)
- 0 exposures → None: No information disclosed
- 1-2 exposures → Info: Minimal disclosure
- 3-4 exposures → Low: Moderate disclosure
- 5+ exposures → Medium: Extensive disclosure
Layer 2: CVE Enhancement (Vulnerability Database)
- Query NIST NVD for each detected technology
- Assess CVE severity levels (High/Medium/Low)
- Map CVE severity to threat levels:
- High severity CVE present → Critical
- 6+ medium severity CVEs → High
- 1-5 medium severity CVEs → Medium
- 11+ low severity CVEs → Medium
- 1-10 low severity CVEs → Low
Layer 3: Heuristic Enhancement (Risk Patterns)
- Debug/test/dev identifiers → Critical
- Common web servers (Apache/Nginx/IIS) → High
Priority Logic:
The function uses maximum threat level logic - if any layer identifies a higher threat, that level becomes the final assessment. This ensures critical vulnerabilities are never downgraded.
CVE Integration:
For each detected technology, the function:
- Creates CVE client instance
- Queries NIST NVD API with technology name
- Receives vulnerability assessment with severity counts
- Maps CVE severity to our ThreatLevel enum
- Updates threat level if higher than current assessment
Parameters:
- analysis: ServerHeaderAnalysis containing exposure and technology data
Returns:
- ThreatLevel: Final calculated threat level (None/Info/Low/Medium/High/Critical)
Example:
// Minimal exposure, no CVEs
analysis := &ServerHeaderAnalysis{
total_exposures: 1,
technologies: []string{"Cloudflare"},
}
level := evaluateServerExposureThreatLevel(analysis)
// Returns: Info
// Multiple exposures with vulnerable technology
analysis := &ServerHeaderAnalysis{
total_exposures: 5,
technologies: []string{"Apache", "PHP"}, // Has known CVEs
}
level := evaluateServerExposureThreatLevel(analysis)
// Returns: Critical (due to CVE assessment)
// Debug environment exposed
analysis := &ServerHeaderAnalysis{
total_exposures: 2,
technologies: []string{"Express-debug"},
}
level := evaluateServerExposureThreatLevel(analysis)
// Returns: Critical (heuristic match)
Security Context:
The threat level indicates:
- Critical: Immediate remediation required (CVE High or debug exposed)
- High: Significant risk (common servers or multiple medium CVEs)
- Medium: Moderate risk (multiple exposures or some CVEs)
- Low: Minor risk (few exposures, low-severity CVEs)
- Info: Informational (minimal exposure, no vulnerabilities)
- None: Secure configuration (no disclosure)
func evaluateXContentTypeOptionsThreatLevel¶
evaluateXContentTypeOptionsThreatLevel determines the security threat level
func mapCVEThreatLevel¶
mapCVEThreatLevel maps CVE vulnerability assessment results from the NIST NVD database to the Engine-AntiGinx ThreatLevel enumeration.
This function translates CVSS (Common Vulnerability Scoring System) severity classifications into our internal threat level system, enabling consistent risk assessment across different vulnerability sources.
CVSS to ThreatLevel Mapping:
High Severity CVEs:
- Any high-severity vulnerability → Critical
- Rationale: High-severity CVEs (CVSS 7.0-10.0) indicate serious vulnerabilities requiring immediate attention
Medium Severity CVEs:
- 6+ medium-severity vulnerabilities → High
- 1-5 medium-severity vulnerabilities → Medium
- Rationale: Multiple medium vulnerabilities (CVSS 4.0-6.9) compound risk and warrant elevated threat levels
Low Severity CVEs:
- 11+ low-severity vulnerabilities → Medium
- 1-10 low-severity vulnerabilities → Low
- Rationale: Large numbers of low-severity issues (CVSS 0.1-3.9) indicate poor maintenance and potential security debt
No Vulnerabilities:
- CVE count > 0 but no severity classified → Info
- CVE count = 0 → None
- Rationale: Presence in CVE database warrants awareness
Priority Logic:
The function uses a cascading if-else structure that prioritizes higher severity findings. Once a match is found, lower severity checks are skipped.
Parameters:
- assessment: VulnerabilityAssessment structure from CVE client containing:
- CVECount: Total number of CVEs found
- HighSeverity: Count of high-severity vulnerabilities
- MediumSeverity: Count of medium-severity vulnerabilities
- LowSeverity: Count of low-severity vulnerabilities
Returns:
- ThreatLevel: Mapped threat level (None/Info/Low/Medium/High/Critical)
Example:
// High severity vulnerability present
assessment := CVE.VulnerabilityAssessment{
CVECount: 8,
HighSeverity: 2,
MediumSeverity: 4,
LowSeverity: 2,
}
level := mapCVEThreatLevel(assessment)
// Returns: Critical
// Multiple medium severity vulnerabilities
assessment := CVE.VulnerabilityAssessment{
CVECount: 7,
HighSeverity: 0,
MediumSeverity: 7,
LowSeverity: 0,
}
level := mapCVEThreatLevel(assessment)
// Returns: High
// Many low severity vulnerabilities
assessment := CVE.VulnerabilityAssessment{
CVECount: 15,
HighSeverity: 0,
MediumSeverity: 0,
LowSeverity: 15,
}
level := mapCVEThreatLevel(assessment)
// Returns: Medium
// No vulnerabilities found
assessment := CVE.VulnerabilityAssessment{
CVECount: 0,
HighSeverity: 0,
MediumSeverity: 0,
LowSeverity: 0,
}
level := mapCVEThreatLevel(assessment)
// Returns: None
Security Standards Alignment:
CVSS Severity Ranges:
- None: 0.0
- Low: 0.1-3.9
- Medium: 4.0-6.9
- High: 7.0-8.9
- Critical: 9.0-10.0
Related Functions:
- evaluateServerExposureThreatLevel(): Uses this function for CVE assessment
- CVE.AssessTechnologyVulnerabilities(): Provides assessment data
func (ThreatLevel) MarshalJSON¶
MarshalJSON implements custom JSON marshaling for ThreatLevel, converting the enumeration value to its string representation in JSON output. This ensures human-readable JSON instead of numeric values.
Without this method, ThreatLevel would serialize as integers (0, 1, 2, etc.). With this method, it serializes as strings ("None", "Info", "Low", etc.).
This is particularly important for:
- API responses that need to be human-readable
- Log files and reports
- Integration with external systems expecting string values
- Debugging and analysis
Returns:
- []byte: JSON-encoded string representation of the threat level
- error: Error from JSON marshaling (typically nil)
Example:
result := TestResult{
Name: "HTTPS Test",
ThreatLevel: High,
}
jsonData, _ := json.Marshal(result)
// Output includes: "ThreatLevel": "High" (not "ThreatLevel": 4)
func (ThreatLevel) String¶
String converts a ThreatLevel value to its human-readable string representation. This method implements the Stringer interface enabling automatic string conversion for logging, display, and debugging purposes.
String representations:
- None (0) → "None"
- Info (1) → "Info"
- Low (2) → "Low"
- Medium (3) → "Medium"
- High (4) → "High"
- Critical (5) → "Critical"
Returns:
- string: Human-readable threat level name
Panics:
- Errors.Error: If the ThreatLevel value is invalid/unknown
Example:
level := High
fmt.Println(level.String()) // Output: "High"
fmt.Printf("Threat: %v\n", level) // Output: "Threat: High"
Generated by gomarkdoc