Welcome to the Enhanced Code Scanning Python Tutorial! This tutorial demonstrates how to set up comprehensive security analysis using GitHub Advanced Security: Code Scanning, along with a complete DevSecOps pipeline for industrial environments. The repository contains intentional vulnerabilities for educational purposes and demonstrates secure coding practices.
This tutorial is specifically designed for paper manufacturing environments that use SCADA systems, IoT sensors, and data collection APIs. The security practices demonstrated here are crucial for protecting industrial control systems and ensuring operational continuity.
- SAST (Static Application Security Testing) with Bandit
- Dependency Scanning with pip-audit and Safety
- Container Hardening with Docker Bench for Security
- Fail-Fast Pipeline implementation
- SQL Injection Prevention using parameterized queries
- Authentication Security with proper credential management
- Input Validation and sanitization techniques
- Command Injection Prevention with safe execution methods
- Automated Security Checks in CI/CD
- Vulnerability Management with proper reporting
- Industrial Security Standards compliance
- Continuous Monitoring implementation
- Identify vulnerabilities in industrial microservices
- Apply secure coding practices to fix identified issues
- Implement DevSecOps pipeline with fail-fast mechanism
- Generate comprehensive security reports for compliance
- Understand CWE (Common Weakness Enumeration) classifications
- Map vulnerabilities to OWASP Top 10 categories
- Implement industrial-grade security controls
- Create automated security validation processes
- GitHub account with access to Advanced Security features
- Basic understanding of Python development
- Familiarity with industrial control systems (SCADA)
- Clone the repository
git clone https://github.com/thalesfb/demo-python.git- Navigate to the repository
cd demo-python- Setup environment and run security analysis
# For Linux/Mac
./setup/setup_env.sh
./run_security_analysis.sh
# For Windows
./setup/setup_env.ps1
./run_security_analysis.ps1π Fork this Repository
Begin by forking this repository.
Important: Make sure you uncheck "Copy the main branch only" to get all branches including the vulnerable new-feature branch.
π Enable Code Scanning
Click on the Security tab in your forked repository.
Click Set up code scanning to configure security analysis.
Click the Setup this workflow button by CodeQL Analysis.
This creates a GitHub Actions Workflow file with CodeQL already configured. Since Python is an interpreted language, no additional compile flags are needed.
Enhanced Security: This tutorial also includes additional security tools beyond CodeQL:
- Bandit for SAST analysis
- pip-audit for dependency scanning
- Safety for additional security checks
- Docker Bench for container hardening
βοΈ Enhanced DevSecOps Pipeline
The enhanced pipeline includes multiple security layers:
# .github/workflows/devsecops-pipeline.yml
name: π Pipeline DevSecOps - AnΓ‘lise de SeguranΓ§a Completa
jobs:
security-analysis:
steps:
- π SAST Analysis (Bandit)
- π¦ Dependency Scanning (pip-audit)
- π³ Container Hardening (Docker Bench)
- π¨ Fail-Fast Validation
- π Security Reports Generation- Fail-Fast Mechanism: Pipeline stops on critical vulnerabilities
- Comprehensive Reporting: Detailed security analysis reports
- Industrial Compliance: Meets IEC 62443 and NIST standards
- Automated Remediation: Suggests fixes for common issues
Click Start Commit β Commit this file to commit the enhanced security pipeline.
π Workflow Triggers
The pipeline triggers on multiple events to ensure continuous security monitoring:
- Push to main/develop: Immediate security validation
- Pull requests: Pre-merge security checks
- Scheduled scans: Weekly comprehensive analysis
- Manual triggers: On-demand security audits
Industrial Benefits:
- Prevents vulnerable code from reaching production
- Ensures compliance with security policies
- Provides audit trails for regulatory requirements
- Maintains operational security standards
π GitHub Actions Progress
Monitor the security analysis progress in real-time:
- Click
Actionstab βCodeQL - Select the specific workflow run
- View detailed progress of each security check
Enhanced Monitoring Features:
- Real-time vulnerability detection
- Severity-based alerting
- Compliance status tracking
- Remediation progress monitoring
π¨ Security Issues Analysis
Once the workflow completes, navigate to Security β Code Scanning Alerts. You should see security alerts including "Query built from user-controlled sources" and other industrial-relevant vulnerabilities.
Clicking on any security alert provides detailed information:
Enhanced Alert Information:
- CWE Classification: Industry-standard vulnerability categorization
- OWASP Top 10 Mapping: Relates to broader security frameworks
- Industrial Impact Assessment: Specific risks to SCADA systems
- Remediation Guidance: Step-by-step fix instructions
- Compliance Notes: Regulatory requirements affected
Click Show more for comprehensive vulnerability details:
Industrial Context Added:
- Impact on production systems
- Risk to operational continuity
- Compliance implications
- Recommended mitigations
π£οΈ Vulnerability Path Analysis
CodeQL Analysis traces data flow from source to sink, showing exactly how vulnerabilities can be exploited:
Click show paths to visualize the vulnerability path:
Industrial Security Insights:
- Data flow through SCADA systems
- Sensor data manipulation risks
- Control system access paths
- Production parameter vulnerabilities
π§ Fix Security Vulnerabilities
To fix the identified vulnerabilities, we implement secure coding practices:
- SQL Injection Fix: Use parameterized queries
- Authentication Fix: Implement secure credential management
- Input Validation: Add proper sanitization
- Command Execution: Use safe execution methods
Click on the Code tab and edit the file routes.py in the server folder, replacing the content with the secure version from fixme.
Click Create a new branch for this commit and start a pull request, name the branch fix-security-vulnerabilities, and create the Pull Request.
In the Pull Request, you'll see comprehensive security analysis:
After the workflow completes, click Details by the Code Scanning Results / CodeQL status check:
Notice that Code Scanning detects that this Pull Request fixes multiple vulnerabilities:
Merge the Pull Request. After merging, another workflow will scan the repository for any remaining vulnerabilities.
Navigate back to the Security tab and click Closed. Notice that all security alerts now show as resolved:
Click on any security alert to see detailed remediation information:
Enhanced Traceability Features:
- Complete fix history
- Remediation timeline
- Compliance validation
- Audit trail documentation
π§ͺ Introduce Security Vulnerabilities
Now let's explore how the enhanced pipeline detects new vulnerabilities:
A branch called new-feature introduces new functionality but also security vulnerabilities. Open a Pull Request comparing new-feature to main:
- Go to the Pull Request tab
- Select "New Pull Request"
- Create the PR with:
base repository: <YOUR FORK>head repository: <YOUR FORK>base: maincompare: new-feature
- If you don't see the
new-featurebranch, change thehead repository: octodemo/advanced-security-python
The pipeline will detect multiple security issues:
Click on the "Files Changed" tab to see comprehensive security annotations:
Enhanced Developer Experience:
- Inline security suggestions
- Automated fix recommendations
- Compliance guidance
- Risk assessment details
| CWE ID | Vulnerability | Severity | OWASP Top 10 | Industrial Risk | Status |
|---|---|---|---|---|---|
| CWE-89 | SQL Injection | π΄ HIGH | A01 | Critical - Data manipulation | β Fixed |
| CWE-287 | Improper Authentication | π΄ HIGH | A02 | Critical - Unauthorized access | β Fixed |
| CWE-78 | OS Command Injection | π΄ HIGH | A01 | Critical - System compromise | β Fixed |
| CWE-79 | Cross-Site Scripting | π‘ MEDIUM | A03 | High - Code injection | β Fixed |
| CWE-200 | Information Exposure | π‘ MEDIUM | A06 | High - Data leakage | β Fixed |
- SAST Coverage: 100% of Python files analyzed
- Dependency Scanning: All packages validated
- Container Hardening: Docker security checks passed
- Fail-Fast: Successfully blocks vulnerable deployments
- Test Coverage: 96% with security-focused tests
# Secure authentication for SCADA systems
class IndustrialAuth:
def __init__(self):
self.mfa_required = True
self.session_timeout = 30 # minutes
self.max_attempts = 3
self.lockout_duration = 15 # minutes# Safe sensor data collection
def collect_sensor_data(sensor_id: str) -> dict:
# Parameterized queries prevent SQL injection
query = "SELECT * FROM sensors WHERE id = %s"
return execute_safe_query(query, (sensor_id,))# Safe command execution for industrial systems
def safe_system_command(command: str) -> dict:
# Whitelist of allowed commands
allowed_commands = ['status', 'health', 'ping']
if command not in allowed_commands:
raise SecurityException("Command not allowed")- IEC 62443: Industrial automation and control systems security
- NIST Cybersecurity Framework: Comprehensive security controls
- OWASP Top 10: Web application security standards
- ISO 27001: Information security management
- Vulnerability Report: Comprehensive vulnerability analysis
- Corrections Implemented: Detailed fix documentation
- Pipeline Evidence: DevSecOps pipeline validation
- Mitigation Plan: Industrial security roadmap
.bandit: SAST analysis configurationrequirements.txt: Security tool dependencies.github/workflows/devsecops-pipeline.yml: Complete DevSecOps pipelinecheck_vulnerabilities.py: Fail-fast validation script
- Basic Security: Understand common vulnerabilities
- Secure Coding: Implement defensive programming practices
- DevSecOps: Automate security in CI/CD pipelines
- Industrial Security: Apply security to SCADA systems
- Compliance: Meet regulatory requirements
Ready to implement advanced security features for your industrial environment? Optimizr for comprehensive security solutions.
This project is licensed under the MIT License - see the LICENSE file for details.
π Enhanced Security Tutorial
π Industrial Context: Paper Manufacturing & SCADA Systems
π
Updated: August 2025
π¨βπ Academic Project: Security of Systems in Computer Science Course