Debugging & Logging - Code Analyzer
Static code analysis for security, performance, and best practices
Overview
The Code Analyzer is a static code analysis tool in ColdFusion Administrator that scans your CFML application code to identify potential issues, security vulnerabilities, performance problems, and violations of coding best practices. Unlike runtime debugging tools that analyze code during execution, the Code Analyzer examines your source files statically, without running the application.
This powerful tool helps maintain code quality, enforce coding standards, and prevent common issues before they reach production. The analyzer can detect various categories of problems including SQL injection vulnerabilities, inefficient queries, scope usage issues, deprecated functions, and much more.
Analysis Categories
Security Vulnerabilities
- SQL Injection: Detects unparameterized queries with user input
- Cross-Site Scripting (XSS): Identifies unescaped output of user data
- Path Traversal: Flags insecure file path operations
- Command Injection: Warns about unsafe cfexecute usage
- Insecure Deserialization: Identifies risky evaluate() or deserialize() usage
- Information Disclosure: Flags cfdump in production code, error details exposure
Performance Issues
- N+1 Query Problems: Detects queries inside loops
- Missing cfqueryparam: Identifies queries without parameterization (performance and security)
- Inefficient Loops: Flags performance-draining loop patterns
- Scope Issues: Identifies inefficient variable scope usage
- Query of Queries: Flags potentially inefficient QoQ operations
- Large Result Sets: Warns about queries without maxrows or pagination
Best Practice Violations
- Deprecated Functions: Lists usage of deprecated CFML functions or tags
- Var Scoping: Identifies missing var declarations in functions
- Output Directives: Flags missing or incorrect cfoutput usage
- Error Handling: Detects missing or overly broad try/catch blocks
- Component Design: Identifies CFCs without proper initialization
- Naming Conventions: Warns about non-standard naming patterns
Code Quality Metrics
- Cyclomatic Complexity: Measures code complexity and branching
- Function Length: Identifies overly long functions
- Code Duplication: Detects repeated code blocks
- Dead Code: Identifies unreachable or unused code
- Comment Density: Measures code documentation
Running the Code Analyzer
Configuration
- Directory Selection: Specify root directory to analyze
- Recursive Scanning: Include subdirectories in analysis
- File Types: .cfm, .cfc, .cfml files automatically included
- Exclusions: Exclude vendor code, third-party libraries
- Rule Selection: Choose which rules to enable (security, performance, best practices)
- Severity Levels: Configure thresholds for error, warning, info
Execution Process
- Initiation: Start analysis from Administrator interface
- Background Processing: Analysis runs without blocking administrator
- Progress Tracking: Shows files processed and issues found
- Duration: Depends on codebase size (minutes for large applications)
- Resource Usage: Minimal server impact, CPU-bound operation
Report Generation
- Automatic: Report generated upon completion
- Format Options: HTML, PDF, XML, CSV
- Categorization: Issues grouped by severity, category, file
- Code Snippets: Shows problematic code with line numbers
- Recommendations: Provides fix suggestions for each issue
Interpreting Results
Severity Levels
- Critical: Security vulnerabilities requiring immediate attention
- High: Significant performance or security issues
- Medium: Best practice violations, moderate issues
- Low: Minor style or convention violations
- Informational: Suggestions for improvement
False Positives
- Common Occurrence: Static analysis may flag legitimate code patterns
- Review Required: Manually verify each reported issue
- Context Matters: Analyzer may miss security mitigations in surrounding code
- Suppression: Some tools allow suppressing specific warnings
- Whitelist: Configure known-safe patterns to reduce noise
Prioritization
- Security First: Address all critical security vulnerabilities
- High Impact: Fix high-severity issues in frequently used code
- Quick Wins: Easy fixes that provide immediate benefit
- Technical Debt: Lower priority items for future refactoring
- Team Discussion: Review findings with development team
Common Security Issues Detected
SQL Injection
- Pattern: Queries built with string concatenation of user input
- Example: <cfquery>SELECT * FROM users WHERE id = #url.id#</cfquery>
- Fix: Use cfqueryparam for all dynamic values
- Impact: Critical - allows database compromise
Cross-Site Scripting (XSS)
- Pattern: User input output without HTMLEditFormat() or similar
- Example: <cfoutput>#form.username#</cfoutput>
- Fix: Always escape output: <cfoutput>#HTMLEditFormat(form.username)#</cfoutput>
- Impact: High - enables session hijacking, malware injection
Insecure File Operations
- Pattern: File operations with unvalidated user input
- Example: <cffile action="read" file="#url.filename#">
- Fix: Validate and sanitize file paths, use whitelists
- Impact: Critical - allows reading arbitrary server files
Evaluate() Usage
- Risk: Dynamic code execution enables injection attacks
- Pattern: evaluate(userInput) or similar constructs
- Fix: Use bracket notation or proper structures instead
- Impact: Critical - allows arbitrary code execution
Common Performance Issues Detected
Queries in Loops
- Pattern: cfquery inside cfloop
- Impact: N+1 query problem causing severe performance degradation
- Fix: Use JOIN clauses or query entire dataset once
- Performance Gain: Often 10-100x improvement
Missing cfqueryparam
- Impact: Both security and performance issues
- Performance: Prevents query plan caching
- Security: Enables SQL injection
- Fix: Always use cfqueryparam for dynamic values
Unscoped Variables
- Pattern: Variable references without scope prefix
- Impact: CF must search all scopes, slowing execution
- Fix: Always scope variables (local.var, variables.var, etc.)
- Performance: 5-15% improvement in function execution
Large Session/Application Objects
- Pattern: Storing large objects in session or application scope
- Impact: Memory consumption, serialization overhead
- Fix: Cache only necessary data, use external caching for large objects
Integration with CI/CD
Automated Analysis
- Pre-Commit Hooks: Run analyzer before allowing commits
- Build Pipeline: Include code analysis in CI/CD pipeline
- Quality Gates: Fail builds if critical issues found
- Trend Tracking: Monitor code quality metrics over time
Command Line Integration
- Scriptable: Some analyzers provide CLI interfaces
- Exit Codes: Return non-zero on critical issues
- Report Formats: XML or JSON for parsing by build tools
- Thresholds: Configure acceptable issue counts
Continuous Monitoring
- Regular Scans: Schedule automatic analysis (daily/weekly)
- Delta Reports: Show only new issues since last scan
- Email Notifications: Alert team of new critical issues
- Dashboard Integration: Display metrics in team dashboards
Best Practices
Development Workflow
- Run code analyzer before committing code
- Address all critical and high-severity issues
- Review medium-severity issues and fix when practical
- Document decisions to accept certain warnings
- Use analyzer findings to educate junior developers
- Establish team coding standards based on analysis
Initial Analysis
- Expect many issues in first analysis of existing codebase
- Prioritize security vulnerabilities above all else
- Create remediation plan with timeline
- Fix issues in batches by category or severity
- Track progress and celebrate improvements
- Use findings to justify technical debt reduction
Ongoing Usage
- Integrate into regular development process
- Run analysis on every release branch
- Set quality gates: no critical issues allowed in production
- Review reports during code reviews
- Update analyzer rules as new patterns emerge
- Share analysis reports with stakeholders
Configuration and Tuning
- Start with all rules enabled to understand codebase
- Disable rules generating excessive false positives
- Customize severity levels based on team priorities
- Create custom rules for organization-specific patterns
- Document rule configuration and rationale
- Review and update rules quarterly
Common Issues and Solutions
Analysis Takes Too Long
- Symptom: Code analysis runs for hours or times out
- Cause: Very large codebase, complex rules
- Solution: Analyze smaller directory trees separately
- Optimization: Exclude vendor code and libraries
- Alternative: Use incremental analysis of changed files only
Too Many False Positives
- Symptom: Majority of reported issues are not actual problems
- Cause: Overly aggressive rules, analyzer limitations
- Solution: Tune rules, adjust severity thresholds
- Whitelist: Configure known-safe patterns
- Manual Review: Always verify before dismissing warnings
Missing Known Issues
- Symptom: Analyzer doesn't detect issues you know exist
- Cause: Limited rule set, dynamic code complexity
- Expectations: No static analyzer catches 100% of issues
- Complement: Use manual code reviews and penetration testing
- Updates: Keep analyzer updated to latest version
Report Difficult to Navigate
- Symptom: Thousands of issues in unorganized report
- Solution: Use filtering and sorting features
- Focus: Address by severity, then by file or category
- Export: Export to CSV for custom analysis in Excel
- Incremental: Fix issues in manageable batches
Third-Party Code Analyzers
CFLint
- Type: Open-source CFML linter
- Features: Configurable rules, command-line interface
- Integration: Works with build tools, IDEs
- Customization: Extensible rule system
- Community: Active development and rule contributions
Fixinator
- Type: Commercial security scanner for ColdFusion
- Focus: Security vulnerability detection
- Features: Detailed remediation guidance
- Integration: CI/CD pipeline support
- Updates: Regular rule updates for new vulnerabilities
SonarQube
- Type: Multi-language code quality platform
- CFML Support: Via community plugins
- Features: Historical tracking, dashboards, technical debt
- Integration: Enterprise CI/CD integration
- Scalability: Suitable for large organizations
Report Example Categories
Executive Summary
- Total files analyzed
- Total issues found by severity
- Security vulnerability count
- Performance issue count
- Code quality score
- Trend compared to previous scans
Critical Issues
- SQL injection vulnerabilities
- XSS vulnerabilities
- Insecure file operations
- Command injection risks
- Authentication bypasses
Performance Warnings
- N+1 query problems
- Missing query parameterization
- Unscoped variable access
- Inefficient loops
- Large object storage
Best Practice Violations
- Deprecated function usage
- Missing var declarations
- Poor error handling
- Code duplication
- Complex functions
Related Resources
- Debugging & Logging - License Scanner - Feature usage analysis
- Debugging & Logging - Debug Output Settings - Runtime debugging
- Security - Sandbox Security - Runtime security controls
- ColdFusion Administrator Reference - Main administrator guide