### Serve MkDocs Documentation Locally Source: https://github.com/owasp/devguide/blob/main/contributing.md Starts a local development server to preview the OWASP Developer Guide. Changes to the documentation will be reflected live after saving. ```text python3 -m mkdocs serve ``` -------------------------------- ### Install MkDocs and Plugins Source: https://github.com/owasp/devguide/blob/main/contributing.md Installs MkDocs and necessary plugins for building the OWASP Developer Guide documentation locally. Ensure Python and pip are installed first. ```text python3 -m pip install mkdocs python3 -m pip install mkdocs-material python3 -m pip install mkdocs-open-in-new-tab python3 -m pip install mkdocs-redirects python3 -m pip install mkdocs-with-pdf ``` -------------------------------- ### Download and Install Dependency-Check Source: https://context7.com/owasp/devguide/llms.txt Download the release zip file and extract it to install Dependency-Check. This is the initial setup step for command-line usage. ```bash wget https://github.com/jeremylong/DependencyCheck/releases/download/v9.0.0/dependency-check-9.0.0-release.zip unzip dependency-check-9.0.0-release.zip ``` -------------------------------- ### Install MkDocs and Plugins Source: https://github.com/owasp/devguide/blob/main/contributing.md Install necessary Python packages for MkDocs using pip. These are required for building and serving the documentation. ```text pip install mkdocs pip install mkdocs-material pip install mkdocs-open-in-new-tab pip install mkdocs-redirects pip install mkdocs-with-pdf ``` -------------------------------- ### Generate DFD, Sequence Diagram, and Report with pytm Source: https://github.com/owasp/devguide/blob/main/docs/en/04-design/01-threat-modeling/02-pytm.md This example demonstrates how to use the pytm script to generate a data flow diagram (DFD), a sequence diagram, and a threat modeling report. It requires Graphviz, Java, PlantUML, and pandoc to be installed and configured. ```text mkdir -p tm ./tm.py --report docs/basic_template.md | pandoc -f markdown -t html > tm/report.html ./tm.py --dfd | dot -Tpng -o tm/dfd.png ./tm.py --seq | java -Djava.awt.headless=true -jar $PLANTUML_PATH -tpng -pipe > tm/seq.png ``` -------------------------------- ### Example Usage of SecureDataManager Source: https://context7.com/owasp/devguide/llms.txt Demonstrates how to initialize the SecureDataManager and define a list of sensitive fields for a user record. This setup is necessary before encrypting or decrypting user data. ```python # Example usage data_manager = SecureDataManager() # Define which fields are sensitive user_fields = [ SensitiveField("username", DataClassification.INTERNAL), SensitiveField("email", DataClassification.CONFIDENTIAL), SensitiveField("ssn", DataClassification.RESTRICTED), SensitiveField("credit_card", DataClassification.RESTRICTED) ] ``` -------------------------------- ### User Registration and Authentication Example Source: https://context7.com/owasp/devguide/llms.txt Demonstrates registering a user and then authenticating them with provided credentials and session details. Ensure strong password policies are enforced. ```python auth = SecureAuthManager() # Register user user = auth.register_user("john_doe", "SecureP@ssw0rd123!") # Authenticate session = auth.authenticate( "john_doe", "SecureP@ssw0rd123!", ip_address="192.168.1.1", user_agent="Mozilla/5.0..." ) if session: print(f"Session created: {session.session_id[:16]}...") # Validate session on subsequent requests valid = auth.validate_session(session.session_id, "192.168.1.1") if valid: print("Session is valid") ``` -------------------------------- ### Scan Dependencies with OWASP Dependency-Check Source: https://context7.com/owasp/devguide/llms.txt Example command to initiate a vulnerability scan on project dependencies using OWASP Dependency-Check from the command line. ```bash # Example: Using OWASP Dependency-Check from command line ``` -------------------------------- ### Install Markdownlint-cli2 Source: https://github.com/owasp/devguide/blob/main/contributing.md Install the markdownlint-cli2 tool globally using npm. This is used for linting markdown files. ```bash npm install markdownlint-cli2 --global ``` -------------------------------- ### Install and Run OWASP Juice Shop with Docker Source: https://github.com/owasp/devguide/blob/main/docs/en/07-training-education/01-vulnerable-apps/01-juice-shop.md Use these Docker commands to pull the Juice Shop image and run it. Access the application via your browser at http://localhost:3000. ```text docker pull bkimminich/juice-shop docker run --rm -p 3000:3000 bkimminich/juice-shop ``` -------------------------------- ### Build PDF Export for Spanish Documentation Source: https://github.com/owasp/devguide/blob/main/contributing.md Generates a PDF export of the Spanish version of the OWASP Developer Guide using the specified configuration file. ```text python3 -m mkdocs build --config-file mkdocs-pdf-es.yaml ``` -------------------------------- ### Protected Endpoint Example Source: https://context7.com/owasp/devguide/llms.txt Demonstrates applying multiple security decorators to an endpoint. This example combines authentication, role checking, rate limiting, and input validation for a robustly protected function. ```python # Example: Protected endpoint with multiple security layers @require_authentication @require_role(["admin", "manager"]) @rate_limit(max_requests=50, window_seconds=60) @validate_input def update_user_record(ctx: SecurityContext, data: dict) -> dict: """Update user record with defense in depth protection""" # Business logic here - all security checks passed return {"status": "success", "updated_by": ctx.user_id} ``` -------------------------------- ### Run Dependency-Check from Command Line Source: https://github.com/owasp/devguide/blob/main/docs/en/05-implementation/02-dependencies/01-dependency-check.md Execute Dependency-Check from the command line to scan a project and generate a report. Ensure Java is installed and the tool is downloaded and unzipped. ```bash ./dependency-check.sh --project "Threat Dragon" --scan ~/github/threat-dragon ``` -------------------------------- ### Example Usage of Secure Endpoint Decorator Source: https://context7.com/owasp/devguide/llms.txt Demonstrates how to use the `@secure_endpoint` decorator with a function that simulates payment processing. This example shows how exceptions raised within the decorated function are caught and handled by the decorator. ```python # Example usage @secure_endpoint(ErrorCode.INTERNAL_ERROR) def process_payment(user_id: str, amount: float, card_number: str): """Process payment - errors handled securely""" if amount <= 0: raise ValueError("Invalid payment amount") if not user_id: raise PermissionError("User authentication required") # Simulate processing error raise RuntimeError("Payment gateway timeout") # Test the secure error handling response = process_payment( user_id="user123", amount=99.99, card_number="4111111111111111" ) print(f"Error Code: {response.error_code}") print(f"Message: {response.message}") print(f"Reference: {response.reference_id}") # Output: Safe generic message with reference ID for support ``` -------------------------------- ### SecurityContext Usage Example Source: https://context7.com/owasp/devguide/llms.txt Illustrates how to instantiate and use a SecurityContext object for passing user and request information to protected functions. ```python # Usage ctx = SecurityContext(user_id="user123", roles=["manager"], ip_address="192.168.1.1") result = update_user_record(ctx, {"name": "John Doe", "email": "john@example.com"}) ``` -------------------------------- ### Build PDF Export for Brazilian Portuguese Documentation Source: https://github.com/owasp/devguide/blob/main/contributing.md Generates a PDF export of the Brazilian Portuguese version of the OWASP Developer Guide using the specified configuration file. ```text python3 -m mkdocs build --config-file mkdocs-pdf-pt-br.yaml ``` -------------------------------- ### Building Safe HTML Output Example Source: https://context7.com/owasp/devguide/llms.txt Demonstrates how to use the OutputEncoder class to safely construct HTML output by encoding user-provided input for different parts of the HTML structure (content, attributes, and JavaScript). ```python import html import urllib.parse import json import re from typing import Any class OutputEncoder: """Contextual output encoding for different target systems""" @staticmethod def html_encode(data: str) -> str: """Encode for HTML content - prevents XSS""" return html.escape(data, quote=True) @staticmethod def html_attribute_encode(data: str) -> str: """Encode for HTML attributes - more restrictive""" # Only allow alphanumeric, encode everything else return ''.join( c if c.isalnum() else f'&#x{ord(c):02x};' for c in data ) @staticmethod def javascript_encode(data: str) -> str: """Encode for JavaScript string context""" replacements = { '\': '\\', "'": "\'", '"': '"', '\n': '\n', '\r': '\r', '\t': '\t', '<': '\x3c', '>': '\x3e', '&': '\x26' } for char, replacement in replacements.items(): data = data.replace(char, replacement) return data @staticmethod def url_encode(data: str) -> str: """Encode for URL parameters""" return urllib.parse.quote(data, safe='') @staticmethod def json_encode(data: Any) -> str: """Encode for JSON output""" return json.dumps(data, ensure_ascii=True) @staticmethod def sql_identifier_encode(identifier: str) -> str: """ Encode SQL identifier (table/column names). Note: Always use parameterized queries for values! """ # Remove any characters that aren't alphanumeric or underscore safe_identifier = re.sub(r'[^a-zA-Z0-9_]', '', identifier) if not safe_identifier or safe_identifier[0].isdigit(): raise ValueError("Invalid SQL identifier") return f'"{safe_identifier}"' @staticmethod def ldap_encode(data: str) -> str: """Encode for LDAP filter to prevent injection""" replacements = { '\': '\5c', '*': '\2a', '(': '\28', ')': '\29', '\x00': '\00' } for char, replacement in replacements.items(): data = data.replace(char, replacement) return data @staticmethod def shell_encode(data: str) -> str: """ Encode for shell commands. WARNING: Avoid shell commands with user input when possible! """ # Only allow safe characters, reject everything else if not re.match(r'^[a-zA-Z0-9._-]+$', data): raise ValueError("Input contains unsafe characters for shell") return data # Example: Building safe HTML output encoder = OutputEncoder() user_input = '' user_url = 'https://example.com/search?q=test&page=1' user_name = "O'Brien" # Safe HTML content html_output = f"""

{encoder.html_encode(user_input)}

Link
" print(html_output) # Output will have encoded dangerous characters, preventing XSS ``` ``` -------------------------------- ### Implement CIA Triad Principles in Python Source: https://context7.com/owasp/devguide/llms.txt Demonstrates encryption for confidentiality, hashing for integrity, and logging for auditing in a Python web application. Ensure necessary libraries are installed. ```python # Example: Implementing CIA principles in a Python web application from cryptography.fernet import Fernet from functools import wraps import hashlib import logging import datetime # CONFIDENTIALITY: Encrypt sensitive data at rest class DataEncryption: def __init__(self): self.key = Fernet.generate_key() self.cipher = Fernet(self.key) def encrypt_sensitive_data(self, plaintext: str) -> bytes: """Encrypt data before storage""" return self.cipher.encrypt(plaintext.encode()) def decrypt_sensitive_data(self, ciphertext: bytes) -> str: """Decrypt data only when needed""" return self.cipher.decrypt(ciphertext).decode() # INTEGRITY: Verify data has not been tampered with def compute_integrity_hash(data: str) -> str: """Create hash to verify data integrity""" return hashlib.sha256(data.encode()).hexdigest() def verify_integrity(data: str, expected_hash: str) -> bool: """Verify data matches expected hash""" return compute_integrity_hash(data) == expected_hash # AUDITING: Log security-relevant events logging.basicConfig(level=logging.INFO) audit_logger = logging.getLogger('security_audit') def audit_log(action: str, user: str, resource: str, outcome: str): """Log security events with required metadata""" audit_logger.info(f"AUDIT: action={action} user={user} resource={resource} outcome={outcome} timestamp={datetime.datetime.utcnow().isoformat()}") # Example usage encryption = DataEncryption() sensitive_data = "user_ssn:123-45-6789" # Encrypt for storage (Confidentiality) encrypted = encryption.encrypt_sensitive_data(sensitive_data) # Store hash for integrity verification (Integrity) data_hash = compute_integrity_hash(sensitive_data) # Log access attempt (Auditing) audit_log("data_access", "admin_user", "user_records", "success") ``` -------------------------------- ### Example Usage of Request Validation Source: https://context7.com/owasp/devguide/llms.txt Demonstrates how to use the `validate_request` function with sample request data and a schema. It prints the validated data upon success or catches and prints validation errors. ```python request_data = { "username": "john_doe123", "email": "john@example.com", "phone": "+14155551234", "age": "25" } schema = { "username": InputType.USERNAME, "email": InputType.EMAIL, "phone": InputType.PHONE, "age": InputType.INTEGER } try: validated_data = validate_request(request_data, schema) print(f"Validated: {validated_data}") except ValidationError as e: print(f"Validation failed: {e}") ``` -------------------------------- ### Create Suppression File for False Positives Source: https://context7.com/owasp/devguide/llms.txt Example XML content for a suppression file. Use this to define rules for ignoring specific vulnerabilities based on package URL or CVE ID. ```xml False positive - not using vulnerable feature ^pkg:npm/lodash@.*$ CVE-2021-23337 ``` -------------------------------- ### Install Pyspelling Source: https://github.com/owasp/devguide/blob/main/contributing.md Install the pyspelling package using pip. This tool is used for spell checking documentation. ```bash pip install pyspelling ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://github.com/owasp/devguide/blob/main/contributing.md Run the MkDocs development server to view the documentation locally. Changes to markdown files will trigger automatic rebuilds. ```bash mkdocs serve ``` -------------------------------- ### SecurityLogger Initialization and Event Logging Source: https://context7.com/owasp/devguide/llms.txt Demonstrates the initialization of a SecurityLogger and the logging of various security events using its methods. ```python # Example usage security_log = SecurityLogger("myapp") # Log successful authentication security_log.log_authentication( success=True, username="john_doe", ip_address="192.168.1.100", user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)" ) # Log failed authentication security_log.log_authentication( success=False, username="john_doe", ip_address="192.168.1.100", user_agent="Mozilla/5.0", failure_reason="Invalid password" ) # Log authorization denial security_log.log_authorization( granted=False, user_id="user123", resource="/admin/users", action="DELETE", denial_reason="Insufficient privileges" ) # Log suspicious activity security_log.log_suspicious_activity( description="Multiple failed login attempts from same IP", ip_address="10.0.0.50", indicators={ "failed_attempts": 15, "time_window_seconds": 60, "targeted_accounts": ["admin", "root", "administrator"] } ) ``` -------------------------------- ### Build MkDocs Site Content Source: https://github.com/owasp/devguide/blob/main/contributing.md Generate the static site content for the documentation. This command builds the website into the 'site' directory. ```bash mkdocs build ``` -------------------------------- ### Build MkDocs Site for Deployment Source: https://github.com/owasp/devguide/blob/main/contributing.md Generates the static site content for deployment. This command builds the entire website, including assets and pages. ```text python3 -m mkdocs build --config-file mkdocs-pdf-en.yaml ``` -------------------------------- ### Run WebGoat Desktop Environment Source: https://github.com/owasp/devguide/blob/main/docs/en/07-training-education/01-vulnerable-apps/02-webgoat.md This command launches the WebGoat desktop environment using Docker. Access the application via the specified localhost port. ```bash docker run -p 127.0.0.1:3000:3000 webgoat/webgoat-desktop ``` -------------------------------- ### Python pip-audit for Python Projects Source: https://context7.com/owasp/devguide/llms.txt Install and run pip-audit to check Python package vulnerabilities. The `--format json` flag outputs the report in JSON format. ```bash pip install pip-audit pip-audit pip-audit --format json > audit-report.json ``` -------------------------------- ### Generate PDF Export (English) Source: https://github.com/owasp/devguide/blob/main/contributing.md Build the documentation and generate a PDF export file using a specific configuration file for English. ```bash mkdocs build --config-file mkdocs-pdf-en.yaml ``` -------------------------------- ### Scan Project Directory with Dependency-Check Source: https://context7.com/owasp/devguide/llms.txt Scan a project directory using the Dependency-Check CLI. Specify project name, scan path, output format, and output directory. Supported formats include HTML. ```bash ./dependency-check/bin/dependency-check.sh \ --project "MyWebApp" \ --scan ./my-project \ --format HTML \ --out ./reports ``` -------------------------------- ### Securely Get Users by Role with Dynamic IN Clause Source: https://context7.com/owasp/devguide/llms.txt Retrieves users based on a list of role names using a parameterized `IN` clause. Placeholders are dynamically generated for the `IN` clause, and the role names are passed as parameters to ensure security. ```python def get_users_by_role(self, role_names: List[str]) -> List[Dict]: """ SECURE: IN clause with dynamic parameters """ if not role_names: return [] # Create placeholders for each role placeholders = ','.join(['?' for _ in role_names]) query = f""" SELECT u.id, u.username, u.email, r.name as role FROM users u JOIN user_roles ur ON u.id = ur.user_id JOIN roles r ON ur.role_id = r.id WHERE r.name IN ({placeholders}) """ with self.get_connection() as conn: cursor = conn.execute(query, role_names) return [dict(row) for row in cursor.fetchall()] ``` -------------------------------- ### Initialize Security Logger Source: https://context7.com/owasp/devguide/llms.txt Initializes the SecurityLogger with a given application name and configures a stream handler with JSON formatting. ```python class SecurityLogger: """Centralized security logging with structured events""" def __init__(self, app_name: str = "application"): self.app_name = app_name self.logger = logging.getLogger(f"{app_name}.security") self._setup_logger() def _setup_logger(self): """Configure logger with JSON formatting""" handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(message)s')) self.logger.addHandler(handler) self.logger.setLevel(logging.INFO) ``` -------------------------------- ### Create Symbolic Links for Docs Source: https://github.com/owasp/devguide/blob/main/contributing.md Create symbolic links for contributing pages and license files within the 'docs' directory. This ensures these files are accessible when the documentation is built or served. ```bash ln -s ../code_of_conduct.md docs/code_of_conduct.md ln -s ../contributing.md docs/contributing.md ln -s ../license.txt docs/license.txt ``` -------------------------------- ### Generate PDF Exports (Other Languages) Source: https://github.com/owasp/devguide/blob/main/contributing.md Generate PDF exports for documentation in different languages using their respective configuration files. ```bash mkdocs build --config-file mkdocs-pdf-es.yaml ``` ```bash mkdocs build --config-file mkdocs-pdf-pt-br.yaml ``` -------------------------------- ### Gradle Plugin Configuration for Dependency-Check Source: https://context7.com/owasp/devguide/llms.txt Configure the OWASP Dependency-Check Gradle plugin in your build.gradle file. Set the CVSS score threshold, output formats, and suppression file. ```gradle plugins { id 'org.owasp.dependencycheck' version '9.0.0' } dependencyCheck { failBuildOnCVSS = 7 formats = ['HTML', 'JSON'] suppressionFile = 'suppression.xml' } ``` -------------------------------- ### Run Gradle Dependency Check Source: https://context7.com/owasp/devguide/llms.txt Execute the Dependency-Check analyze task using Gradle. This command performs the vulnerability analysis based on your build.gradle configuration. ```bash gradle dependencyCheckAnalyze ```