Repository: project-codeguard/rules Branch: main Commit: 036b66c1554f Files: 165 Total size: 697.1 KB Directory structure: gitextract_qrwk3pjw/ ├── .claude-plugin/ │ ├── marketplace.json │ └── plugin.json ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── new-rule.yml │ │ └── rule-feedback.yml │ └── workflows/ │ ├── build-ide-bundles.yml │ ├── deploy-docs.yml │ ├── stale.yml │ └── validate-rules.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── pyproject.toml ├── skills/ │ └── software-security/ │ ├── SKILL.md │ └── rules/ │ ├── codeguard-0-additional-cryptography.md │ ├── codeguard-0-api-web-services.md │ ├── codeguard-0-authentication-mfa.md │ ├── codeguard-0-authorization-access-control.md │ ├── codeguard-0-client-side-web-security.md │ ├── codeguard-0-cloud-orchestration-kubernetes.md │ ├── codeguard-0-data-storage.md │ ├── codeguard-0-devops-ci-cd-containers.md │ ├── codeguard-0-file-handling-and-uploads.md │ ├── codeguard-0-framework-and-languages.md │ ├── codeguard-0-iac-security.md │ ├── codeguard-0-input-validation-injection.md │ ├── codeguard-0-logging.md │ ├── codeguard-0-mcp-security.md │ ├── codeguard-0-mobile-apps.md │ ├── codeguard-0-privacy-data-protection.md │ ├── codeguard-0-safe-c-functions.md │ ├── codeguard-0-session-management-and-cookies.md │ ├── codeguard-0-supply-chain-security.md │ ├── codeguard-0-xml-and-serialization.md │ ├── codeguard-1-crypto-algorithms.md │ ├── codeguard-1-digital-certificates.md │ └── codeguard-1-hardcoded-credentials.md ├── sources/ │ ├── core/ │ │ ├── codeguard-0-additional-cryptography.md │ │ ├── codeguard-0-api-web-services.md │ │ ├── codeguard-0-authentication-mfa.md │ │ ├── codeguard-0-authorization-access-control.md │ │ ├── codeguard-0-client-side-web-security.md │ │ ├── codeguard-0-cloud-orchestration-kubernetes.md │ │ ├── codeguard-0-data-storage.md │ │ ├── codeguard-0-devops-ci-cd-containers.md │ │ ├── codeguard-0-file-handling-and-uploads.md │ │ ├── codeguard-0-framework-and-languages.md │ │ ├── codeguard-0-iac-security.md │ │ ├── codeguard-0-input-validation-injection.md │ │ ├── codeguard-0-logging.md │ │ ├── codeguard-0-mcp-security.md │ │ ├── codeguard-0-mobile-apps.md │ │ ├── codeguard-0-privacy-data-protection.md │ │ ├── codeguard-0-safe-c-functions.md │ │ ├── codeguard-0-session-management-and-cookies.md │ │ ├── codeguard-0-supply-chain-security.md │ │ ├── codeguard-0-xml-and-serialization.md │ │ ├── codeguard-1-crypto-algorithms.md │ │ ├── codeguard-1-digital-certificates.md │ │ ├── codeguard-1-hardcoded-credentials.md │ │ └── codeguard-SKILLS.md.template │ ├── owasp/ │ │ ├── codeguard-0-ajax-security.md │ │ ├── codeguard-0-attack-surface-analysis.md │ │ ├── codeguard-0-authentication.md │ │ ├── codeguard-0-authorization-testing-automation.md │ │ ├── codeguard-0-authorization.md │ │ ├── codeguard-0-bean-validation.md │ │ ├── codeguard-0-browser-extension-vulnerabilities.md │ │ ├── codeguard-0-c-based-toolchain-hardening.md │ │ ├── codeguard-0-choosing-and-using-security-questions.md │ │ ├── codeguard-0-ci-cd-security.md │ │ ├── codeguard-0-clickjacking-defense.md │ │ ├── codeguard-0-content-security-policy.md │ │ ├── codeguard-0-cookie-theft-mitigation.md │ │ ├── codeguard-0-credential-stuffing-prevention.md │ │ ├── codeguard-0-cross-site-request-forgery-prevention.md │ │ ├── codeguard-0-cross-site-scripting-prevention.md │ │ ├── codeguard-0-cryptographic-storage.md │ │ ├── codeguard-0-cw-cryptographic-security-guidelines.md │ │ ├── codeguard-0-cw-memory-string-usage-guidelines.md │ │ ├── codeguard-0-database-security.md │ │ ├── codeguard-0-deserialization.md │ │ ├── codeguard-0-django-rest-framework.md │ │ ├── codeguard-0-django-security.md │ │ ├── codeguard-0-docker-security.md │ │ ├── codeguard-0-dom-based-xss-prevention.md │ │ ├── codeguard-0-dom-clobbering-prevention.md │ │ ├── codeguard-0-dotnet-security.md │ │ ├── codeguard-0-error-handling.md │ │ ├── codeguard-0-file-upload.md │ │ ├── codeguard-0-forgot-password.md │ │ ├── codeguard-0-graphql.md │ │ ├── codeguard-0-html5-security.md │ │ ├── codeguard-0-http-headers.md │ │ ├── codeguard-0-http-strict-transport-security.md │ │ ├── codeguard-0-injection-prevention.md │ │ ├── codeguard-0-input-validation.md │ │ ├── codeguard-0-insecure-direct-object-reference-prevention.md │ │ ├── codeguard-0-jaas.md │ │ ├── codeguard-0-java-security.md │ │ ├── codeguard-0-json-web-token-for-java.md │ │ ├── codeguard-0-key-management.md │ │ ├── codeguard-0-kubernetes-security.md │ │ ├── codeguard-0-laravel.md │ │ ├── codeguard-0-ldap-injection-prevention.md │ │ ├── codeguard-0-legacy-application-management.md │ │ ├── codeguard-0-logging-vocabulary.md │ │ ├── codeguard-0-mass-assignment.md │ │ ├── codeguard-0-microservices-security.md │ │ ├── codeguard-0-mobile-application-security.md │ │ ├── codeguard-0-multifactor-authentication.md │ │ ├── codeguard-0-network-segmentation.md │ │ ├── codeguard-0-nodejs-docker.md │ │ ├── codeguard-0-nodejs-security.md │ │ ├── codeguard-0-npm-security.md │ │ ├── codeguard-0-oauth2.md │ │ ├── codeguard-0-open-redirect.md │ │ ├── codeguard-0-os-command-injection-defense.md │ │ ├── codeguard-0-password-storage.md │ │ ├── codeguard-0-php-configuration.md │ │ ├── codeguard-0-pinning.md │ │ ├── codeguard-0-prototype-pollution-prevention.md │ │ ├── codeguard-0-query-parameterization.md │ │ ├── codeguard-0-rest-assessment.md │ │ ├── codeguard-0-rest-security.md │ │ ├── codeguard-0-ruby-on-rails.md │ │ ├── codeguard-0-safe-c-functions.md │ │ ├── codeguard-0-saml-security.md │ │ ├── codeguard-0-securing-cascading-style-sheets.md │ │ ├── codeguard-0-server-side-request-forgery-prevention.md │ │ ├── codeguard-0-session-management.md │ │ ├── codeguard-0-sql-injection-prevention.md │ │ ├── codeguard-0-symfony.md │ │ ├── codeguard-0-third-party-javascript-management.md │ │ ├── codeguard-0-threat-modeling.md │ │ ├── codeguard-0-transaction-authorization.md │ │ ├── codeguard-0-transport-layer-security.md │ │ ├── codeguard-0-unvalidated-redirects-and-forwards.md │ │ ├── codeguard-0-user-privacy-protection.md │ │ ├── codeguard-0-virtual-patching.md │ │ ├── codeguard-0-vulnerable-dependency-management.md │ │ ├── codeguard-0-web-service-security.md │ │ ├── codeguard-0-xml-external-entity-prevention.md │ │ ├── codeguard-0-xml-security.md │ │ ├── codeguard-0-xs-leaks.md │ │ ├── codeguard-0-xss-filter-evasion.md │ │ └── codeguard-0-zero-trust-architecture.md │ └── templates/ │ └── custom-rule-template.md.example └── src/ ├── LICENSE.md ├── convert_to_ide_formats.py ├── converter.py ├── formats/ │ ├── __init__.py │ ├── agentskills.py │ ├── antigravity.py │ ├── base.py │ ├── copilot.py │ ├── cursor.py │ └── windsurf.py ├── language_mappings.py ├── tag_mappings.py ├── utils.py ├── validate_unified_rules.py └── validate_versions.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .claude-plugin/marketplace.json ================================================ { "name": "project-codeguard", "metadata": { "description": "Official Project CodeGuard plugins for secure AI-assisted coding" }, "owner": { "name": "Project CodeGuard", "url": "https://project-codeguard.org", "email": "contact@project-codeguard.org" }, "plugins": [ { "name": "codeguard-security", "source": "./", "description": "Comprehensive security rules for AI coding agents", "version": "1.2.0", "repository": "https://github.com/project-codeguard/rules.git", "tags": [ "security", "code-review", "vulnerability-prevention" ] } ] } ================================================ FILE: .claude-plugin/plugin.json ================================================ { "name": "codeguard-security", "description": "Security code review skill based on Project CodeGuard's comprehensive security rules. Helps AI coding agents write secure code and prevent common vulnerabilities.", "version": "1.2.0", "author": { "name": "Project CodeGuard", "url": "https://project-codeguard.org" }, "license": "CC-BY-4.0 (rules), Apache-2.0 (tools)", "homepage": "https://github.com/project-codeguard/rules", "repository": "https://github.com/project-codeguard/rules.git", "keywords": [ "security", "secure-coding", "vulnerability-prevention", "code-review", "appsec" ] } ================================================ FILE: .github/ISSUE_TEMPLATE/new-rule.yml ================================================ name: ✨ New Rule Request description: Share your new rule request labels: ["new-rule"] body: - type: markdown attributes: value: | Thank you for your new rule request! Please provide as much detail as possible. Use any of the existing rules as a reference. You only have to provide the rule contents (markdown), not the rule metadata. We will handle the rest. In other words, convert your rule into all the formats (Cursor, Windsurf, Copilot, Antigravity). - type: textarea id: description attributes: label: Description description: Provide the new rule contents (markdown). placeholder: Enter the new rule contents (markdown) here... validations: required: true - type: dropdown id: language attributes: label: What language(s) are the rule for? multiple: true options: - 'python' - 'javascript' - 'typescript' - 'java' - 'c' - 'c++' - 'go' - 'rust' - 'ruby' - 'php' - 'swift' - 'kotlin' - 'scala' - 'r' - 'matlab' - 'julia' - 'dart' - 'lua' - 'perl' - 'shell' - 'powershell' - 'fsharp' - 'erlang' - 'ocaml' - 'yaml' - 'docker' - 'xml' - 'vue' - 'elm' - 'cuda' - 'opencl' - 'other (please specify)' validations: required: true - type: textarea id: other attributes: label: Other description: Please specify the language(s) you are requesting. Only specify this if the language is not listed above. placeholder: Add the language(s) here... validations: required: false ================================================ FILE: .github/ISSUE_TEMPLATE/rule-feedback.yml ================================================ --- name: 📝 Rule Feedback description: Share your feedback, suggestions, or report issues labels: ["rule-feedback"] body: - type: markdown attributes: value: | Thank you for your feedback! Please provide as much detail as possible. - type: textarea id: description attributes: label: Description description: Provide detailed feedback. placeholder: Describe your feedback here... Add any additional context, such as screenshots, related issues, or why this matters. validations: required: true - type: dropdown id: ai-coding-tool attributes: label: What AI Coding Tool are you Using? options: - Cursor - GitHub Copilot - Windsurf - Antigravity - Codex - Augment Code - Sourcegraph - Claude Code - Other validations: required: true - type: textarea id: ai-model attributes: label: AI Model Used description: What AI model are you using? placeholder: Add the model name... (e.g. GPT-5, Claude 4.5 Sonnet, Gemini 2.5 Pro, etc.) - type: dropdown id: feedback-type attributes: label: The feedback pertains to which aspect of the project? options: - Rule definition - Rule invocation or execution - Rule distribution - Other validations: required: true ================================================ FILE: .github/workflows/build-ide-bundles.yml ================================================ --- name: Build and Release IDE Bundles on: release: types: [published] jobs: build-and-release: runs-on: ubuntu-latest permissions: contents: write steps: - name: Checkout repository uses: actions/checkout@v4 with: ref: ${{ github.event.release.tag_name }} - name: Install uv uses: astral-sh/setup-uv@v4 with: enable-cache: true - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: uv sync - name: Get version from release id: get_version run: | TAG="${{ github.event.release.tag_name }}" VERSION=${TAG#v} echo "tag=$TAG" >> $GITHUB_OUTPUT echo "version=$VERSION" >> $GITHUB_OUTPUT echo "Release version: $VERSION (tag: $TAG)" - name: Validate rules run: uv run python src/validate_unified_rules.py sources/ - name: Validate versions match tag run: uv run python src/validate_versions.py ${{ steps.get_version.outputs.version }} - name: Generate IDE bundles run: uv run python src/convert_to_ide_formats.py - name: Create release archives run: | cd dist zip -r ../ide-rules-cursor.zip .cursor/ zip -r ../ide-rules-windsurf.zip .windsurf/ zip -r ../ide-rules-copilot.zip .github/ zip -r ../ide-rules-antigravity.zip .agent/ cd .. zip -r ide-rules-all.zip dist/ ls -lh ide-rules-*.zip - name: Upload release assets env: GH_TOKEN: ${{ github.token }} run: | gh release upload "${{ steps.get_version.outputs.tag }}" \ ide-rules-all.zip \ ide-rules-cursor.zip \ ide-rules-windsurf.zip \ ide-rules-copilot.zip \ ide-rules-antigravity.zip \ --clobber ================================================ FILE: .github/workflows/deploy-docs.yml ================================================ --- name: Deploy Documentation on: workflow_dispatch: permissions: contents: write jobs: deploy: runs-on: ubuntu-latest steps: - name: Generate GitHub App Token id: generate-token uses: actions/create-github-app-token@v1 with: app-id: ${{ secrets.CODEGUARD_APP_ID }} private-key: ${{ secrets.CODEGUARD_APP_PRIVATE_KEY }} - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 token: ${{ steps.generate-token.outputs.token }} - name: Install uv uses: astral-sh/setup-uv@v4 with: enable-cache: true - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: uv sync - name: Configure Git run: | git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" - name: Deploy to GitHub Pages env: GH_TOKEN: ${{ steps.generate-token.outputs.token }} run: uv run mkdocs gh-deploy --force --clean --verbose ================================================ FILE: .github/workflows/stale.yml ================================================ --- # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. # For more information, see: https://github.com/actions/stale name: 'Close Stale Issues and PRs' on: schedule: # Runs at 02:33 UTC every day. You can adjust the schedule as needed. - cron: '33 2 * * *' jobs: stale: # The type of runner that the job will run on. runs-on: ubuntu-latest # Permissions for the GITHUB_TOKEN to allow the action to modify issues and PRs. permissions: issues: write pull-requests: write steps: - uses: actions/stale@v9 with: # The token for the repository. Required. repo-token: ${{ secrets.GITHUB_TOKEN }} # The message to post on stale issues. stale-issue-message: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # The message to post on stale PRs. stale-pr-message: > This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # The label to apply to stale issues and PRs. stale-issue-label: 'stale' stale-pr-label: 'stale' # The number of days of inactivity before an issue or PR is marked as stale. days-before-stale: 60 # The number of days of inactivity before a stale issue or PR is closed. # Set to -1 to disable closing. days-before-close: 7 # Labels that prevent an issue or PR from being marked as stale. exempt-issue-labels: 'pinned,security' exempt-pr-labels: 'pinned,security' # Exempt all issues and PRs with an assignee. exempt-all-issue-assignees: true exempt-all-pr-assignees: true # The maximum number of operations to perform per run. operations-per-run: 100 ================================================ FILE: .github/workflows/validate-rules.yml ================================================ --- name: Validate Rules permissions: contents: read on: pull_request: paths: - 'sources/**' - 'src/**' - 'pyproject.toml' push: branches: - main - develop paths: - 'sources/**' - 'src/**' - 'pyproject.toml' workflow_dispatch: jobs: validate: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Install uv uses: astral-sh/setup-uv@v4 with: enable-cache: true - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: uv sync - name: Validate unified rules run: uv run python src/validate_unified_rules.py sources/ - name: Check required core rule files exist run: | echo "Checking for required core rule files..." required_files=( "sources/core/codeguard-1-hardcoded-credentials.md" "sources/core/codeguard-1-crypto-algorithms.md" "sources/core/codeguard-1-digital-certificates.md" "sources/core/codeguard-SKILLS.md.template" ) missing=0 for file in "${required_files[@]}"; do if [ ! -f "$file" ]; then echo "❌ Missing required file: $file" missing=1 else echo "✅ Found: $file" fi done if [ $missing -eq 1 ]; then exit 1 fi - name: Test conversion to IDE formats run: | echo "Testing IDE format conversion..." uv run python src/convert_to_ide_formats.py --output-dir test-output # Check that files were generated if [ ! -d "test-output/.cursor" ]; then echo "❌ Cursor rules not generated" exit 1 fi if [ ! -d "test-output/.windsurf" ]; then echo "❌ Windsurf rules not generated" exit 1 fi if [ ! -d "test-output/.github" ]; then echo "❌ Copilot instructions not generated" exit 1 fi if [ ! -d "test-output/.agent" ]; then echo "❌ Antigravity rules not generated" exit 1 fi echo "✅ All IDE formats generated successfully" - name: Check skills/ directory is up-to-date run: | echo "Checking if committed skills/ directory is up-to-date..." # Save current skills mv skills skills-committed # Regenerate skills (core rules only, matching default) uv run python src/convert_to_ide_formats.py # Compare if ! diff -r skills/ skills-committed/ > /dev/null 2>&1; then echo "❌ The skills/ directory is out of date!" echo "Please regenerate by running: python src/convert_to_ide_formats.py" echo "Then: git add skills/" mv skills-committed skills exit 1 fi # Restore original rm -rf skills mv skills-committed skills echo "✅ Committed skills/ directory is up-to-date" - name: Summary if: success() run: | echo "✅ All validation checks passed!" echo "" echo "Rule validation: ✅" echo "Required files: ✅" echo "IDE conversion: ✅" echo "Skills directory: ✅" ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # Node.js node_modules/ npm-debug.log yarn-error.log # macOS .DS_Store .AppleDouble .LSOverride # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # VSCode .vscode/ # JetBrains .idea/ # Log files *.log # Environment variables .env .env.local .env.development.local .env.test.local .env.production.local # Coding Agents CLAUDE.md AGENTS.md # Claude Code Plugin .claude-plugin/.cache .claude/settings.local.json # Generated IDE-specific rule bundles (not committed, built for releases) dist/ ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at oss-security@cisco.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing ## How to contribute? Project CodeGuard is an open-source initiative actively seeking contributions from the community. This document outlines how to get involved and the process we follow for proposing, reviewing, and merging changes. In general, a Project CodeGuard Contributor is expected to: - be knowledgeable in one or more areas related to the project - contribute to developing and finalizing workstream deliverables - be reliable in completing issues they take on - show commitment over time with one or more PRs merged - follow the project style and testing guidelines - follow branch, PR, and code style conventions - contribute in ways that substantially improve the quality of the project and the experience of people who use it When contributing to any CodeGuard repository, please first discuss the change you wish to make via a GitHub issue. For small fixes, opening a PR directly with clear context is fine; for larger changes or new features, please open an issue first to align on scope and approach. Please note that all of your interactions in the project are subject to our [Code of Conduct](CODE_OF_CONDUCT.md). This includes creation of issues or pull requests, commenting on issues or pull requests, and extends to all interactions in any real-time space. Please be respectful of differing opinions when discussing potential contributions. We aim for a welcoming, collaborative environment for all contributors. ## Content Update Governance Process CodeGuard uses a two-stage governance process for updates to the project’s rules, controls, and other structured content. This separates technical review from community governance, ensuring both content quality and project alignment. ### What Constitutes a Content Update Content updates include changes to: - Rules definitions, categories, and metadata - Security control specifications and mappings - Component or taxonomy elements and relationships - Content-oriented documentation and guidance materials ### Two-Stage Process Overview **Stage 1: Technical Review** – Content `feature` branches merge to the `develop` branch after standard PR review **Stage 2: Community Review** – Bi-weekly governance review of the `develop` branch’s accumulated changes before release to `main` ``` feature-branch → develop → main ↑ ↑ ↑ Stage 1 Stage 2 Release (Technical) (Community) ``` ### Non-Content Changes The following types of changes are not covered by the two-stage content update process and continue to follow existing workflows: - Bug fixes – technical corrections and error resolution - Implementation changes – updates to code logic, algorithms, or system functionality - Infrastructure updates – CI/CD, build processes, deployment configurations - Documentation fixes – corrections to technical documentation, README updates, etc. - Security patches – critical security-related fixes requiring immediate deployment - Dependency updates – library upgrades and security patches for dependencies These excluded change types may follow direct-to-`main` workflows as determined by repository maintainers and policies. ## Repository Structure - **`sources/`** - Source rules (edit these: `core/` has 22 files, `owasp/` has 88) - **`src/`** - Conversion and validation tools - **`skills/`** - Claude Code plugin (generated, committed) - **`dist/`** - Other IDE bundles (generated, not committed) ## First-time contributors If you are new to the project and looking for an entry point, check the open issues. Issues tagged `good first issue` are meant to be small, well-scoped tasks suitable for first-time contributors. If you find one you’d like to work on, comment on the issue and/or assign yourself, and a maintainer can confirm assignment. ## Submitting a new issue If you want to create a new issue that doesn't exist already, open a new one and include: - a concise problem statement or feature request - steps to reproduce (for bugs) - expected vs. actual behavior - environment details (versions, OS) if applicable - proposed approach or alternatives (optional but helpful) **If you discover a security bug, please do not report it through GitHub. Instead, please see security procedures in [SECURITY.md](SECURITY.md).** ## Submitting a new pull request and review process The process for submitting pull requests depends on the type of change: ### For Content Updates (Two-Stage Process) Follow these steps when submitting content updates: 1. Fork this repo into your GitHub account. If you have write access, you may create a branch directly. 2. Create a new branch, based on the `develop` branch, with a name that concisely describes what you’re working on. 3. Ensure that your changes pass validation and do not cause any existing tests to fail. 4. Submit a pull request against the `develop` branch. #### Content Update PR Review **Stage 1 Review**: Your PR to `develop` will be reviewed for technical criteria including content correctness, formatting and schema validation (where applicable), code hygiene, and commit message quality. **Stage 2 Review**: On a regular cadence (typically bi-weekly), a PR will be created from `develop` to `main` containing all merged content changes from the cycle period. This undergoes community review by maintainers and contributors using lazy consensus and/or simple voting procedures as needed. ### For Non-Content Changes (Standard Process) Follow these steps when submitting non-content changes (bug fixes, implementation changes, infrastructure updates, etc.): 1. Fork this repo into your GitHub account (or create a branch if you have write access). 2. Create a new branch, based on the `main` branch, with a name that concisely describes what you’re working on. 3. Ensure that your changes do not cause any existing tests to fail. 4. Submit a pull request against the `main` branch. #### Non-Content PR Review 1. PRs will be reviewed by maintainers. Additional reviewers may be requested depending on scope. 2. Reviewer responses are typically due within 3 business days. ### General Review Guidelines Maintainers aim to review pull requests and issues within 3 business days. [Lazy consensus](https://openoffice.apache.org/docs/governance/lazyConsensus.html) is practiced for this project. Major changes in GitHub or to a project document on any official platform should be accompanied by an issue or discussion with a comment period of no less than seven (7) business days, mindful of major world holidays. ## Branch naming and commit messages ### Branch naming - `main` – main development branch and authoritative source; updated after community approval for content changes - `develop` – staging area for community review of content updates; feature branches for content changes target this branch - `feature` – feature/this-is-a-new-feature-branch (target `develop` for content updates, `main` for non-content changes) - `codebugfix` – codebugfix/description-of-the-bug (typically targets `main`) - `languagefix` – languagefix/description-of-the-language-fix (typically targets `main`) - `docs` – docs/description-of-the-documentation-change (typically targets `main`; documentation changes are exempt from the content update rule above) - `release` – release/description-of-the-release – cut from `main` when ready ### Commit messages format Write commit messages that clearly explain the change by continuing the sentence “This commit …”. Examples of good commit messages: - "This commit renames the examples folder to reference-implementations." - "This commit bumps dependency versions to address security advisories." ## Release Process (Maintainers) ### Step 1: Update Version ```bash # Edit pyproject.toml and update the version number vi pyproject.toml # Change version = "1.2.3" # Regenerate all IDE bundles (auto-syncs version to JSON files) uv run python src/convert_to_ide_formats.py # Review changes git diff # Commit changes git add -A git commit -m "Bump version to 1.2.3" # Push to main (via PR or direct) git push origin main ``` **Note**: The conversion script automatically syncs the version from `pyproject.toml` to: - `.claude-plugin/plugin.json` and `marketplace.json` (Claude Code plugin metadata) - All generated IDE rule files (Cursor `.mdc`, Windsurf `.md`, Copilot `.instructions.md`, Claude Code `.md`, Antigravity `.md`) This ensures version consistency across all artifacts. ### Step 2: Create Release (GitHub UI) 1. Go to: https://github.com/project-codeguard/rules/releases/new 2. **Tag**: Enter `vX.Y.Z` (must match version in pyproject.toml) 3. **Title**: `Project CodeGuard vX.Y.Z` 4. Click **"Generate release notes"** (auto-generates changelog) 5. Click **"Publish release"** GitHub Actions will automatically: - ✅ Validate versions match the tag - ✅ Build IDE bundles (Cursor, Windsurf, Copilot, Antigravity) - ✅ Upload ZIP artifacts to the release ## Testing Your Changes ```bash # Validate rules (required if you modified rules) python src/validate_unified_rules.py sources/ # Regenerate skills/ (required if you modified rules) python src/convert_to_ide_formats.py git add skills/ # skills/ is version-controlled # Test with all sources (core + owasp) python src/convert_to_ide_formats.py --source core owasp -o test-output/ # Check: test-output/.cursor/, test-output/.windsurf/, etc. # Get help python src/convert_to_ide_formats.py --help ``` ## Feedback Questions or comments about this project may be composed as GitHub issues or PR comments. If a broader discussion is needed, open or reference a GitHub Discussion (if enabled) or propose a short design doc in an issue. ================================================ FILE: LICENSE ================================================ Creative Commons Attribution 4.0 International (CC BY 4.0) Copyright © 2025 Cisco Systems, Inc. Licensed under the Creative Commons Attribution 4.0 International License. You may obtain a copy of the License at: https://creativecommons.org/licenses/by/4.0/ Unless required by applicable law or agreed to in writing, content distributed under this license is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Attribution Requirements — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. — No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. For the full legal code of CC BY 4.0, see: https://creativecommons.org/licenses/by/4.0/legalcode ================================================ FILE: README.md ================================================ ## Project CodeGuard has been donated to the Coalition for Secure AI (CoSAI)! This project is now maintained by the Coalition for Secure AI (CoSAI). **➡️ New Repository: [github.com/cosai-oasis/project-codeguard](https://github.com/cosai-oasis/project-codeguard)** Please visit the new repository for the latest updates and how to contribute to the project. ================================================ FILE: SECURITY.md ================================================ # Security Policies and Procedures This document outlines security procedures and general policies for the Project CodeGuard project. - [Disclosing a security issue](#disclosing-a-security-issue) - [Vulnerability management](#vulnerability-management) - [Suggesting changes](#suggesting-changes) ## Disclosing a security issue The Project CodeGuard maintainers take all security issues in the project seriously. Thank you for improving the security of Project CodeGuard. We appreciate your dedication to responsible disclosure and will make every effort to acknowledge your contributions. Project CodeGuard leverages GitHub's private vulnerability reporting. To learn more about this feature and how to submit a vulnerability report, review [GitHub's documentation on private reporting](https://docs.github.com/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability). Here are some helpful details to include in your report: - a detailed description of the issue - the steps required to reproduce the issue - versions of the project that may be affected by the issue - if known, any mitigations for the issue A maintainer will acknowledge the report within three (3) business days, and will send a more detailed response within an additional three (3) business days indicating the next steps in handling your report. If you've been unable to successfully draft a vulnerability report via GitHub or have not received a response during the alloted response window, please reach out via the [Cisco Open security contact email](mailto:oss-security@cisco.com). After the initial reply to your report, the maintainers will endeavor to keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance. ## Vulnerability management When the maintainers receive a disclosure report, they will assign it to a primary handler. This person will coordinate the fix and release process, which involves the following steps: - confirming the issue - determining affected versions of the project - auditing code to find any potential similar problems - preparing fixes for all releases under maintenance ## Suggesting changes If you have suggestions on how this process could be improved please submit an issue or pull request. ================================================ FILE: pyproject.toml ================================================ [project] name = "project-codeguard" version = "1.2.0" description = "AI Coding Rules for Security and Best Practices" requires-python = ">=3.11" dependencies = [ "pyyaml~=6.0.2", "mkdocs~=1.6.1", "mkdocs-material~=9.6.21", ] ================================================ FILE: skills/software-security/SKILL.md ================================================ --- name: software-security description: A software security skill that integrates with Project CodeGuard to help AI coding agents write secure code and prevent common vulnerabilities. Use this skill when writing, reviewing, or modifying code to ensure secure-by-default practices are followed. codeguard-version: "1.2.0" framework: "Project CodeGuard" purpose: "Embed secure-by-default practices into AI coding workflows" --- # Software Security Skill (Project CodeGuard) This skill provides comprehensive security guidance to help AI coding agents generate secure code and prevent common vulnerabilities. It is based on **Project CodeGuard**, an open-source, model-agnostic security framework that embeds secure-by-default practices into AI coding workflows. ## When to Use This Skill This skill should be activated when: - Writing new code in any language - Reviewing or modifying existing code - Implementing security-sensitive features (authentication, cryptography, data handling, etc.) - Working with user input, databases, APIs, or external services - Configuring cloud infrastructure, CI/CD pipelines, or containers - Handling sensitive data, credentials, or cryptographic operations ## How to Use This Skill When writing or reviewing code: 1. Always-Apply Rules: Some rules MUST be checked on every code operation: - `codeguard-1-hardcoded-credentials.md` - Never hardcode secrets, passwords, API keys, or tokens - `codeguard-1-crypto-algorithms.md` - Use only modern, secure cryptographic algorithms - `codeguard-1-digital-certificates.md` - Validate and manage digital certificates securely 2. Context-Specific Rules: Apply rules from /rules directory based on the language of the feature being implemented using the table given below: | Language | Rule Files to Apply | |----------|---------------------| | apex | codeguard-0-input-validation-injection.md | | c | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-client-side-web-security.md, codeguard-0-data-storage.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-iac-security.md, codeguard-0-input-validation-injection.md, codeguard-0-logging.md, codeguard-0-safe-c-functions.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | cpp | codeguard-0-safe-c-functions.md | | d | codeguard-0-iac-security.md | | docker | codeguard-0-devops-ci-cd-containers.md, codeguard-0-supply-chain-security.md | | go | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-input-validation-injection.md, codeguard-0-mcp-security.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | html | codeguard-0-client-side-web-security.md, codeguard-0-input-validation-injection.md, codeguard-0-session-management-and-cookies.md | | java | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-input-validation-injection.md, codeguard-0-mcp-security.md, codeguard-0-mobile-apps.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | javascript | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-client-side-web-security.md, codeguard-0-cloud-orchestration-kubernetes.md, codeguard-0-data-storage.md, codeguard-0-devops-ci-cd-containers.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-iac-security.md, codeguard-0-input-validation-injection.md, codeguard-0-logging.md, codeguard-0-mcp-security.md, codeguard-0-mobile-apps.md, codeguard-0-privacy-data-protection.md, codeguard-0-session-management-and-cookies.md, codeguard-0-supply-chain-security.md | | kotlin | codeguard-0-additional-cryptography.md, codeguard-0-authentication-mfa.md, codeguard-0-framework-and-languages.md, codeguard-0-mobile-apps.md | | matlab | codeguard-0-additional-cryptography.md, codeguard-0-authentication-mfa.md, codeguard-0-mobile-apps.md, codeguard-0-privacy-data-protection.md | | perl | codeguard-0-mobile-apps.md | | php | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-client-side-web-security.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-input-validation-injection.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | powershell | codeguard-0-devops-ci-cd-containers.md, codeguard-0-iac-security.md, codeguard-0-input-validation-injection.md | | python | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-input-validation-injection.md, codeguard-0-mcp-security.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | ruby | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-iac-security.md, codeguard-0-input-validation-injection.md, codeguard-0-session-management-and-cookies.md, codeguard-0-xml-and-serialization.md | | rust | codeguard-0-mcp-security.md | | shell | codeguard-0-devops-ci-cd-containers.md, codeguard-0-iac-security.md, codeguard-0-input-validation-injection.md | | sql | codeguard-0-data-storage.md, codeguard-0-input-validation-injection.md | | swift | codeguard-0-additional-cryptography.md, codeguard-0-authentication-mfa.md, codeguard-0-mobile-apps.md | | typescript | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authentication-mfa.md, codeguard-0-authorization-access-control.md, codeguard-0-client-side-web-security.md, codeguard-0-file-handling-and-uploads.md, codeguard-0-framework-and-languages.md, codeguard-0-input-validation-injection.md, codeguard-0-mcp-security.md, codeguard-0-session-management-and-cookies.md | | vlang | codeguard-0-client-side-web-security.md | | xml | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-devops-ci-cd-containers.md, codeguard-0-framework-and-languages.md, codeguard-0-mobile-apps.md, codeguard-0-xml-and-serialization.md | | yaml | codeguard-0-additional-cryptography.md, codeguard-0-api-web-services.md, codeguard-0-authorization-access-control.md, codeguard-0-cloud-orchestration-kubernetes.md, codeguard-0-data-storage.md, codeguard-0-devops-ci-cd-containers.md, codeguard-0-framework-and-languages.md, codeguard-0-iac-security.md, codeguard-0-logging.md, codeguard-0-privacy-data-protection.md, codeguard-0-supply-chain-security.md | 3. Proactive Security: Don't just avoid vulnerabilities-actively implement secure patterns: - Use parameterized queries for database access - Validate and sanitize all user input - Apply least-privilege principles - Use modern cryptographic algorithms and libraries - Implement defense-in-depth strategies ## CodeGuard Security Rules The security rules are available in the `rules/` directory. ### Usage Workflow When generating or reviewing code, follow this workflow: ### 1. Initial Security Check Before writing any code: - Check: Will this handle credentials? → Apply codeguard-1-hardcoded-credentials - Check: What language am I using? → Identify applicable language-specific rules - Check: What security domains are involved? → Load relevant rule files ### 2. Code Generation While writing code: - Apply secure-by-default patterns from relevant Project CodeGuard rules - Add security-relevant comments explaining choices ### 3. Security Review After writing code: - Review against implementation checklists in each rule - Verify no hardcoded credentials or secrets - Validate that all the rules have been successfully followed when applicable. - Explain which security rules were applied - Highlight security features implemented ================================================ FILE: skills/software-security/rules/codeguard-0-additional-cryptography.md ================================================ --- description: Additional Cryptography guidance languages: - c - go - java - javascript - kotlin - matlab - php - python - ruby - swift - typescript - xml - yaml alwaysApply: false --- rule_id: codeguard-0-additional-cryptography ## Additional Cryptography & TLS Apply modern, vetted cryptography for data at rest and in transit. Manage keys safely, configure TLS correctly, deploy HSTS, and consider pinning only when appropriate. ### Algorithms and Modes - Symmetric: AES‑GCM or ChaCha20‑Poly1305 preferred. Avoid ECB. CBC/CTR only with encrypt‑then‑MAC. - Asymmetric: RSA ≥2048 or modern ECC (Curve25519/Ed25519). Use OAEP for RSA encryption. - Hashing: SHA‑256+ for integrity; avoid MD5/SHA‑1. - RNG: Use CSPRNG appropriate to platform (e.g., SecureRandom, crypto.randomBytes, secrets module). Never use non‑crypto RNGs. ### Key Management - Generate keys within validated modules (HSM/KMS) and never from passwords or predictable inputs. - Separate keys by purpose (encryption, signing, wrapping). Rotate on compromise, cryptoperiod, or policy. - Store keys in KMS/HSM or vault; never hardcode; avoid plain env vars. Use KEK to wrap DEKs; store separately. - Control access to trust stores; validate updates; audit all key access and operations. ### Data at Rest - Encrypt sensitive data; minimize stored secrets; tokenize where possible. - Use authenticated encryption; manage nonces/IVs properly; keep salts unique per item. - Protect backups: encrypt, restrict access, test restores, manage retention. ### TLS Configuration - Protocols: TLS 1.3 preferred; allow TLS 1.2 only for legacy compatibility; disable TLS 1.0/1.1 and SSL. Enable TLS_FALLBACK_SCSV. - Ciphers: prefer AEAD suites; disable NULL/EXPORT/anon. Keep libraries updated; disable compression. - Key exchange groups: prefer x25519/secp256r1; configure secure FFDHE groups if needed. - Certificates: 2048‑bit+ keys, SHA‑256, correct CN/SAN. Manage lifecycle and revocation (OCSP stapling). - Application: HTTPS site‑wide; redirect HTTP→HTTPS; prevent mixed content; set cookies `Secure`. ### HSTS - Send Strict‑Transport‑Security only over HTTPS. Phase rollout: - Test: short max‑age (e.g., 86400) with includeSubDomains - Prod: ≥1 year max‑age; includeSubDomains when safe - Optional preload once mature; understand permanence and subdomain impact ### Pinning - Avoid browser HPKP. Consider pinning only for controlled clients (e.g., mobile) and when you own both ends. - Prefer SPKI pinning with backup pins; plan secure update channels; never allow user bypass. - Thoroughly test rotation and failure handling; understand operational risk. ### Implementation Checklist - AEAD everywhere; vetted libraries only; no custom crypto. - Keys generated and stored in KMS/HSM; purpose‑scoped; rotation documented. - TLS 1.3/1.2 with strong ciphers; compression off; OCSP stapling on. - HSTS deployed per phased plan; mixed content eliminated. - Pinning used only where justified, with backups and update path. ### Test Plan - Automated config scans (e.g., SSL Labs, testssl.sh) for protocol/cipher/HSTS. - Code review for crypto API misuse; tests for key rotation, backup/restore. - Pinning simulations for rotation/failures if deployed. ================================================ FILE: skills/software-security/rules/codeguard-0-api-web-services.md ================================================ --- description: API & Web services security (REST/GraphQL/SOAP), schema validation, authn/z, SSRF languages: - c - go - java - javascript - php - python - ruby - typescript - xml - yaml alwaysApply: false --- rule_id: codeguard-0-api-web-services ## API & Web Services Security Secure REST, GraphQL, and SOAP/WS services end‑to‑end: transport, authn/z, schema validation, SSRF controls, DoS limits, and microservice‑safe patterns. ### Transport and TLS - HTTPS only; consider mTLS for high‑value/internal services. Validate certs (CN/SAN, revocation) and prevent mixed content. ### Authentication and Tokens - Use standard flows (OAuth2/OIDC) for clients; avoid custom schemes. For services, use mTLS or signed service tokens. - JWTs: pin algorithms; validate iss/aud/exp/nbf; short lifetimes; rotation; denylist on logout/revoke. Prefer opaque tokens when revocation is required and central store is available. - API keys: scope narrowly; rate limit; monitor usage; do not use alone for sensitive operations. ### Authorization - Enforce per‑endpoint, per‑resource checks server‑side; deny by default. - For microservices, authorize at gateway (coarse) and service (fine) layers; propagate signed internal identity, not external tokens. ### Input and Content Handling - Validate inputs via contracts: OpenAPI/JSON Schema, GraphQL SDL, XSD. Reject unknown fields and oversize payloads; set limits. - Content types: enforce explicit Content‑Type/Accept; reject unsupported combinations. Harden XML parsers against XXE/expansion. ### SQL/Injection Safety in Resolvers and Handlers - Use parameterized queries/ORM bind parameters; never concatenate user input into queries or commands. ### GraphQL‑Specific Controls - Limit query depth and overall complexity; enforce pagination; timeouts on execution; disable introspection and IDEs in production. - Implement field/object‑level authorization to prevent IDOR/BOLA; validate batching and rate limit per object type. ### SSRF Prevention for Outbound Calls - Do not accept raw URLs. Validate domains/IPs using libraries; restrict to HTTP/HTTPS only (block file://, gopher://, ftp://, etc.). - Case 1 (fixed partners): strict allow‑lists; disable redirects; network egress allow‑lists. - Case 2 (arbitrary): block private/link‑local/localhost ranges; resolve and verify all IPs are public; require signed tokens from the target where feasible. ### SOAP/WS and XML Safety - Validate SOAP payloads with XSD; limit message sizes; enable XML signatures/encryption where required. - Configure parsers against XXE, entity expansion, and recursive payloads; scan attachments. ### Rate Limiting and DoS - Apply per‑IP/user/client limits, circuit breakers, and timeouts. Use server‑side batching and caching to reduce load. ### Management Endpoints - Do not expose over the Internet. Require strong auth (MFA), network restrictions, and separate ports/hosts. ### Testing and Assessment - Maintain formal API definitions; drive contract tests and fuzzing from specs. - Assess endpoints for authn/z bypass, SSRF, injection, and information leakage; log token validation failures. ### Microservices Practices - Policy‑as‑code with embedded decision points; sidecar or library PDPs. - Service identity via mTLS or signed tokens; never reuse external tokens internally. - Centralized structured logging with correlation IDs; sanitize sensitive data. ### Implementation Checklist - HTTPS/mTLS configured; certs managed; no mixed content. - Contract validation at the edge and service; unknown fields rejected; size/time limits enforced. - Strong authn/z per endpoint; GraphQL limits applied; introspection disabled in prod. - SSRF protections at app and network layers; redirects disabled; allow‑lists where possible. - Rate limiting, circuit breakers, and resilient patterns in place. - Management endpoints isolated and strongly authenticated. - Logs structured and privacy‑safe with correlation IDs. ### Test Plan - Contract tests for schema adherence; fuzzing with schema‑aware tools. - Pen tests for SSRF, IDOR/BOLA, and authz bypass; performance tests for DoS limits. - Test all HTTP methods per endpoint; discover parameters in URL paths, headers, and structured data beyond obvious query strings. - Automated checks for token validation and revocation behavior. ================================================ FILE: skills/software-security/rules/codeguard-0-authentication-mfa.md ================================================ --- description: Authentication and MFA best practices (passwords, MFA, OAuth/OIDC, SAML, recovery, tokens) languages: - c - go - java - javascript - kotlin - matlab - php - python - ruby - swift - typescript alwaysApply: false --- rule_id: codeguard-0-authentication-mfa ## Authentication & MFA Build a resilient, user-friendly authentication system that resists credential attacks, protects secrets, and supports strong, phishing-resistant MFA and secure recovery. ### Account Identifiers and UX - Use non-public, random, and unique internal user identifiers. Allow login via verified email or username. - Always return generic error messages (e.g., "Invalid username or password"). Keep timing consistent to prevent account enumeration. - Support password managers: ``, allow paste, no JS blocks. ### Password Policy - Accept passphrases and full Unicode; minimum 8 characters; avoid composition rules. Set only a reasonable maximum length (64+). - Check new passwords against breach corpora (e.g., k‑anonymity APIs); reject breached/common passwords. ### Password Storage (Hashing) - Hash, do not encrypt. Use slow, memory‑hard algorithms with unique per‑user salts and constant‑time comparison. - Preferred order and parameters (tune to your hardware; target <1s on server): - Argon2id: m=19–46 MiB, t=2–1, p=1 (or equivalent security trade‑offs) - scrypt: N=2^17, r=8, p=1 (or equivalent) - bcrypt (legacy only): cost ≥10, be aware of 72‑byte input limit - PBKDF2 (FIPS): PBKDF2‑HMAC‑SHA‑256 ≥600k, or SHA‑1 ≥1.3M - Optional pepper: store outside DB (KMS/HSM); if used, apply via HMAC or pre‑hashing. Plan for user resets if pepper rotates. - Unicode and null bytes must be supported end‑to‑end by the library. ### Authentication Flow Hardening - Enforce TLS for all auth endpoints and token transport; enable HSTS. - Implement rate limits per IP, account, and globally; add proof‑of‑work or CAPTCHA only as last resort. - Lockouts/throttling: progressive backoff; avoid permanent lockout via resets/alerts. - Uniform responses and code paths to reduce oracle/timing signals. ### Multi‑Factor Authentication (MFA) - Adopt phishing‑resistant factors by default for sensitive accounts: passkeys/WebAuthn (FIDO2) or hardware U2F. - Acceptable: TOTP (app‑based), smart cards with PIN. Avoid for sensitive use: SMS/voice, email codes; never rely on security questions. - Require MFA for: login, password/email changes, disabling MFA, privilege elevation, high‑value transactions, new devices/locations. - Risk‑based MFA signals: new device, geo‑velocity, IP reputation, unusual time, breached credentials. - MFA recovery: provide single‑use backup codes, encourage multiple factors, and require strong identity verification for resets. - Handle failed MFA: offer alternative enrolled methods, notify users of failures, and log context (no secrets). ### Federation and Protocols (OAuth 2.0 / OIDC / SAML) - Use standard protocols only; do not build your own. - OAuth 2.0/OIDC: - Prefer Authorization Code with PKCE for public/native apps; avoid Implicit and ROPC. - Validate state and nonce; use exact redirect URI matching; prevent open redirects. - Constrain tokens to audience/scope; use DPoP or mTLS for sender‑constraining when possible. - Rotate refresh tokens; revoke on logout or risk signals. - SAML: - TLS 1.2+; sign responses/assertions; encrypt sensitive assertions. - Validate issuers, InResponseTo, timestamps (NotBefore/NotOnOrAfter), Recipient; verify against trusted keys. - Prevent XML signature wrapping with strict schema validation and hardened XPath selection. - Keep response lifetimes short; prefer SP‑initiated flows; validate RelayState; implement replay detection. ### Tokens (JWT and Opaque) - Prefer opaque server‑managed tokens for simplicity and revocation. If using JWTs: - Explicitly pin algorithms; reject "none"; validate iss/aud/exp/iat/nbf; use short lifetimes and rotation. - Store secrets/keys securely (KMS/HSM). Use strong HMAC secrets or asymmetric keys; never hardcode. - Consider binding tokens to a client context (e.g., fingerprint hash in cookie) to reduce replay. - Implement denylist/allowlist for revocation on logout and critical events. ### Recovery and Reset - Return the same response for existing and non‑existing accounts (no enumeration). Normalize timing. - Generate 32+ byte, CSPRNG tokens; single‑use; store as hashes; short expiry. - Use HTTPS reset links to pinned, trusted domains; add referrer policy (no‑referrer) on UI. - After reset: require re‑authentication, rotate sessions, and do not auto‑login. - Never lock accounts due to reset attempts; rate‑limit and monitor instead. ### Administrative and Internal Accounts - Separate admin login from public forms; enforce stronger MFA, device posture checks, IP allowlists, and step‑up auth. - Use distinct session contexts and stricter timeouts for admin operations. ### Monitoring and Signals - Log auth events (failures/successes, MFA enroll/verify, resets, lockouts) with stable fields and correlation IDs; never log secrets or raw tokens. - Detect credential stuffing: high failure rates, many IPs/agents, impossible travel. Notify users of new device logins. ### Implementation Checklist - Passwords: Argon2id (preferred) with per‑user salt, constant‑time verify; breached password checks on change/set. - MFA: WebAuthn/passkeys or hardware tokens for high‑risk; TOTP as fallback; secure recovery with backup codes. - Federation: Authorization Code + PKCE; strict redirect URI validation; audience/scope enforced; token rotation. - Tokens: short‑lived, sender‑constrained where possible; revocation implemented; secrets in KMS/HSM. - Recovery: single‑use, hashed, time‑boxed tokens; consistent responses; re‑auth required after reset; sessions rotated. - Abuse: rate limits, throttling, and anomaly detection on auth endpoints; uniform error handling. - Admin: isolated flows with stricter policies and device checks. ### Test Plan - Unit/integration tests for login, MFA enroll/verify, resets, and lockouts with uniform errors. - Protocol tests: PKCE, state/nonce, redirect URI validation, token audience/scope. - Dynamic tests for credential stuffing resistance and token replay; validate revocation after logout and role change. ================================================ FILE: skills/software-security/rules/codeguard-0-authorization-access-control.md ================================================ --- description: Authorization and access control (RBAC/ABAC/ReBAC, IDOR, mass assignment, transaction auth) languages: - c - go - java - javascript - php - python - ruby - typescript - yaml alwaysApply: false --- rule_id: codeguard-0-authorization-access-control ## Authorization & Access Control Enforce least privilege and precise access decisions for every request and resource, prevent IDOR and mass assignment, and provide strong transaction authorization where necessary. ### Core Principles 1. Deny by Default: The default for any access request should be 'deny'. Explicitly grant permissions to roles or users rather than explicitly denying them. When no allow rule matches, return HTTP 403 Forbidden. 2. Principle of Least Privilege: Grant users the minimum level of access required to perform their job functions. Regularly audit permissions to ensure they are not excessive. 3. Validate Permissions on Every Request: Check authorization for every single request, regardless of source (AJAX, API, direct). Use middleware/filters to ensure consistent enforcement. 4. Prefer ABAC/ReBAC over RBAC: Use Attribute-Based Access Control (ABAC) or Relationship-Based Access Control (ReBAC) for fine-grained permissions instead of simple role-based access control. ### Systemic Controls - Centralize authorization at service boundaries via middleware/policies/filters. - Model permissions at the resource level (ownership/tenancy) and enforce scoping in data queries. - Return generic 403/404 responses to avoid leaking resource existence. - Log all denials with user, action, resource identifier (non-PII), and rationale code. ### Preventing IDOR - Never trust user-supplied identifiers alone. Always verify access to each object instance. - Resolve resources through user-scoped queries or server-side lookups. Example: `currentUser.projects.find(id)` instead of `Project.find(id)`. - Use non-enumerable identifiers (UUIDs/random) as defense-in-depth. Do not rely on obscurity alone. ### Preventing Mass Assignment - Do not bind request bodies directly to domain objects containing sensitive fields. - Expose only safe, editable fields via DTOs. Maintain explicit allow-lists for patch/update. - Use framework features to block-list sensitive fields if allow-listing is infeasible. ### Transaction Authorization (Step-Up) - Require a second factor for sensitive actions (wire transfers, privilege elevation, data export). Apply What‑You‑See‑Is‑What‑You‑Sign: show critical fields for user confirmation. - Use unique, time‑limited authorization credentials per transaction; reject on data changes mid‑flow. - Enforce the chosen authorization method server-side; prevent client‑side downgrades. - Protect against brute-force with throttling and complete flow restarts after failures. ### Testing and Automation - Maintain an authorization matrix (YAML/JSON) listing endpoints/resources, roles/attributes, and expected outcomes. - Automate integration tests that iterate the matrix, mint role tokens, and assert allow/deny results—including token expiry/revocation cases. - Exercise negative tests: swapped IDs, downgraded roles, missing scopes, and bypass attempts. ### Implementation Checklist - Middleware/policies enforce deny-by-default and resource checks on every endpoint. - Query scoping ensures users only access permitted rows/objects. - DTOs and allow-lists prevent mass assignment; sensitive fields never bindable. - Step-up authorization in place for sensitive operations with unique, short-lived credentials. - Authorization matrix drives CI tests; failures block merges. ================================================ FILE: skills/software-security/rules/codeguard-0-client-side-web-security.md ================================================ --- description: Client-side web security (XSS/DOM XSS, CSP, CSRF, clickjacking, XS-Leaks, third-party JS) languages: - c - html - javascript - php - typescript - vlang alwaysApply: false --- rule_id: codeguard-0-client-side-web-security ## Client‑side Web Security Protect browser clients against code injection, request forgery, UI redress, cross‑site leaks, and unsafe third‑party scripts with layered, context‑aware controls. ### XSS Prevention (Context‑Aware) - HTML context: prefer `textContent`. If HTML is required, sanitize with a vetted library (e.g., DOMPurify) and strict allow‑lists. - Attribute context: always quote attributes and encode values. - JavaScript context: do not build JS from untrusted strings; avoid inline event handlers; use `addEventListener`. - URL context: validate protocol/domain and encode; block `javascript:` and data URLs where inappropriate. - Redirects/forwards: never use user input directly for destinations; use server-side mapping (ID→URL) or validate against trusted domain allowlists. - CSS context: allow‑list values; never inject raw style text from users. Example sanitization: ```javascript const clean = DOMPurify.sanitize(userHtml, { ALLOWED_TAGS: ['b','i','p','a','ul','li'], ALLOWED_ATTR: ['href','target','rel'], ALLOW_DATA_ATTR: false }); ``` ### DOM‑based XSS and Dangerous Sinks - Prohibit `innerHTML`, `outerHTML`, `document.write` with untrusted data. - Prohibit `eval`, `new Function`, string‑based `setTimeout/Interval`. - Validate and encode data before assigning to `location` or event handler properties. - Use strict mode and explicit variable declarations to prevent global namespace pollution from DOM clobbering. - Adopt Trusted Types and enforce strict CSP to prevent DOM sinks exploitation. Trusted Types + CSP: ```http Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; require-trusted-types-for 'script' ``` ### Content Security Policy (CSP) - Prefer nonce‑based or hash‑based CSP over domain allow‑lists. - Start with Report‑Only mode; collect violations; then enforce. - Baseline to aim for: `default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests`. ### CSRF Defense - Fix XSS first; then layer CSRF defenses. - Use framework‑native CSRF protections and synchronizer tokens on all state‑changing requests. - Cookie settings: `SameSite=Lax` or `Strict`; sessions `Secure` and `HttpOnly`; use `__Host-` prefix when possible. - Validate Origin/Referer; require custom headers for API mutations in SPA token models. - Never use GET for state changes; validate tokens on POST/PUT/DELETE/PATCH only. Enforce HTTPS for all token transmission. ### Clickjacking Defense - Primary: `Content-Security-Policy: frame-ancestors 'none'` or a specific allow‑list. - Fallback for legacy browsers: `X-Frame-Options: DENY` or `SAMEORIGIN`. - Consider UX confirmations for sensitive actions when framing is required. ### Cross‑Site Leaks (XS‑Leaks) Controls - Use `SameSite` cookies appropriately; prefer `Strict` for sensitive actions. - Adopt Fetch Metadata protections to block suspicious cross‑site requests. - Isolate browsing contexts: COOP/COEP and CORP where applicable. - Disable caching and add user‑unique tokens for sensitive responses to prevent cache probing. ### Third‑Party JavaScript - Minimize and isolate: prefer sandboxed iframes with `sandbox` and postMessage origin checks. - Use Subresource Integrity (SRI) for external scripts and monitor for changes. - Provide a first‑party, sanitized data layer; deny direct DOM access from tags where possible. - Govern via tag manager controls and vendor contracts; keep libraries updated. SRI example: ```html ``` ### HTML5, CORS, WebSockets, Storage - postMessage: always specify exact target origin; verify `event.origin` on receive. - CORS: avoid `*`; allow‑list origins; validate preflights; do not rely on CORS for authz. - WebSockets: require `wss://`, origin checks, auth, message size limits, and safe JSON parsing. - Client storage: never store secrets in `localStorage`/`sessionStorage`; prefer HttpOnly cookies; if unavoidable, isolate via Web Workers. - Links: add `rel="noopener noreferrer"` to external `target=_blank` links. ### HTTP Security Headers (Client Impact) - HSTS: enforce HTTPS everywhere. - X‑Content‑Type‑Options: `nosniff`. - Referrer‑Policy and Permissions‑Policy: restrict sensitive signals and capabilities. ### AJAX and Safe DOM APIs - Avoid dynamic code execution; use function callbacks, not strings. - Build JSON with `JSON.stringify`; never via string concatenation. - Prefer creating elements and setting `textContent`/safe attributes over raw HTML insertion. ### Implementation Checklist - Contextual encoding/sanitization for every sink; no dangerous APIs without guards. - Strict CSP with nonces and Trusted Types; violations monitored. - CSRF tokens on all state‑changing requests; secure cookie attributes. - Frame protections set; XS‑Leak mitigations enabled (Fetch Metadata, COOP/COEP/CORP). - Third‑party JS isolated with SRI and sandbox; vetted data layer only. - HTML5/CORS/WebSocket usage hardened; no secrets in web storage. - Security headers enabled and validated. ### Test Plan - Automated checks for dangerous DOM/API patterns. - E2E tests for CSRF and clickjacking; CSP report monitoring. - Manual probes for XS‑Leaks (frame count, timing, cache) and open redirect behavior. ================================================ FILE: skills/software-security/rules/codeguard-0-cloud-orchestration-kubernetes.md ================================================ --- description: Kubernetes hardening (RBAC, admission policies, network policies, secrets, supply chain) languages: - javascript - yaml alwaysApply: false --- rule_id: codeguard-0-cloud-orchestration-kubernetes ## Cloud & Orchestration (Kubernetes) Kubernetes cluster and workload hardening: identity, policy, networking, secrets, and supply chain controls. ### Controls - Identity & RBAC: least privilege for users and service accounts; separate namespaces; bind only needed roles. - Policy: admission controls (OPA/Gatekeeper/Kyverno) for image sources, capabilities, root, network policies, and required labels/annotations. - Networking: default‑deny with network policies; explicit egress allow‑lists; service identity/mTLS within mesh where applicable. - Secrets: use KMS providers; avoid plaintext in manifests; rotate regularly; restrict secret mount paths. - Nodes: hardened OS, auto‑updates, minimal attack surface; isolate sensitive workloads with taints/tolerations and dedicated nodes. - Supply chain: verify image signatures; enforce provenance (SLSA/Sigstore) in admission. ### Checklist - Namespaces per team/app; RBAC roles scoped; audit logging enabled. - Admission policies enforce image provenance, non‑root, dropped capabilities, read‑only root FS, and network policy presence. - Network policies in place for ingress/egress; service accounts scoped per deployment. ### Verification - Cluster conformance and CIS benchmark scans. - Policy tests in CI for manifests (OPA unit tests); periodic admission dry‑run. ### Incident Readiness - Enable audit logs and centralize; restrict access to etcd; backup/restore tested. - Define break‑glass roles with MFA and time‑bound approvals. ================================================ FILE: skills/software-security/rules/codeguard-0-data-storage.md ================================================ --- description: Data & storage security (DB isolation, TLS, least privilege, RLS/CLS, backups, auditing) languages: - c - javascript - sql - yaml alwaysApply: false --- rule_id: codeguard-0-data-storage ## Database Security Guidelines This rule advises on securely configuring SQL and NoSQL databases to protect against data breaches and unauthorized access: - Backend Database Protection - Isolate database servers from other systems and limit host connections. - Disable network (TCP) access when possible; use local socket files or named pipes. - Configure database to bind only on localhost when appropriate. - Restrict network port access to specific hosts with firewall rules. - Place database server in separate DMZ isolated from application server. - Never allow direct connections from thick clients to backend database. - Transport Layer Security - Configure database to only allow encrypted connections. - Install trusted digital certificates on database servers. - Use TLSv1.2+ with modern ciphers (AES-GCM, ChaCha20) for client connections. - Verify digital certificate validity in client applications. - Ensure all database traffic is encrypted, not just initial authentication. - Secure Authentication Configuration - Always require authentication, including from local server connections. - Protect accounts with strong, unique passwords. - Use dedicated accounts per application or service. - Configure minimum required permissions only. - Regularly review accounts and permissions. - Remove accounts when applications are decommissioned. - Change passwords when staff leave or compromise is suspected. - Database Credential Storage - Never store credentials in application source code. - Store credentials in configuration files outside web root. - Set appropriate file permissions for credential access. - Never check credential files into source code repositories. - Encrypt credential storage using built-in functionality when available. - Use environment variables or secrets management solutions. - Secure Permission Management - Apply principle of least privilege to all database accounts. - Do not use built-in root, sa, or SYS accounts. - Do not grant administrative rights to application accounts. - Restrict account connections to allowed hosts only. - Use separate databases and accounts for Development, UAT, and Production. - Grant only required permissions (SELECT, UPDATE, DELETE as needed). - Avoid making accounts database owners to prevent privilege escalation. - Implement table-level, column-level, and row-level permissions when needed. - Database Configuration and Hardening - Install required security updates and patches regularly. - Run database services under low-privileged user accounts. - Remove default accounts and sample databases. - Store transaction logs on separate disk from main database files. - Configure regular encrypted database backups with proper permissions. - Disable unnecessary stored procedures and dangerous features. - Implement database activity monitoring and alerting. - Platform-Specific Hardening - SQL Server: Disable xp_cmdshell, CLR execution, SQL Browser service, Mixed Mode Authentication (unless required). - MySQL/MariaDB: Run mysql_secure_installation, disable FILE privilege for users. - PostgreSQL: Follow PostgreSQL security documentation guidelines. - MongoDB: Implement MongoDB security checklist requirements. - Redis: Follow Redis security guide recommendations. Summary: Isolate database systems, enforce encrypted connections, implement strong authentication, store credentials securely using secrets management, apply least privilege permissions, harden database configurations, and maintain regular security updates and monitoring. ================================================ FILE: skills/software-security/rules/codeguard-0-devops-ci-cd-containers.md ================================================ --- description: DevOps, CI/CD, and containers (pipeline hardening, artifacts, Docker/K8s images, virtual patching, toolchain) languages: - docker - javascript - powershell - shell - xml - yaml alwaysApply: false --- rule_id: codeguard-0-devops-ci-cd-containers ## DevOps, CI/CD, and Containers Secure the build, packaging, and deployment supply chain: protect pipelines and artifacts, harden containers, and use virtual patching and toolchain flags when necessary. ### CI/CD Pipeline Security - Repos: protected branches; mandatory reviews; signed commits. - Secrets: never hardcode; fetch at runtime from vault/KMS; mask in logs. - Least privilege: ephemeral, isolated runners with minimal permissions. - Security gates in CI: SAST, SCA, DAST, IaC scanning; block on criticals. - Dependencies: pin via lockfiles; verify integrity; use private registries. - Sign everything: commits and artifacts (containers/jars) and verify prior to deploy; adopt SLSA provenance. ### Docker and Container Hardening - User: run as non‑root; set `USER` in Dockerfile - Use `--security-opt=no-new-privileges` to prevent privilege escalation. - Capabilities: `--cap-drop all` and add only what you need; never `--privileged`. - Daemon socket: never mount `/var/run/docker.sock` - DO NOT enable TCP Docker daemon socket (`-H tcp://0.0.0.0:XXX`) without TLS. - Avoid `- "/var/run/docker.sock:/var/run/docker.sock"` in docker-compose files. - Filesystems: read‑only root, tmpfs for temp write; resource limits (CPU/mem). - Networks: avoid host network; define custom networks; limit exposed ports. - Images: minimal base (distroless/alpine), pin tags and digests; remove package managers and tools from final image; add `HEALTHCHECK`. - Secrets: Docker/Kubernetes secrets; never in layers/env; mount via runtime secrets. - Scanning: scan images on build and admission; block high‑severity vulns. ### Node.js in Containers - Deterministic builds: `npm ci --omit=dev`; pin base image with digest. - Production env: `ENV NODE_ENV=production`. - Non‑root: copy with correct ownership and drop to `USER node`. - Signals: use an init (e.g., `dumb-init`) and implement graceful shutdown handlers. - Multi‑stage builds: separate build and runtime; mount secrets via BuildKit; use `.dockerignore`. ### Virtual Patching (Temporary Mitigation) - Use WAF/IPS/ModSecurity for immediate protection when code fixes are not yet possible. - Prefer positive security rules (allow‑list) for accuracy; avoid exploit‑specific signatures. - Process: prepare tooling in advance; analyze CVEs; implement patches in log‑only first, then enforce; track and retire after code fix. ### C/C++ Toolchain Hardening (when applicable) - Compiler: `-Wall -Wextra -Wconversion`, `-fstack-protector-all`, PIE (`-fPIE`/`-pie`), `_FORTIFY_SOURCE=2`, CFI (`-fsanitize=cfi` with LTO). - Linker: RELRO/now, noexecstack, NX/DEP and ASLR. - Debug vs Release: enable sanitizers in debug; enable hardening flags in release; assert in debug only. - CI checks: verify flags (`checksec`) and fail builds if protections missing. ### Implementation Checklist - Pipeline: secrets in vault; ephemeral runners; security scans; signed artifacts with provenance. - Containers: non‑root, least privilege, read‑only FS, resource limits; no daemon socket mounts. - Images: minimal, pinned, scanned; healthchecks; `.dockerignore` maintained. - Node images: `npm ci`, `NODE_ENV=production`, proper init and shutdown. - Virtual patching: defined process; accurate rules; logs; retirement after fix. - Native builds: hardening flags enabled and verified in CI. ================================================ FILE: skills/software-security/rules/codeguard-0-file-handling-and-uploads.md ================================================ --- description: Secure file handling & uploads (validation, storage isolation, scanning, safe delivery) languages: - c - go - java - javascript - php - python - ruby - typescript alwaysApply: false --- rule_id: codeguard-0-file-handling-and-uploads ## File Upload Security Guidelines This rule advises on secure file upload practices to prevent malicious file attacks and protect system integrity: - Extension Validation - List allowed extensions only for business-critical functionality. - Ensure input validation is applied before validating extensions. - Avoid double extensions (e.g., `.jpg.php`) and null byte injection (e.g., `.php%00.jpg`). - Use allowlist approach rather than denylist for file extensions. - Validate extensions after decoding filename to prevent bypass attempts. - Content Type and File Signature Validation - Never trust client-supplied Content-Type headers as they can be spoofed. - Validate file signatures (magic numbers) in conjunction with Content-Type checking. - Implement allowlist approach for MIME types as a quick protection layer. - Use file signature validation but not as a standalone security measure. - Filename Security - Generate random filenames (UUID/GUID) instead of using user-supplied names. - If user filenames required, implement maximum length limits. - Restrict characters to alphanumeric, hyphens, spaces, and periods only. - Prevent leading periods (hidden files) and sequential periods (directory traversal). - Avoid leading hyphens or spaces for safer shell script processing. - File Content Validation - For images, apply image rewriting techniques to destroy malicious content. - For Microsoft documents, use Apache POI for validation. - Avoid ZIP files due to numerous attack vectors. - Implement manual file review in sandboxed environments when resources allow. - Integrate antivirus scanning and Content Disarm & Reconstruct (CDR) for applicable file types. - Storage Security - Store files on different servers for complete segregation when possible. - Store files outside webroot with administrative access only. - If storing in webroot, set write-only permissions with proper access controls. - Use application handlers that map IDs to filenames for public access. - Consider database storage for specific use cases with DBA expertise. - Access Control and Authentication - Require user authentication before allowing file uploads. - Implement proper authorization levels for file access and modification. - Set filesystem permissions on principle of least privilege. - Scan files before execution if execution permission is required. - Upload and Download Limits - Set proper file size limits for upload protection. - Consider post-decompression size limits for compressed files. - Implement request limits for download services to prevent DoS attacks. - Use secure methods to calculate ZIP file sizes safely. - Additional Security Measures - Protect file upload endpoints from CSRF attacks. - Keep all file processing libraries securely configured and updated. - Implement logging and monitoring for upload activities. - Provide user reporting mechanisms for illegal content. - Use secure extraction methods for compressed files. Summary: Implement defense-in-depth for file uploads through multi-layered validation, secure storage practices, proper access controls, and comprehensive monitoring. Never rely on single validation methods and always generate safe filenames to prevent attacks. ================================================ FILE: skills/software-security/rules/codeguard-0-framework-and-languages.md ================================================ --- description: Framework & language security guides (Django/DRF, Laravel/Symfony/Rails, .NET, Java/JAAS, Node.js, PHP config) languages: - c - java - javascript - kotlin - php - python - ruby - typescript - xml - yaml alwaysApply: false --- rule_id: codeguard-0-framework-and-languages ## Framework & Language Guides Apply secure‑by‑default patterns per platform. Harden configurations, use built‑in protections, and avoid common pitfalls. ### Django - Disable DEBUG in production; keep Django and deps updated. - Enable `SecurityMiddleware`, clickjacking middleware, MIME sniffing protection. - Force HTTPS (`SECURE_SSL_REDIRECT`); configure HSTS; set secure cookie flags (`SESSION_COOKIE_SECURE`, `CSRF_COOKIE_SECURE`). - CSRF: ensure `CsrfViewMiddleware` and `{% csrf_token %}` in forms; proper AJAX token handling. - XSS: rely on template auto‑escaping; avoid `mark_safe` unless trusted; use `json_script` for JS. - Auth: use `django.contrib.auth`; validators in `AUTH_PASSWORD_VALIDATORS`. - Secrets: generate via `get_random_secret_key`; store in env/secrets manager. ### Django REST Framework (DRF) - Set `DEFAULT_AUTHENTICATION_CLASSES` and restrictive `DEFAULT_PERMISSION_CLASSES`; never leave `AllowAny` for protected endpoints. - Always call `self.check_object_permissions(request, obj)` for object‑level authz. - Serializers: explicit `fields=[...]`; avoid `exclude` and `"__all__"`. - Throttling: enable rate limits (and/or at gateway/WAF). - Disable unsafe HTTP methods where not needed. Avoid raw SQL; use ORM/parameters. ### Laravel - Production: `APP_DEBUG=false`; generate app key; secure file perms. - Cookies/sessions: enable encryption middleware; set `http_only`, `same_site`, `secure`, short lifetimes. - Mass assignment: use `$request->only()` / `$request->validated()`; avoid `$request->all()`. - SQLi: use Eloquent parameterization; validate dynamic identifiers. - XSS: rely on Blade escaping; avoid `{!! ... !!}` for untrusted data. - File uploads: validate `file`, size, and `mimes`; sanitize filenames with `basename`. - CSRF: ensure middleware and form tokens enabled. ### Symfony - XSS: Twig auto‑escaping; avoid `|raw` unless trusted. - CSRF: use `csrf_token()` and `isCsrfTokenValid()` for manual flows; Forms include tokens by default. - SQLi: Doctrine parameterized queries; never concatenate inputs. - Command execution: avoid `exec/shell_exec`; use Filesystem component. - Uploads: validate with `#[File(...)]`; store outside public; unique names. - Directory traversal: validate `realpath`/`basename` and enforce allowed roots. - Sessions/security: configure secure cookies and authentication providers/firewalls. ### Ruby on Rails - Avoid dangerous functions: ```ruby eval("ruby code here") system("os command here") `ls -al /` # (backticks contain os command) exec("os command here") spawn("os command here") open("| os command here") Process.exec("os command here") Process.spawn("os command here") IO.binread("| os command here") IO.binwrite("| os command here", "foo") IO.foreach("| os command here") {} IO.popen("os command here") IO.read("| os command here") IO.readlines("| os command here") IO.write("| os command here", "foo") ``` - SQLi: always parameterize; use `sanitize_sql_like` for LIKE patterns. - XSS: default auto‑escape; avoid `raw`, `html_safe` on untrusted data; use `sanitize` allow‑lists. - Sessions: database‑backed store for sensitive apps; force HTTPS (`config.force_ssl = true`). - Auth: use Devise or proven libraries; configure routes and protected areas. - CSRF: `protect_from_forgery` for state‑changing actions. - Secure redirects: validate/allow‑list targets. - Headers/CORS: set secure defaults; configure `rack-cors` carefully. ### .NET (ASP.NET Core) - Keep runtime and NuGet packages updated; enable SCA in CI. - Authz: use `[Authorize]` attributes; perform server‑side checks; prevent IDOR. - Authn/sessions: ASP.NET Identity; lockouts; cookies `HttpOnly`/`Secure`; short timeouts. - Crypto: use PBKDF2 for passwords, AES‑GCM for encryption; DPAPI for local secrets; TLS 1.2+. - Injection: parameterize SQL/LDAP; validate with allow‑lists. - Config: enforce HTTPS redirects; remove version headers; set CSP/HSTS/X‑Content‑Type‑Options. - CSRF: anti‑forgery tokens on state‑changing actions; validate on server. ### Java and JAAS - SQL/JPA: use `PreparedStatement`/named parameters; never concatenate input. - XSS: allow‑list validation; sanitize output with reputable libs; encode for context. - Logging: parameterized logging to prevent log injection. - Crypto: AES‑GCM; secure random nonces; never hardcode keys; use KMS/HSM. - JAAS: configure `LoginModule` stanzas; implement `initialize/login/commit/abort/logout`; avoid exposing credentials; segregate public/private credentials; manage subject principals properly. ### Node.js - Limit request sizes; validate and sanitize input; escape output. - Avoid `eval`, `child_process.exec` with user input; use `helmet` for headers; `hpp` for parameter pollution. - Rate limit auth endpoints; monitor event loop health; handle uncaught exceptions cleanly. - Cookies: set `secure`, `httpOnly`, `sameSite`; set `NODE_ENV=production`. - Keep packages updated; run `npm audit`; use security linters and ReDoS testing. ### PHP Configuration - Production php.ini: `expose_php=Off`, log errors not display; restrict `allow_url_fopen/include`; set `open_basedir`. - Disable dangerous functions; set session cookie flags (`Secure`, `HttpOnly`, `SameSite=Strict`); enable strict session mode. - Constrain upload size/number; set resource limits (memory, post size, execution time). - Use Snuffleupagus or similar for additional hardening. ### Implementation Checklist - Use each framework’s built‑in CSRF/XSS/session protections and secure cookie flags. - Parameterize all data access; avoid dangerous OS/exec functions with untrusted input. - Enforce HTTPS/HSTS; set secure headers. - Centralize secret management; never hardcode secrets; lock down debug in production. - Validate/allow‑list redirects and dynamic identifiers. - Keep dependencies and frameworks updated; run SCA and static analysis regularly. ================================================ FILE: skills/software-security/rules/codeguard-0-iac-security.md ================================================ --- description: Infrastructure as Code Security languages: - c - d - javascript - powershell - ruby - shell - yaml alwaysApply: false --- rule_id: codeguard-0-iac-security # Infrastructure as Code (IaC) Security When designing cloud infrastructure and writing Infrastructure as Code (IaC) in languages like Terraform and CloudFormation, always use secure practices and defaults such as preventing public exposure and follow the principle of least privilege. Actively identify security misconfigurations and provide secure alternatives. ## Critical Security Patterns In Infrastructure as Code ### Network security - **ALWAYS** restrict the access to remote administrative services, databases, LDAP, TACACS+, or other sensitive services. No service should be accessible from the entire Internet if it does not need to be. Instead, restrict access to a specific set of IP addresses or CIDR blocks which require access. - Security Group and ACL inbound rules should **NEVER** allow `0.0.0.0/0` to remote administration ports (such as SSH 22, RDP 3389). - Security Group and ACL inbound rules should **NEVER** allow `0.0.0.0/0` to database ports (such as 3306, 5432, 1433, 1521, 27017). - Kubernetes API endpoints allow lists should **NEVER** allow `0.0.0.0/0`. EKS, AKS, GKE, and any other Kubernetes API endpoint should be restricted to an allowed list of CIDR addresses which require administrative access. - **NEVER** expose cloud platform database services (RDS, Azure SQL, Cloud SQL) to all IP addresses `0.0.0.0/0`. - Generally prefer private networking, such as internal VPC, VNET, VPN, or other internal transit unless public network access is required. - **ALWAYS** enable VPC/VNET flow logs for network monitoring and security analysis. - **ALWAYS** implement default deny rules and explicit allow rules for required traffic only. - Generally prefer blocking egress traffic to the Internet by default. If egress is required appropriate traffic control solutions might include: - Egress firewall or proxy with rules allowing access to specific required services. - Egress security group (SG) or access control list (ACL) with rules allowing access to specific required IPs or CIDR blocks. - DNS filtering to prevent access to malicious domains. ### Data protection - **ALWAYS** configure data encryption at rest for all storage services including databases, file systems, object storage, and block storage. - Enable encryption for cloud storage services (S3, Azure Blob, GCS buckets). - Configure database encryption at rest for all database engines (RDS, Azure SQL, Cloud SQL, DocumentDB, etc.). - Enable EBS/disk encryption for virtual machine storage volumes. - **ALWAYS** configure encryption in transit for all data communications. - Use TLS 1.2 or higher for all HTTPS/API communications. - Configure SSL/TLS for database connections with certificate validation. - Enable encryption for inter-service communication within VPCs/VNETs. - Use encrypted protocols for remote access (SSH, HTTPS, secure RDP). - **ALWAYS** implement data classification and protection controls based on sensitivity levels. - Apply stricter encryption and access controls for PII, PHI, financial data, and intellectual property. - Use separate encryption keys for different data classification levels. - **ALWAYS** configure secure data retention and disposal policies. - Define data retention periods based on regulatory and business requirements. - Implement automated data lifecycle management with secure deletion. - **ALWAYS** enable comprehensive data access monitoring and auditing. - Log all data access, modification, and deletion operations. - Monitor for unusual data access patterns and potential data exfiltration. - Implement real-time alerting for sensitive data access violations. - **ALWAYS** encrypt data backups. - Encrypt all backup data using separate encryption keys from production data. - Store backups in geographically distributed locations with appropriate access controls. - Test backup restoration procedures regularly and verify backup integrity. ### Access control - **NEVER** leave critical administration or data services with anonymous access (backups, storage, container registries, file shares) unless otherwise labeled as public classification or intended to be public. - **NEVER** use wildcard permissions in IAM policies or cloud RBAC (`"Action": "*"`, `"Resource": "*"`) - **NEVER** overprivilege service accounts with Owner/Admin roles when it is not necessary. - **NEVER** use service API Keys and client secrets and instead use workload identity with role-based access control to eliminate the need for long-lived credentials. - **NEVER** enable or use the legacy Instance Metadata Service version 1 (IMDSv1) in AWS. - **NEVER** use legacy or outdated authentication methods (such as local users) when there is a more secure alternative such as OAuth. ### Container and VM images - **NEVER** use non-hardened VM and container images. - **ALWAYS** choose distroless or minimal container images. - **RECOMMEND** using secure baseline virtual machine images from trusted sources. - **RECOMMEND** using minimal distroless container images from trusted sources. ### Logging and administrative access - **NEVER** disable administrative activity logging for sensitive services. - **ALWAYS** enable audit logging for privileged operations. ### Secrets management - **NEVER** hardcode secrets, passwords, API keys, or certificates directly in IaC source code. - **ALWAYS** in Terraform mark secrets with "sensitive = true", in other IaC code use appropriate annotations or metadata to indicate sensitive values. ### Backup and data recovery - **NEVER** create backups without encryption at rest and in transit. - **ALWAYS** configure multi-region data storage for backups with cross-region replication. - **NEVER** configure backups without retention policies and lifecycle management. ================================================ FILE: skills/software-security/rules/codeguard-0-input-validation-injection.md ================================================ --- description: Input validation and injection defense (SQL/SOQL/LDAP/OS), parameterization, prototype pollution languages: - apex - c - go - html - java - javascript - php - powershell - python - ruby - shell - sql - typescript alwaysApply: false --- rule_id: codeguard-0-input-validation-injection ## Input Validation & Injection Defense Ensure untrusted input is validated and never interpreted as code. Prevent injection across SQL, LDAP, OS commands, templating, and JavaScript runtime object graphs. ### Core Strategy - Validate early at trust boundaries with positive (allow‑list) validation and canonicalization. - Treat all untrusted input as data, never as code. Use safe APIs that separate code from data. - Parameterize queries/commands; escape only as last resort and context‑specific. ### Validation Playbook - Syntactic validation: enforce format, type, ranges, and lengths for each field. - Semantic validation: enforce business rules (e.g., start ≤ end date, enum allow‑lists). - Normalization: canonicalize encodings before validation; validate complete strings (regex anchors ^$); beware ReDoS. - Free‑form text: define character class allow‑lists; normalize Unicode; set length bounds. - Files: validate by content type (magic), size caps, and safe extensions; server‑generate filenames; scan; store outside web root. ### SQL Injection Prevention - Use prepared statements and parameterized queries for 100% of data access. - Use bind variables for any dynamic SQL construction within stored procedures and never concatenate user input into SQL. - Prefer least‑privilege DB users and views; never grant admin to app accounts. - Escaping is fragile and discouraged; parameterization is the primary defense. Example (Java PreparedStatement): ```java String custname = request.getParameter("customerName"); String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( ); ``` ### SOQL/SOSL Injection (Salesforce) SOQL and SOSL are query/search languages (no SQL-style DDL/DML). Data changes are performed via Apex DML or Database methods. Note: SOQL can lock rows via `FOR UPDATE`. - Primary risk: data exfiltration by bypassing intended query filters/business logic; impact is amplified when Apex runs with elevated access (system mode) or when CRUD/FLS aren't enforced. - Second-order risk (conditional): if queried records are passed to DML, injection can broaden the record set and cause unintended mass updates/deletes. - Prefer static SOQL/SOSL with bind variables: `[SELECT Id FROM Account WHERE Name = :userInput]` or `FIND :term`. - For dynamic SOQL, use `Database.queryWithBinds()`; for dynamic SOSL, use `Search.query()`. Allow‑list any dynamic identifiers. If concatenation is unavoidable, escape string values with `String.escapeSingleQuotes()`. - Enforce CRUD/FLS with `WITH USER_MODE` or `WITH SECURITY_ENFORCED` (don't combine both). Enforce record sharing with `with sharing` or user-mode operations. Use `Security.stripInaccessible()` before DML. ### LDAP Injection Prevention - Always apply context‑appropriate escaping: - DN escaping for `\ # + < > , ; " =` and leading/trailing spaces - Filter escaping for `* ( ) \ NUL` - Validate inputs with allow‑lists before constructing queries; use libraries that provide DN/filter encoders. - Use least‑privilege LDAP connections with bind authentication; avoid anonymous binds for application queries. ### OS Command Injection Defense - Prefer built‑in APIs instead of shelling out (e.g., library calls over `exec`). - If unavoidable, use structured execution that separates command and arguments (e.g., ProcessBuilder). Do not invoke shells. - Strictly allow‑list commands and validate arguments with allow‑list regex; exclude metacharacters (& | ; $ > < ` \ ! ' " ( ) and whitespace as needed). - Use `--` to delimit arguments where supported to prevent option injection. Example (Java ProcessBuilder): ```java ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "Arg1", "Arg2"); Map env = pb.environment(); pb.directory(new File("TrustedDir")); Process p = pb.start(); ``` ### Query Parameterization Guidance - Use the platform’s parameterization features (JDBC PreparedStatement, .NET SqlCommand, Ruby ActiveRecord bind params, PHP PDO, SQLx bind, etc.). - For stored procedures, ensure parameters are bound; never build dynamic SQL via string concatenation inside procedures. ### Prototype Pollution (JavaScript) - Developers should use `new Set()` or `new Map()` instead of using object literals - When objects are required, create with `Object.create(null)` or `{ __proto__: null }` to avoid inherited prototypes. - Freeze or seal objects that should be immutable; consider Node `--disable-proto=delete` as defense‑in‑depth. - Avoid unsafe deep merge utilities; validate keys against allow‑lists and block `__proto__`, `constructor`, `prototype`. ### Caching and Transport - Apply `Cache-Control: no-store` on responses containing sensitive data; enforce HTTPS across data flows. ### Implementation Checklist - Central validators: types, ranges, lengths, enums; canonicalization before checks. - 100% parameterization coverage for SQL; dynamic identifiers via allow‑lists only. - LDAP DN/filter escaping in use; inputs validated prior to query. - No shell invocation for untrusted input; if unavoidable, structured exec + allow‑list + regex validation. - JS object graph hardened: safe constructors, blocked prototype paths, safe merge utilities. - File uploads validated by content, size, and extension; stored outside web root and scanned. ### Test Plan - Static checks for string concatenation in queries/commands and dangerous DOM/merge sinks. - Fuzzing for SQL/LDAP/OS injection vectors; unit tests for validator edge cases. - Negative tests exercising blocked prototype keys and deep merge behavior. ================================================ FILE: skills/software-security/rules/codeguard-0-logging.md ================================================ --- description: Logging & monitoring (structured telemetry, redaction, integrity, detection & alerting) languages: - c - javascript - yaml alwaysApply: false --- rule_id: codeguard-0-logging ## Logging & Monitoring Produce structured, privacy‑aware telemetry that supports detection, response, and forensics without exposing secrets. ### What to Log - Authn/authz events; admin actions; config changes; sensitive data access; input validation failures; security errors. - Include correlation/request IDs, user/session IDs (non‑PII), source IP, user agent, timestamps (UTC, RFC3339). ### How to Log - Structured logs (JSON) with stable field names; avoid free‑form text for critical signals. - Sanitize all log inputs to prevent log injection (strip CR/LF/delimiters); validate data from other trust zones. - Redact/tokenize secrets and sensitive fields; never log credentials, tokens, recovery codes, or raw session IDs. - Ensure integrity: append‑only or WORM storage; tamper detection; centralized aggregation; access controls and retention policies. ### Detection & Alerting - Build alerts for auth anomalies (credential stuffing patterns, impossible travel), privilege changes, excessive failures, SSRF indicators, and data exfil patterns. - Tune thresholds; provide runbooks; ensure on‑call coverage; test alert flows. ### Storage & Protection - Isolate log storage (separate partition/database); strict file/directory permissions; store outside web‑accessible locations. - Synchronize time across systems; use secure protocols for transmission; implement tamper detection and monitoring. ### Privacy & Compliance - Maintain data inventory and classification; minimize personal data in logs; honor retention and deletion policies. - Provide mechanisms to trace and delete user‑linked log data where required by policy. ### Implementation Checklist - JSON logging enabled; log injection sanitization active; redaction filters active; correlation IDs on all requests. - Isolated log storage with tamper detection; centralized log pipeline with integrity protections; retention configured. - Security alerts defined and tested; dashboards and reports in place. ### Validation - Unit/integration tests assert presence/absence of key fields; redaction unit tests. - Periodic audits for secret/PII leakage; tabletop exercises for incident workflows. ================================================ FILE: skills/software-security/rules/codeguard-0-mcp-security.md ================================================ --- description: MCP (Model Context Protocol) Security based on CoSAI MCP Security guidelines languages: - python - javascript - typescript - go - rust - java alwaysApply: false --- rule_id: codeguard-0-mcp-security # MCP (Model Context Protocol) Security Guidelines NEVER deploy MCP servers or clients without implementing proper security controls. ### Workload Identity and Authentication - Use SPIFFE/SPIRE for cryptographic workload identities - SPIFFE (Secure Production Identity Framework For Everyone) provides a standard for service identity - SPIRE (SPIFFE Runtime Environment) issues and rotates short-lived cryptographic identities (SVIDs) ### Input and Data Sanitization - Validate ALL inputs using allowlists at every trust boundary - Sanitize file paths through canonicalization - Use parameterized queries for database operations - Apply context-aware output encoding (SQL, shell, HTML) - Sanitize tool outputs: return only minimum fields, redact all PII and sensitive data - Treat ALL inputs, tool schemas, metadata, prompts, and resource content as untrusted input - Deploy prompt injection detection systems - Use strict JSON schemas to maintain boundaries between instructions and data ### Sandboxing and Isolation - Design MCP servers to execute with least privilege - MCP servers interacting with host environment (files, commands, network) MUST implement sandboxing controls - LLM-generated code MUST NOT run with full user privileges - Implement additional sandboxing layers: gVisor, Kata Containers, SELinux sandboxes ### Cryptographic Verification of Resources - Provide cryptographic signatures and SBOMs for all server code - Implement signature verification in your MCP client before loading servers - Use TLS for ALL data in transit - Implement remote attestation capabilities to verify servers are running expected code ### Transport Layer Security #### stdio Transport (Local Servers) - STRONGLY RECOMMENDED for local MCP to eliminate DNS rebinding risks - Direct pipe-based stream communication - Implement sandbox to prevent privilege escalation #### HTTP Streaming Transport (Remote Servers) Required security controls to implement: - Payload Limits (prevent large payload and recursive payload DoS) - Rate limiting for tool calls and transport requests - Client-Server Authentication/Authorization - Mutual TLS Authentication - TLS Encryption - CORS Protection - CSRF Protection - Integrity Checks (prevent replay, spoofing, poisoned responses) ### Secure Tool and UX Design - Create single-purpose tools with explicit boundaries; avoid "do anything" tools - Do not rely on the LLM for validation or authorization decisions - Use two-stage commit for high-impact actions: draft/preview first, explicit commit with confirmation second - Provide rollback/undo paths (draft IDs, snapshots, reversible actions) and time-bound commits when possible ### Human-in-the-Loop - Implement confirmation prompts for risky operations in your MCP server - Use elicitation on MCP server side to request user confirmation of risky actions - Security-relevant messages MUST clearly indicate implications - Do NOT rely solely on human approval (users can become fatigued) ### Logging and Observability - Implement logging in your MCP servers and clients - Log: tools that were used, parameters, originating prompt - Use OpenTelemetry for end-to-end linkability of actions - Maintain immutable records of actions and authorizations --- ## Deployment Pattern Security ### All-Local (stdio or http) - Security depends entirely on host system posture - Use `stdio` transport to avoid DNS rebinding risks - Use sandboxing to limit privilege escalation attacks - Appropriate for development and personal use ### Single-Tenant Remote (http) - Authentication between client and server is REQUIRED - Use secure credential storage (OS keychains, secret managers) - Communication MUST be authenticated and encrypted - Enterprise clients should enforce authenticated server discovery with explicit allowlists ### Multi-Tenant Remote (http) - Require robust tenant isolation, identity, and access control - Implement strong multi-tenancy controls (per-tenant encryption, role-based access control) - Prefer MCP servers hosted directly by service provider - Provide remote attestation when possible ================================================ FILE: skills/software-security/rules/codeguard-0-mobile-apps.md ================================================ --- description: 'Mobile app security (iOS/Android): storage, transport, code integrity, biometrics, permissions' languages: - java - javascript - kotlin - matlab - perl - swift - xml alwaysApply: false --- rule_id: codeguard-0-mobile-apps ## Mobile Application Security Guidelines Essential security practices for developing secure mobile applications across iOS and Android platforms. ### Architecture and Design Implement secure design principles from the start: - Follow least privilege and defense in depth principles - Use standard secure authentication protocols (OAuth2, JWT) - Perform all authentication and authorization checks server-side - Request only necessary permissions for app and backend services - Establish security controls for app updates, patches, and releases - Use only trusted and validated third-party libraries and components ### Authentication and Authorization Never trust the client for security decisions: - Perform authentication/authorization server-side only - Do not store user passwords on device; use revocable access tokens - Avoid hardcoding credentials in the mobile app - Encrypt credentials in transmission - Use platform-specific secure storage (iOS Keychain, Android Keystore) - Require password complexity and avoid short PINs (4 digits) - Implement session timeouts and remote logout functionality - Require re-authentication for sensitive operations - Use platform-supported biometric authentication with secure fallbacks ### Data Storage and Privacy Protect sensitive data at rest and in transit: - Encrypt sensitive data using platform APIs; avoid custom encryption - Leverage hardware-based security features (Secure Enclave, Strongbox) - Store private data on device's internal storage only - Minimize PII collection to necessity and implement automatic expiration - Avoid caching, logging, or background snapshots of sensitive data - Always use HTTPS for network communications ### Network Communication Assume all network communication is insecure: - Use HTTPS for all network communication - Do not override SSL certificate validation for self-signed certificates - Use strong, industry standard cipher suites with appropriate key lengths - Use certificates signed by trusted CA providers - Consider certificate pinning for additional security - Encrypt data even if sent over SSL - Avoid sending sensitive data via SMS ### Code Quality and Integrity Maintain application security throughout development: - Use static analysis tools to identify vulnerabilities - Make security a focal point during code reviews - Keep all libraries up to date to patch known vulnerabilities - Disable debugging in production builds - Include code to validate integrity of application code - Obfuscate the app binary - Implement runtime anti-tampering controls: - Check for debugging, hooking, or code injection - Detect emulator or rooted/jailbroken devices - Verify app signatures at runtime ### Platform-Specific Security #### Android Security - Use Android's ProGuard for code obfuscation - Avoid storing sensitive data in SharedPreferences - Disable backup mode to prevent sensitive data in backups - Use Android Keystore with hardware backing (TEE or StrongBox) - Implement Google's Play Integrity API for device and app integrity checks #### iOS Security - Configure Shortcuts permissions to require device unlock for sensitive actions - Set Siri intent `requiresUserAuthentication` to true for sensitive functionality - Implement authentication checks on deep link endpoints - Use conditional logic to mask sensitive widget content on lock screen - Store sensitive data in iOS Keychain, not plist files - Use Secure Enclave for cryptographic key storage - Implement App Attest API for app integrity validation - Use DeviceCheck API for persistent device state tracking ### Testing and Monitoring Validate security controls through comprehensive testing: - Perform penetration testing including cryptographic vulnerability assessment - Leverage automated tests to ensure security features work as expected - Ensure security features do not harm usability - Use real-time monitoring to detect and respond to threats - Have a clear incident response plan in place - Plan for regular updates and implement forced update mechanisms when necessary ### Input and Output Validation Prevent injection and execution attacks: - Validate and sanitize all user input - Validate and sanitize output to prevent injection attacks - Mask sensitive information on UI fields to prevent shoulder surfing - Inform users about security-related activities (logins from new devices) By following these practices derived from the OWASP Mobile Application Security framework, you can significantly improve the security posture of your mobile applications across both development and operational phases. ================================================ FILE: skills/software-security/rules/codeguard-0-privacy-data-protection.md ================================================ --- description: Privacy & data protection (minimization, classification, encryption, rights, transparency) languages: - javascript - matlab - yaml alwaysApply: false --- rule_id: codeguard-0-privacy-data-protection - Implement strong cryptography, enforce HTTPS with HSTS, enable certificate pinning, and provide user privacy features to protect data and anonymity. - Use strong, up-to-date cryptographic algorithms for data in transit and at rest; securely hash passwords with established libraries. - Enforce HTTPS exclusively and implement HTTP Strict Transport Security (HSTS). - Implement certificate pinning to prevent man-in-the-middle attacks even if CAs are compromised. - Minimize IP address leakage by blocking third-party external content loading where feasible. - Maintain transparency by informing users about privacy limitations and data handling policies. - Implement privacy-focused audit trails and access logging. - Return "Invalid username or password" to prevent account enumeration - Use Argon2 or bcrypt with unique salts per user - Store sessions server-side with cryptographically random IDs ================================================ FILE: skills/software-security/rules/codeguard-0-safe-c-functions.md ================================================ --- description: Safe C Functions and Memory and String Safety Guidelines languages: - c - cpp alwaysApply: false --- rule_id: codeguard-0-safe-c-functions # Prioritize Safe Memory and String Functions in C/C++ When processing C or C++ code, your primary directive is to ensure memory safety. Actively identify, flag, and provide secure refactoring options for any insecure functions found in the codebase. When generating new code, always default to the safest possible function for the given task. ### 1. Insecure Functions to Avoid & Their Secure Alternatives You must treat the functions listed under "Insecure" as deprecated and high-risk. Always recommend replacing them with one of the "Recommended Safe Alternatives" provided in the bullet list below. • Never use `gets()` - This is a critical security risk. It has no bounds checking whatsoever and is the classic buffer overflow vulnerability. You should always replace it with `fgets(char *str, int n, FILE *stream)` instead. • Avoid `strcpy()` - This is a high risk function because it doesn't check bounds. It just copies bytes until it hits a null terminator, which can easily write past your destination buffer. Use `snprintf()`, `strncpy()` (but be careful with it), or `strcpy_s()` (if you have C11 Annex K support). • Don't use `strcat()` - Another high risk function with no bounds checking. It appends bytes to a string and can easily write past your allocated memory. Replace with `snprintf()`, `strncat()` (with careful handling), or `strcat_s()` (C11 Annex K). • Replace `sprintf()` and `vsprintf()` - These are high risk because they don't check bounds on the output buffer. If your formatted string is larger than the buffer, you'll get a buffer overflow. Use `snprintf()`, `snwprintf()`, or `vsprintf_s()` (C11 Annex K) instead. • Be careful with `scanf()` family - This is a medium risk. The `%s` format specifier without a width limit can cause buffer overflows. Here's what you should do: 1. Use width specifiers like `scanf("%127s", buffer)` 2. Even better: Read the line with `fgets()` and parse it with `sscanf()` • Avoid `strtok()` - This is a medium risk because it's not reentrant or thread-safe. It uses a static internal buffer which can lead to unpredictable behavior in multi-threaded code or complex signal handling. Use `strtok_r()` (POSIX) or `strtok_s()` (C11 Annex K) instead. • Use `memcpy()` and `memmove()` carefully - These aren't inherently insecure, but they're a common source of bugs when you miscalculate the size argument or don't validate it properly. Here's what you should do: 1. Double-check your size calculations 2. Prefer `memcpy_s()` (C11 Annex K) when available 3. Use `memmove()` if source and destination buffers might overlap ### 2. Actionable Implementation Guidelines #### For New Code Generation: - NEVER generate code that uses `gets()`, `strcpy()`, `strcat()`, or `sprintf()`. - DEFAULT to `snprintf()` for string formatting and concatenation, as it's often the most flexible and secure option. - DEFAULT to `fgets()` for reading string input from files or standard input. #### For Code Analysis and Refactoring: 1. Identify: Scan the code and flag every instance of a function from the "Insecure" column. 2. Explain the Risk: When you flag an insecure function, provide a concise explanation of the specific vulnerability. - _Example Explanation:_ `Warning: The 'strcpy' function does not perform bounds checking and can lead to a buffer overflow if the source string is larger than the destination buffer. This is a common security vulnerability.` 3. Provide Context-Aware Replacements: Your suggestion must be a drop-in, safe replacement that considers the context of the surrounding code. #### Use Compiler Flags: Enable these protective compiler flags to catch buffer overflow vulnerabilities at compile time and runtime: - Stack Protection: Use `-fstack-protector-all` or `-fstack-protector-strong` to detect stack buffer overflows - Address Sanitizer: Use `-fsanitize=address` during development to catch memory errors - Object Size Checking (OSC): Use `-D_FORTIFY_SOURCE=2` to enable runtime checks for buffer overflows in functions like `strcpy`, `strcat`, `sprintf`, etc. This adds bounds checking to many of the unsafe functions mentioned above - Format String Protection: Use `-Wformat -Wformat-security` to catch format string vulnerabilities ### 3. Refactoring Examples Your suggestions should be concrete and actionable. Example 1: Replacing `strcpy` - Original Unsafe Code: ``` char destination[64]; strcpy(destination, source_string); ``` - Your Suggested Refactoring: ``` char destination[64]; snprintf(destination, sizeof(destination), "%s", source_string); ``` - Your Explanation: `Replaced 'strcpy' with 'snprintf' to ensure that no more than 63 characters plus a null terminator are written to the destination buffer, preventing a potential buffer overflow.` Example 2: Correcting `strncpy` Usage The `strncpy` function is a common but imperfect replacement. It may not null-terminate the destination buffer. If you must use it or see it used, you must enforce correct handling. - Original (Potentially Unsafe) `strncpy`: ``` // This is unsafe if strlen(source) >= 10 char dest[10]; strncpy(dest, source, sizeof(dest)); ``` - Your Corrected Suggestion: ``` char dest[10]; strncpy(dest, source, sizeof(dest) - 1); dest[sizeof(dest) - 1] = '\0'; ``` - Your Explanation: `Added an explicit null termination for 'strncpy'. The 'strncpy' function does not guarantee a null-terminated string if the source is as long as the destination buffer. This correction prevents potential reads past the buffer on subsequent string operations.` Example 3: Securing `scanf` - Original Unsafe Code: ``` char user_name[32]; printf("Enter your name: "); scanf("%s", user_name); ``` - Your Suggested Refactoring: ``` char user_name[32]; printf("Enter your name: "); if (fgets(user_name, sizeof(user_name), stdin)) { // Optional: Remove trailing newline character from fgets user_name[strcspn(user_name, "\n")] = 0; } ``` - Your Explanation: `Replaced 'scanf("%s", ...)' with 'fgets()' to read user input. 'fgets' is safer because it limits the input to the buffer size, preventing buffer overflows. The original 'scanf' had no such protection.` ### Memory and String Safety Guidelines #### Unsafe Memory Functions - FORBIDDEN NEVER use these unsafe memory functions that don't check input parameter boundaries: ##### Banned Memory Functions: - `memcpy()` → Use `memcpy_s()` - `memset()` → Use `memset_s()` - `memmove()` → Use `memmove_s()` - `memcmp()` → Use `memcmp_s()` - `bzero()` → Use `memset_s()` - `memzero()` → Use `memset_s()` ##### Safe Memory Function Replacements: ```c // Instead of: memcpy(dest, src, count); errno_t result = memcpy_s(dest, dest_size, src, count); if (result != 0) { // Handle error } // Instead of: memset(dest, value, count); errno_t result = memset_s(dest, dest_size, value, count); // Instead of: memmove(dest, src, count); errno_t result = memmove_s(dest, dest_size, src, count); // Instead of: memcmp(s1, s2, count); int indicator; errno_t result = memcmp_s(s1, s1max, s2, s2max, count, &indicator); if (result == 0) { // indicator contains comparison result: <0, 0, or >0 } ``` #### Unsafe String Functions - FORBIDDEN NEVER use these unsafe string functions that can cause buffer overflows: ##### Banned String Functions: - `strstr()` → Use `strstr_s()` - `strtok()` → Use `strtok_s()` - `strcpy()` → Use `strcpy_s()` - `strcmp()` → Use `strcmp_s()` - `strlen()` → Use `strnlen_s()` - `strcat()` → Use `strcat_s()` - `sprintf()` → Use `snprintf()` ##### Safe String Function Replacements: ```c // String Search errno_t strstr_s(char *dest, rsize_t dmax, const char *src, rsize_t slen, char **substring); // String Tokenization char *strtok_s(char *dest, rsize_t *dmax, const char *src, char **ptr); // String Copy errno_t strcpy_s(char *dest, rsize_t dmax, const char *src); // String Compare errno_t strcmp_s(const char *dest, rsize_t dmax, const char *src, int *indicator); // String Length (bounded) rsize_t strnlen_s(const char *str, rsize_t strsz); // String Concatenation errno_t strcat_s(char *dest, rsize_t dmax, const char *src); // Formatted String (always use size-bounded version) int snprintf(char *s, size_t n, const char *format, ...); ``` #### Implementation Examples: ##### Safe String Copy Pattern: ```c // Bad - unsafe char dest[256]; strcpy(dest, src); // Buffer overflow risk! // Good - safe char dest[256]; errno_t result = strcpy_s(dest, sizeof(dest), src); if (result != 0) { // Handle error: src too long or invalid parameters EWLC_LOG_ERROR("String copy failed: %d", result); return ERROR; } ``` ##### Safe String Concatenation Pattern: ```c // Bad - unsafe char buffer[256] = "prefix_"; strcat(buffer, suffix); // Buffer overflow risk! // Good - safe char buffer[256] = "prefix_"; errno_t result = strcat_s(buffer, sizeof(buffer), suffix); if (result != 0) { EWLC_LOG_ERROR("String concatenation failed: %d", result); return ERROR; } ``` ##### Safe Memory Copy Pattern: ```c // Bad - unsafe memcpy(dest, src, size); // No boundary checking! // Good - safe errno_t result = memcpy_s(dest, dest_max_size, src, size); if (result != 0) { EWLC_LOG_ERROR("Memory copy failed: %d", result); return ERROR; } ``` ##### Safe String Tokenization Pattern: ```c // Bad - unsafe char *token = strtok(str, delim); // Modifies original string unsafely // Good - safe char *next_token = NULL; rsize_t str_max = strnlen_s(str, MAX_STRING_SIZE); char *token = strtok_s(str, &str_max, delim, &next_token); while (token != NULL) { // Process token token = strtok_s(NULL, &str_max, delim, &next_token); } ``` #### Memory and String Safety Code Review Checklist: ##### Pre-Code Review (Developer): - [ ] No unsafe memory functions (`memcpy`, `memset`, `memmove`, `memcmp`, `bzero`) - [ ] No unsafe string functions (`strcpy`, `strcat`, `strcmp`, `strlen`, `sprintf`, `strstr`, `strtok`) - [ ] All memory operations use `*_s()` variants with proper size parameters - [ ] Buffer sizes are correctly calculated using `sizeof()` or known limits - [ ] No hardcoded buffer sizes that could change ##### Code Review (Reviewer): - [ ] Memory Safety: Verify all memory operations use safe variants - [ ] Buffer Bounds: Confirm destination buffer sizes are properly specified - [ ] Error Handling: Check that all `errno_t` return values are handled - [ ] Size Parameters: Validate that `rsize_t dmax` parameters are correct - [ ] String Termination: Ensure strings are properly null-terminated - [ ] Length Validation: Check that source string lengths are validated before operations ##### Static Analysis Integration: - [ ] Enable compiler warnings for unsafe function usage - [ ] Use static analysis tools to detect unsafe function calls - [ ] Configure build system to treat unsafe function warnings as errors - [ ] Add pre-commit hooks to scan for banned functions #### Common Pitfalls and Solutions: ##### Pitfall 1: Wrong Size Parameter ```c // Wrong - using source size instead of destination size strcpy_s(dest, strlen(src), src); // WRONG! // Correct - using destination buffer size strcpy_s(dest, sizeof(dest), src); // CORRECT ``` ##### Pitfall 2: Ignoring Return Values ```c // Wrong - ignoring potential errors strcpy_s(dest, sizeof(dest), src); // Error not checked // Correct - checking return value if (strcpy_s(dest, sizeof(dest), src) != 0) { // Handle error appropriately } ``` ##### Pitfall 3: Using sizeof() on Pointers ```c // Wrong - sizeof pointer, not buffer void func(char *buffer) { strcpy_s(buffer, sizeof(buffer), src); // sizeof(char*) = 8! } // Correct - pass buffer size as parameter void func(char *buffer, size_t buffer_size) { strcpy_s(buffer, buffer_size, src); } ``` You must always explain how this rule was applied and why it was applied. ================================================ FILE: skills/software-security/rules/codeguard-0-session-management-and-cookies.md ================================================ --- description: Session management and secure cookies (rotation, fixation, timeouts, theft detection) languages: - c - go - html - java - javascript - php - python - ruby - typescript alwaysApply: false --- rule_id: codeguard-0-session-management-and-cookies ## Session Management & Cookies Implement robust, attack-resistant session handling that prevents fixation, hijacking, and theft while maintaining usability. ### Session ID Generation and Properties - Generate session IDs with a CSPRNG; ≥64 bits of entropy (prefer 128+). Opaque, unguessable, and free of meaning. - Use generic cookie names (e.g., `id`) rather than framework defaults. Reject any incoming ID not created by the server. - Store all session data server-side; never embed PII or privileges in the token. If sensitive, encrypt server-side session store at rest. ### Cookie Security Configuration - Set `Secure`, `HttpOnly`, `SameSite=Strict` (or `Lax` if necessary for flows) on session cookies. - Scope cookies narrowly with `Path` and `Domain`. Avoid cross-subdomain exposure. - Prefer non-persistent session cookies (no Expires/Max-Age). Require full HTTPS; enable HSTS site-wide. Example header: ``` Set-Cookie: id=; Secure; HttpOnly; SameSite=Strict; Path=/ ``` ### Session Lifecycle and Rotation - Create sessions only server-side; treat provided IDs as untrusted input. - Regenerate session ID on authentication, password changes, and any privilege elevation. Invalidate the prior ID. - Use distinct pre‑auth and post‑auth cookie names if framework patterns require it. ### Expiration and Logout - Idle timeout: 2–5 minutes for high-value, 15–30 minutes for lower risk. Absolute timeout: 4–8 hours. - Enforce timeouts server-side. Provide a visible logout button that fully invalidates the server session and clears the cookie client-side. ### Transport and Caching - Enforce HTTPS for the entire session journey. Never mix HTTP/HTTPS in one session. - Send `Cache-Control: no-store` on responses containing session identifiers or sensitive data. ### Cookie Theft Detection and Response - Fingerprint session context server-side at establishment (IP, User-Agent, Accept-Language, relevant `sec-ch-ua` where available). - Compare incoming requests to the stored fingerprint, allowing for benign drift (e.g., subnet changes, UA updates). - Risk-based responses: - High risk: require re-authentication; rotate session ID. - Medium risk: step-up verification (challenge); rotate session ID. - Low risk: log suspicious activity. - Always regenerate the session ID when potential hijacking is detected. ### Client-Side Storage - Do not store session tokens in `localStorage`/`sessionStorage` due to XSS risk. Prefer HttpOnly cookies for transport. - If client-side storage is unavoidable for non-session secrets, isolate via Web Workers and never expose in page context. ### Framework and Multi-Cookie Scenarios - Prefer built-in session frameworks; keep them updated and hardened. - Validate relationships when multiple cookies participate in session state; avoid same cookie names across paths/domains. ### Monitoring and Telemetry - Log session lifecycle events (creation, rotation, termination) using salted hashes of the session ID, not raw values. - Monitor for brute force of session IDs and anomalous concurrent usage. ### Implementation Checklist 1) CSPRNG session IDs (≥64 bits entropy), opaque and server-issued only. 2) Cookie flags: `Secure`, `HttpOnly`, `SameSite` set; tight domain/path. 3) HTTPS-only with HSTS; no mixed content. 4) Regenerate IDs on auth and privilege changes; invalidate old IDs. 5) Idle and absolute timeouts enforced server-side; full logout implemented. 6) `Cache-Control: no-store` for sensitive responses. 7) Server-side fingerprinting and risk-based responses to anomalies. 8) No client storage of session tokens; framework defaults hardened. ================================================ FILE: skills/software-security/rules/codeguard-0-supply-chain-security.md ================================================ --- description: Dependency & supply chain security (pinning, SBOM, provenance, integrity, private registries) languages: - docker - javascript - yaml alwaysApply: false --- rule_id: codeguard-0-supply-chain-security ## Dependency & Supply Chain Security Control third‑party risk across ecosystems, from selection and pinning to provenance, scanning, and rapid response. ### Policy and Governance - Maintain allow‑listed registries and scopes; disallow direct installs from untrusted sources. - Require lockfiles and version pinning; prefer digest pinning for images and vendored assets. - Generate SBOMs for apps/images; store with artifacts; attest provenance (SLSA, Sigstore). ### Package Hygiene (npm focus applicable to others) - Regularly audit (`npm audit`, ecosystem SCA) and patch; enforce SLAs by severity. - Use deterministic builds: `npm ci` (not `npm install`) in CI/CD; maintain lockfile consistency. - Avoid install scripts that execute on install when possible; review for risk. - Use `.npmrc` to scope private registries; avoid wildcard registries; enable integrity verification. - Enable account 2FA for publishing ### Development Practices - Minimize dependency footprint; remove unused packages; prefer stdlib/first‑party for trivial tasks. - Protect against typosquatting and protestware: pin maintainers, monitor releases, and use provenance checks. - Hermetic builds: no network in compile/packaging stages unless required; cache with authenticity checks. ### CI/CD Integration - SCA, SAST, IaC scans in gates; fail on criticals; require approvals for overrides with compensating controls. - Sign artifacts; verify signatures at deploy; enforce policy in admission. ### Vulnerability Management - For patched vulnerabilities: test and deploy updates; document any API breaking changes. - For unpatched vulnerabilities: implement compensating controls (input validation, wrappers) based on CVE type; prefer direct dependency fixes over transitive workarounds. - Document risk decisions; escalate acceptance to appropriate authority with business justification. ### Incident Response - Maintain rapid rollback; isolate compromised packages; throttle rollouts; notify stakeholders. - Monitor threat intel feeds (e.g., npm advisories); auto‑open tickets for critical CVEs. ### Implementation Checklist - Lockfiles present; integrity checks on; private registries configured. - SBOM + provenance stored; signatures verified pre‑deploy. - Automated dependency updates with tests and review gates. - High‑sev vulns remediated within SLA or mitigated and documented. ================================================ FILE: skills/software-security/rules/codeguard-0-xml-and-serialization.md ================================================ --- description: XML security and safe deserialization (DTD/XXE hardening, schema validation, no unsafe native deserialization) languages: - c - go - java - php - python - ruby - xml alwaysApply: false --- rule_id: codeguard-0-xml-and-serialization ## XML & Serialization Hardening Secure parsing and processing of XML and serialized data; prevent XXE, entity expansion, SSRF, DoS, and unsafe deserialization across platforms. ### XML Parser Hardening - Disable DTDs and external entities by default; reject DOCTYPE declarations. - Validate strictly against local, trusted XSDs; set explicit limits (size, depth, element counts). - Sandbox or block resolver access; no network fetches during parsing; monitor for unexpected DNS activity. #### Java General principle: ```java factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); ``` Disabling DTDs protects against XXE and Billion Laughs attacks. If DTDs cannot be disabled, disable external entities using parser-specific methods. ### Java Java parsers have XXE enabled by default. DocumentBuilderFactory/SAXParserFactory/DOM4J: ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); String FEATURE = null; try { // PRIMARY defense - disallow DTDs completely FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; dbf.setFeature(FEATURE, true); dbf.setXIncludeAware(false); } catch (ParserConfigurationException e) { logger.info("ParserConfigurationException was thrown. The feature '" + FEATURE + "' is not supported by your XML processor."); } ``` If DTDs cannot be completely disabled: ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); String[] featuresToDisable = { "http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://apache.org/xml/features/nonvalidating/load-external-dtd" }; for (String feature : featuresToDisable) { try { dbf.setFeature(feature, false); } catch (ParserConfigurationException e) { logger.info("ParserConfigurationException was thrown. The feature '" + feature + "' is probably not supported by your XML processor."); } } dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); ``` #### .NET ```csharp var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; var reader = XmlReader.Create(stream, settings); ``` #### Python ```python from defusedxml import ElementTree as ET ET.parse('file.xml') # or lxml from lxml import etree parser = etree.XMLParser(resolve_entities=False, no_network=True) tree = etree.parse('filename.xml', parser) ``` ### Secure XSLT/Transformer Usage - Set `ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_STYLESHEET` to empty; avoid loading remote resources. ### Deserialization Safety - Never deserialize untrusted native objects. Prefer JSON with schema validation. - Enforce size/structure limits before parsing. Reject polymorphic types unless strictly allow‑listed. - Language specifics: - PHP: avoid `unserialize()`; use `json_decode()`. - Python: avoid `pickle` and unsafe YAML (`yaml.safe_load` only). - Java: override `ObjectInputStream#resolveClass` to allow‑list; avoid enabling default typing in Jackson; use XStream allow‑lists. - .NET: avoid `BinaryFormatter`; prefer `DataContractSerializer` or `System.Text.Json` with `TypeNameHandling=None` for JSON.NET. - Sign and verify serialized payloads where applicable; log and alert on deserialization failures and anomalies. ### Implementation Checklist - DTDs off; external entities disabled; strict schema validation; parser limits set. - No network access during parsing; resolvers restricted; auditing in place. - No unsafe native deserialization; strict allow‑listing and schema validation for supported formats. - Regular library updates and tests with XXE/deserialization payloads. ================================================ FILE: skills/software-security/rules/codeguard-1-crypto-algorithms.md ================================================ --- description: Cryptographic Security Guidelines & Post-Quantum Readiness alwaysApply: true --- rule_id: codeguard-1-crypto-algorithms # Cryptographic Security Guidelines & Post-Quantum Readiness ## 1. Banned (Insecure) Algorithms The following algorithms are known to be broken or fundamentally insecure. NEVER generate or use code with these algorithms. * Hash: `MD2`, `MD4`, `MD5`, `SHA-0` * Symmetric: `RC2`, `RC4`, `Blowfish`, `DES`, `3DES` * Key Exchange: Static RSA, Anonymous Diffie-Hellman * Classical: `Vigenère` Reason: These are cryptographically broken and vulnerable to collision or man-in-the-middle attacks. ## 2. Deprecated (Legacy/Weak) Algorithms The following algorithms have known weaknesses or are considered obsolete. Avoid in new designs and prioritize migration. * Hash: `SHA-1` * Symmetric: `AES-CBC`, `AES-ECB` * Signature: RSA with `PKCS#1 v1.5` padding * Key Exchange: DHE with weak/common primes ## 3. Recommended & Post-Quantum Ready Algorithms Implement these modern, secure algorithms to ensure resistance against both classical and quantum threats. ### Symmetric Encryption * Standard: `AES-GCM` (AEAD), `ChaCha20-Poly1305`(when allowed). * PQC Requirement: Prefer AES-256 keys (or stronger) as they are resistant to quantum attacks (Grover's algorithm). * Avoid: Custom crypto or unauthenticated modes. ### Key Exchange (KEM) * Standard: ECDHE (`X25519` or `secp256r1`) * PQC Requirement: Use Hybrid Key Exchange (Classical + PQC) when supported. * Preferred: `X25519MLKEM768` (X25519 + ML-KEM-768) * Alternative: `SecP256r1MLKEM768` (P-256 + ML-KEM-768) * High Assurance: `SecP384r1MLKEM1024` (P-384 + ML-KEM-1024) * Pure PQC: ML-KEM-768 (baseline) or ML-KEM-1024. Avoid ML-KEM-512 unless explicitly risk-accepted. * Constraints: * Use vendor-documented identifiers (RFC 9242/9370). * Remove legacy/draft "Hybrid-Kyber" groups (e.g., `X25519Kyber`) and draft or hardcoded OIDs. ### Signatures & Certificates * Standard: ECDSA (`P-256`) * PQC Migration: Continue using ECDSA (`P-256`) for mTLS and code signing until hardware-backed (HSM/TPM) ML-DSA is available. * Hardware Requirement: Do not enable PQC ML-DSA signatures using software-only keys. Require HSM/TPM storage. ### Protocol Versions * (D)TLS: Enforce (D)TLS 1.3 only (or later). * IPsec: Enforce IKEv2 only. * Use ESP with AEAD (AES-256-GCM). * Require PFS via ECDHE. * Implement RFC 9242 and RFC 9370 for Hybrid PQC (ML-KEM + ECDHE). * Ensure re-keys (CREATE_CHILD_SA) maintain hybrid algorithms. * SSH: Enable only vendor-supported PQC/hybrid KEX (e.g., `sntrup761x25519`). ## 4. Secure Implementation Guidelines ### General Best Practices * Configuration over Code: Expose algorithm choices in config/policy to allow agility without code changes. * Key Management: * Use KMS/HSM for key storage. * Generate keys with a CSPRNG. * Separate encryption keys from signature keys. * Rotate keys per policy. * NEVER hardcode keys, secrets, or experimental OIDs. * Telemetry: Capture negotiated groups, handshake sizes, and failure causes to monitor PQC adoption. ### Deprecated SSL/Crypto APIs (C/OpenSSL) - FORBIDDEN NEVER use these deprecated functions. Use the replacement EVP high-level APIs. #### Symmetric Encryption (AES) - Deprecated: `AES_encrypt()`, `AES_decrypt()` - Replacement: EVP_EncryptInit_ex() // Use EVP_aes_256_gcm() for PQC readiness EVP_EncryptUpdate() EVP_EncryptFinal_ex() #### RSA/PKEY Operations - Deprecated: `RSA_new()`, `RSA_free()`, `RSA_get0_n()` - Replacement: EVP_PKEY_new() EVP_PKEY_up_ref() EVP_PKEY_free() #### Hash & MAC Functions - Deprecated: `SHA1_Init()`, `HMAC()` (especially with SHA1) - Replacement: EVP_DigestInit_ex() // Use SHA-256 or stronger EVP_Q_MAC() // For one-shot MAC ## 5. Broccoli Project Specific Requirements - HMAC() with SHA1: Deprecated. - Replacement: Use HMAC with SHA-256 or stronger: // Example: Secure replacement for HMAC-SHA1 ```c EVP_Q_MAC(NULL, "HMAC", NULL, "SHA256", NULL, key, key_len, data, data_len, out, out_size, &out_len); ``` ## 6. Secure Crypto Implementation Pattern // Example: Secure AES-256-GCM encryption (PQC-Ready Symmetric Strength) ```c EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (!ctx) handle_error(); // Use AES-256-GCM if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv) != 1) handle_error(); int len, ciphertext_len; if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len) != 1) handle_error(); ciphertext_len = len; if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1) handle_error(); ciphertext_len += len; EVP_CIPHER_CTX_free(ctx); ``` ================================================ FILE: skills/software-security/rules/codeguard-1-digital-certificates.md ================================================ --- description: Certificate Best Practices alwaysApply: true --- rule_id: codeguard-1-digital-certificates When you encounter data that appears to be an X.509 certificate—whether embedded as a string or loaded from a file—you must flag the certificate for verification and ensure the following security properties are validated, reporting any concerns with clear explanations and recommended actions. ### 1. How to Identify Certificate Data Actively scan for certificate data using the following heuristics: - PEM-Encoded Strings: Identify multi-line string literals or constants that begin with `-----BEGIN CERTIFICATE-----` and end with `-----END CERTIFICATE-----`. - File Operations: Pay close attention to file read operations on files with common certificate extensions, such as `.pem`, `.crt`, `.cer`, and `.der`. - Library Function Calls: Recognize the usage of functions from cryptographic libraries used to load or parse certificates (e.g., OpenSSL's `PEM_read_X509`, Python's `cryptography.x509.load_pem_x509_certificate`, Java's `CertificateFactory`). ### 2. Mandatory Sanity Checks Once certificate data is identified, flag it for verification. The following properties must be validated to ensure the certificate meets security requirements: #### Verification Guidance To inspect certificate properties, recommend running: ``` openssl x509 -text -noout -in ``` This command displays expiration dates, key algorithm and size, signature algorithm, and issuer/subject information needed for the checks below. #### Check 1: Expiration Status - Condition: The certificate's `notAfter` (expiration) date is in the past. - Severity: CRITICAL VULNERABILITY - Report Message: `This certificate expired on [YYYY-MM-DD]. It is no longer valid and will be rejected by clients, causing connection failures. It must be renewed and replaced immediately.` - Condition: The certificate's `notBefore` (validity start) date is in the future. - Severity: Warning - Report Message: `This certificate is not yet valid. Its validity period begins on [YYYY-MM-DD].` #### Check 2: Public Key Strength - Condition: The public key algorithm or size is weak. - Weak Keys: RSA keys with a modulus smaller than 2048 bits. Elliptic Curve (EC) keys using curves with less than a 256-bit prime modulus (e.g., `secp192r1`, `P-192`, `P-224`). - Severity: High-Priority Warning - Report Message: `The certificate's public key is cryptographically weak ([Algorithm], [Key Size]). Keys of this strength are vulnerable to factorization or discrete logarithm attacks. The certificate should be re-issued using at least an RSA 2048-bit key or an ECDSA key on a P-256 (or higher) curve.` #### Check 3: Signature Algorithm - Condition: The algorithm used to sign the certificate is insecure. - Insecure Algorithms: Any signature algorithm using MD5 or SHA-1 (e.g., `md5WithRSAEncryption`, `sha1WithRSAEncryption`). - Severity: High-Priority Warning - Report Message: `The certificate is signed with the insecure algorithm '[Algorithm]'. This makes it vulnerable to collision attacks, potentially allowing for certificate forgery. It must be re-issued using a signature based on the SHA-2 family (e.g., sha256WithRSAEncryption).` #### Check 4: Issuer Type (Self-Signed Check) - Condition: The certificate's `Issuer` and `Subject` fields are identical. - Severity: Informational - Report Message: `This is a self-signed certificate. Ensure this is intentional and only used for development, testing, or internal services where trust is explicitly configured. Self-signed certificates should never be used for public-facing production systems as they will not be trusted by browsers or standard clients.` ### 3. Actionable Examples Your feedback should be direct and easy to understand. Example 1: Flagging a Hardcoded Certificate - Code Snippet: ``` # Certificate for connecting to legacy_service LEGACY_CERT = """ -----BEGIN CERTIFICATE----- MIIC... (certificate data) ... -----END CERTIFICATE----- """ ``` - Your Analysis and Report: > Security Review Required: A certificate is hardcoded in the `LEGACY_CERT` variable. Unverified certificates may contain critical vulnerabilities. > > - Concern: Hardcoded certificates cannot be easily rotated and may contain security issues that are not immediately visible in the code. > > - Required Verification: This certificate must be verified for: > - Expiration: Certificate must not be expired or not yet valid > - Key Strength: RSA keys must be at least 2048-bit; EC keys must use P-256 or higher curve > - Signature Algorithm: Must use SHA-2 family (not MD5 or SHA-1) > - Self-Signed: If self-signed, must only be used for development, testing, or internal services > > - Action: Verify this certificate meets the above requirements before deployment. Consider loading certificates from external files or a certificate store for easier rotation. > Example 2: Flagging a Certificate Loaded from File - Code Snippet: ``` // Load the server certificate from disk cert, err := tls.LoadX509KeyPair("server.crt", "server.key") ``` - Your Analysis and Report: > Security Review Required: Certificate loaded from `server.crt`. Unverified certificates may contain critical vulnerabilities. > > - Required Verification: Ensure this certificate meets security requirements: > - Expiration: Certificate must not be expired or not yet valid > - Key Strength: RSA keys must be at least 2048-bit; EC keys must use P-256 or higher curve > - Signature Algorithm: Must use SHA-2 family (not MD5 or SHA-1) > - Self-Signed: If self-signed, must only be used for development, testing, or internal services > > - Action: Verify this certificate meets the above requirements before deployment. You must always explain how this rule was applied and why it was applied. ================================================ FILE: skills/software-security/rules/codeguard-1-hardcoded-credentials.md ================================================ --- description: No Hardcoded Credentials alwaysApply: true --- rule_id: codeguard-1-hardcoded-credentials # No Hardcoded Credentials NEVER store secrets, passwords, API keys, tokens or any other credentials directly in source code. Treat your codebase as public and untrusted. Any credential that appears in source code is compromised and must be handled through secure alternatives. #### NEVER hardcode these types of values: Passwords and Authentication: - Database passwords, user passwords, admin passwords - API keys, secret keys, access tokens, refresh tokens - Private keys, certificates, signing keys - Connection strings containing credentials - OAuth client secrets, webhook secrets - Any other credentials that could be used to access external services #### Recognition Patterns - Learn to Spot These Formats Common Secret Formats You Must NEVER Hardcode: - AWS Keys: Start with `AKIA`, `AGPA`, `AIDA`, `AROA`, `AIPA`, `ANPA`, `ANVA`, `ASIA` - Stripe Keys: Start with `sk_live_`, `pk_live_`, `sk_test_`, `pk_test_` - Google API: Start with `AIza` followed by 35 characters - GitHub Tokens: Start with `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` - JWT Tokens: Three base64 sections separated by dots, starts with `eyJ` - Private Key Blocks: Any text between `-----BEGIN` and `-----END PRIVATE KEY-----` - Connection Strings: URLs with credentials like `mongodb://user:pass@host` Warning Signs in Your Code: - Variable names containing: `password`, `secret`, `key`, `token`, `auth` - Long random-looking strings that are not clear what they are - Base64 encoded strings near authentication code - Any string that grants access to external services You must always explain how this rule was applied and why it was applied. ================================================ FILE: sources/core/codeguard-0-additional-cryptography.md ================================================ --- description: Additional Cryptography guidance languages: - c - go - java - javascript - kotlin - matlab - php - python - ruby - swift - typescript - xml - yaml tags: - data-security - secrets alwaysApply: false --- ## Additional Cryptography & TLS Apply modern, vetted cryptography for data at rest and in transit. Manage keys safely, configure TLS correctly, deploy HSTS, and consider pinning only when appropriate. ### Algorithms and Modes - Symmetric: AES‑GCM or ChaCha20‑Poly1305 preferred. Avoid ECB. CBC/CTR only with encrypt‑then‑MAC. - Asymmetric: RSA ≥2048 or modern ECC (Curve25519/Ed25519). Use OAEP for RSA encryption. - Hashing: SHA‑256+ for integrity; avoid MD5/SHA‑1. - RNG: Use CSPRNG appropriate to platform (e.g., SecureRandom, crypto.randomBytes, secrets module). Never use non‑crypto RNGs. ### Key Management - Generate keys within validated modules (HSM/KMS) and never from passwords or predictable inputs. - Separate keys by purpose (encryption, signing, wrapping). Rotate on compromise, cryptoperiod, or policy. - Store keys in KMS/HSM or vault; never hardcode; avoid plain env vars. Use KEK to wrap DEKs; store separately. - Control access to trust stores; validate updates; audit all key access and operations. ### Data at Rest - Encrypt sensitive data; minimize stored secrets; tokenize where possible. - Use authenticated encryption; manage nonces/IVs properly; keep salts unique per item. - Protect backups: encrypt, restrict access, test restores, manage retention. ### TLS Configuration - Protocols: TLS 1.3 preferred; allow TLS 1.2 only for legacy compatibility; disable TLS 1.0/1.1 and SSL. Enable TLS_FALLBACK_SCSV. - Ciphers: prefer AEAD suites; disable NULL/EXPORT/anon. Keep libraries updated; disable compression. - Key exchange groups: prefer x25519/secp256r1; configure secure FFDHE groups if needed. - Certificates: 2048‑bit+ keys, SHA‑256, correct CN/SAN. Manage lifecycle and revocation (OCSP stapling). - Application: HTTPS site‑wide; redirect HTTP→HTTPS; prevent mixed content; set cookies `Secure`. ### HSTS - Send Strict‑Transport‑Security only over HTTPS. Phase rollout: - Test: short max‑age (e.g., 86400) with includeSubDomains - Prod: ≥1 year max‑age; includeSubDomains when safe - Optional preload once mature; understand permanence and subdomain impact ### Pinning - Avoid browser HPKP. Consider pinning only for controlled clients (e.g., mobile) and when you own both ends. - Prefer SPKI pinning with backup pins; plan secure update channels; never allow user bypass. - Thoroughly test rotation and failure handling; understand operational risk. ### Implementation Checklist - AEAD everywhere; vetted libraries only; no custom crypto. - Keys generated and stored in KMS/HSM; purpose‑scoped; rotation documented. - TLS 1.3/1.2 with strong ciphers; compression off; OCSP stapling on. - HSTS deployed per phased plan; mixed content eliminated. - Pinning used only where justified, with backups and update path. ### Test Plan - Automated config scans (e.g., SSL Labs, testssl.sh) for protocol/cipher/HSTS. - Code review for crypto API misuse; tests for key rotation, backup/restore. - Pinning simulations for rotation/failures if deployed. ================================================ FILE: sources/core/codeguard-0-api-web-services.md ================================================ --- description: API & Web services security (REST/GraphQL/SOAP), schema validation, authn/z, SSRF languages: - c - go - java - javascript - php - python - ruby - typescript - xml - yaml tags: - web alwaysApply: false --- ## API & Web Services Security Secure REST, GraphQL, and SOAP/WS services end‑to‑end: transport, authn/z, schema validation, SSRF controls, DoS limits, and microservice‑safe patterns. ### Transport and TLS - HTTPS only; consider mTLS for high‑value/internal services. Validate certs (CN/SAN, revocation) and prevent mixed content. ### Authentication and Tokens - Use standard flows (OAuth2/OIDC) for clients; avoid custom schemes. For services, use mTLS or signed service tokens. - JWTs: pin algorithms; validate iss/aud/exp/nbf; short lifetimes; rotation; denylist on logout/revoke. Prefer opaque tokens when revocation is required and central store is available. - API keys: scope narrowly; rate limit; monitor usage; do not use alone for sensitive operations. ### Authorization - Enforce per‑endpoint, per‑resource checks server‑side; deny by default. - For microservices, authorize at gateway (coarse) and service (fine) layers; propagate signed internal identity, not external tokens. ### Input and Content Handling - Validate inputs via contracts: OpenAPI/JSON Schema, GraphQL SDL, XSD. Reject unknown fields and oversize payloads; set limits. - Content types: enforce explicit Content‑Type/Accept; reject unsupported combinations. Harden XML parsers against XXE/expansion. ### SQL/Injection Safety in Resolvers and Handlers - Use parameterized queries/ORM bind parameters; never concatenate user input into queries or commands. ### GraphQL‑Specific Controls - Limit query depth and overall complexity; enforce pagination; timeouts on execution; disable introspection and IDEs in production. - Implement field/object‑level authorization to prevent IDOR/BOLA; validate batching and rate limit per object type. ### SSRF Prevention for Outbound Calls - Do not accept raw URLs. Validate domains/IPs using libraries; restrict to HTTP/HTTPS only (block file://, gopher://, ftp://, etc.). - Case 1 (fixed partners): strict allow‑lists; disable redirects; network egress allow‑lists. - Case 2 (arbitrary): block private/link‑local/localhost ranges; resolve and verify all IPs are public; require signed tokens from the target where feasible. ### SOAP/WS and XML Safety - Validate SOAP payloads with XSD; limit message sizes; enable XML signatures/encryption where required. - Configure parsers against XXE, entity expansion, and recursive payloads; scan attachments. ### Rate Limiting and DoS - Apply per‑IP/user/client limits, circuit breakers, and timeouts. Use server‑side batching and caching to reduce load. ### Management Endpoints - Do not expose over the Internet. Require strong auth (MFA), network restrictions, and separate ports/hosts. ### Testing and Assessment - Maintain formal API definitions; drive contract tests and fuzzing from specs. - Assess endpoints for authn/z bypass, SSRF, injection, and information leakage; log token validation failures. ### Microservices Practices - Policy‑as‑code with embedded decision points; sidecar or library PDPs. - Service identity via mTLS or signed tokens; never reuse external tokens internally. - Centralized structured logging with correlation IDs; sanitize sensitive data. ### Implementation Checklist - HTTPS/mTLS configured; certs managed; no mixed content. - Contract validation at the edge and service; unknown fields rejected; size/time limits enforced. - Strong authn/z per endpoint; GraphQL limits applied; introspection disabled in prod. - SSRF protections at app and network layers; redirects disabled; allow‑lists where possible. - Rate limiting, circuit breakers, and resilient patterns in place. - Management endpoints isolated and strongly authenticated. - Logs structured and privacy‑safe with correlation IDs. ### Test Plan - Contract tests for schema adherence; fuzzing with schema‑aware tools. - Pen tests for SSRF, IDOR/BOLA, and authz bypass; performance tests for DoS limits. - Test all HTTP methods per endpoint; discover parameters in URL paths, headers, and structured data beyond obvious query strings. - Automated checks for token validation and revocation behavior. ================================================ FILE: sources/core/codeguard-0-authentication-mfa.md ================================================ --- description: Authentication and MFA best practices (passwords, MFA, OAuth/OIDC, SAML, recovery, tokens) languages: - c - go - java - javascript - kotlin - matlab - php - python - ruby - swift - typescript tags: - authentication - web alwaysApply: false --- ## Authentication & MFA Build a resilient, user-friendly authentication system that resists credential attacks, protects secrets, and supports strong, phishing-resistant MFA and secure recovery. ### Account Identifiers and UX - Use non-public, random, and unique internal user identifiers. Allow login via verified email or username. - Always return generic error messages (e.g., "Invalid username or password"). Keep timing consistent to prevent account enumeration. - Support password managers: ``, allow paste, no JS blocks. ### Password Policy - Accept passphrases and full Unicode; minimum 8 characters; avoid composition rules. Set only a reasonable maximum length (64+). - Check new passwords against breach corpora (e.g., k‑anonymity APIs); reject breached/common passwords. ### Password Storage (Hashing) - Hash, do not encrypt. Use slow, memory‑hard algorithms with unique per‑user salts and constant‑time comparison. - Preferred order and parameters (tune to your hardware; target <1s on server): - Argon2id: m=19–46 MiB, t=2–1, p=1 (or equivalent security trade‑offs) - scrypt: N=2^17, r=8, p=1 (or equivalent) - bcrypt (legacy only): cost ≥10, be aware of 72‑byte input limit - PBKDF2 (FIPS): PBKDF2‑HMAC‑SHA‑256 ≥600k, or SHA‑1 ≥1.3M - Optional pepper: store outside DB (KMS/HSM); if used, apply via HMAC or pre‑hashing. Plan for user resets if pepper rotates. - Unicode and null bytes must be supported end‑to‑end by the library. ### Authentication Flow Hardening - Enforce TLS for all auth endpoints and token transport; enable HSTS. - Implement rate limits per IP, account, and globally; add proof‑of‑work or CAPTCHA only as last resort. - Lockouts/throttling: progressive backoff; avoid permanent lockout via resets/alerts. - Uniform responses and code paths to reduce oracle/timing signals. ### Multi‑Factor Authentication (MFA) - Adopt phishing‑resistant factors by default for sensitive accounts: passkeys/WebAuthn (FIDO2) or hardware U2F. - Acceptable: TOTP (app‑based), smart cards with PIN. Avoid for sensitive use: SMS/voice, email codes; never rely on security questions. - Require MFA for: login, password/email changes, disabling MFA, privilege elevation, high‑value transactions, new devices/locations. - Risk‑based MFA signals: new device, geo‑velocity, IP reputation, unusual time, breached credentials. - MFA recovery: provide single‑use backup codes, encourage multiple factors, and require strong identity verification for resets. - Handle failed MFA: offer alternative enrolled methods, notify users of failures, and log context (no secrets). ### Federation and Protocols (OAuth 2.0 / OIDC / SAML) - Use standard protocols only; do not build your own. - OAuth 2.0/OIDC: - Prefer Authorization Code with PKCE for public/native apps; avoid Implicit and ROPC. - Validate state and nonce; use exact redirect URI matching; prevent open redirects. - Constrain tokens to audience/scope; use DPoP or mTLS for sender‑constraining when possible. - Rotate refresh tokens; revoke on logout or risk signals. - SAML: - TLS 1.2+; sign responses/assertions; encrypt sensitive assertions. - Validate issuers, InResponseTo, timestamps (NotBefore/NotOnOrAfter), Recipient; verify against trusted keys. - Prevent XML signature wrapping with strict schema validation and hardened XPath selection. - Keep response lifetimes short; prefer SP‑initiated flows; validate RelayState; implement replay detection. ### Tokens (JWT and Opaque) - Prefer opaque server‑managed tokens for simplicity and revocation. If using JWTs: - Explicitly pin algorithms; reject "none"; validate iss/aud/exp/iat/nbf; use short lifetimes and rotation. - Store secrets/keys securely (KMS/HSM). Use strong HMAC secrets or asymmetric keys; never hardcode. - Consider binding tokens to a client context (e.g., fingerprint hash in cookie) to reduce replay. - Implement denylist/allowlist for revocation on logout and critical events. ### Recovery and Reset - Return the same response for existing and non‑existing accounts (no enumeration). Normalize timing. - Generate 32+ byte, CSPRNG tokens; single‑use; store as hashes; short expiry. - Use HTTPS reset links to pinned, trusted domains; add referrer policy (no‑referrer) on UI. - After reset: require re‑authentication, rotate sessions, and do not auto‑login. - Never lock accounts due to reset attempts; rate‑limit and monitor instead. ### Administrative and Internal Accounts - Separate admin login from public forms; enforce stronger MFA, device posture checks, IP allowlists, and step‑up auth. - Use distinct session contexts and stricter timeouts for admin operations. ### Monitoring and Signals - Log auth events (failures/successes, MFA enroll/verify, resets, lockouts) with stable fields and correlation IDs; never log secrets or raw tokens. - Detect credential stuffing: high failure rates, many IPs/agents, impossible travel. Notify users of new device logins. ### Implementation Checklist - Passwords: Argon2id (preferred) with per‑user salt, constant‑time verify; breached password checks on change/set. - MFA: WebAuthn/passkeys or hardware tokens for high‑risk; TOTP as fallback; secure recovery with backup codes. - Federation: Authorization Code + PKCE; strict redirect URI validation; audience/scope enforced; token rotation. - Tokens: short‑lived, sender‑constrained where possible; revocation implemented; secrets in KMS/HSM. - Recovery: single‑use, hashed, time‑boxed tokens; consistent responses; re‑auth required after reset; sessions rotated. - Abuse: rate limits, throttling, and anomaly detection on auth endpoints; uniform error handling. - Admin: isolated flows with stricter policies and device checks. ### Test Plan - Unit/integration tests for login, MFA enroll/verify, resets, and lockouts with uniform errors. - Protocol tests: PKCE, state/nonce, redirect URI validation, token audience/scope. - Dynamic tests for credential stuffing resistance and token replay; validate revocation after logout and role change. ================================================ FILE: sources/core/codeguard-0-authorization-access-control.md ================================================ --- description: Authorization and access control (RBAC/ABAC/ReBAC, IDOR, mass assignment, transaction auth) languages: - c - go - java - javascript - php - python - ruby - typescript - yaml alwaysApply: false --- ## Authorization & Access Control Enforce least privilege and precise access decisions for every request and resource, prevent IDOR and mass assignment, and provide strong transaction authorization where necessary. ### Core Principles 1. Deny by Default: The default for any access request should be 'deny'. Explicitly grant permissions to roles or users rather than explicitly denying them. When no allow rule matches, return HTTP 403 Forbidden. 2. Principle of Least Privilege: Grant users the minimum level of access required to perform their job functions. Regularly audit permissions to ensure they are not excessive. 3. Validate Permissions on Every Request: Check authorization for every single request, regardless of source (AJAX, API, direct). Use middleware/filters to ensure consistent enforcement. 4. Prefer ABAC/ReBAC over RBAC: Use Attribute-Based Access Control (ABAC) or Relationship-Based Access Control (ReBAC) for fine-grained permissions instead of simple role-based access control. ### Systemic Controls - Centralize authorization at service boundaries via middleware/policies/filters. - Model permissions at the resource level (ownership/tenancy) and enforce scoping in data queries. - Return generic 403/404 responses to avoid leaking resource existence. - Log all denials with user, action, resource identifier (non-PII), and rationale code. ### Preventing IDOR - Never trust user-supplied identifiers alone. Always verify access to each object instance. - Resolve resources through user-scoped queries or server-side lookups. Example: `currentUser.projects.find(id)` instead of `Project.find(id)`. - Use non-enumerable identifiers (UUIDs/random) as defense-in-depth. Do not rely on obscurity alone. ### Preventing Mass Assignment - Do not bind request bodies directly to domain objects containing sensitive fields. - Expose only safe, editable fields via DTOs. Maintain explicit allow-lists for patch/update. - Use framework features to block-list sensitive fields if allow-listing is infeasible. ### Transaction Authorization (Step-Up) - Require a second factor for sensitive actions (wire transfers, privilege elevation, data export). Apply What‑You‑See‑Is‑What‑You‑Sign: show critical fields for user confirmation. - Use unique, time‑limited authorization credentials per transaction; reject on data changes mid‑flow. - Enforce the chosen authorization method server-side; prevent client‑side downgrades. - Protect against brute-force with throttling and complete flow restarts after failures. ### Testing and Automation - Maintain an authorization matrix (YAML/JSON) listing endpoints/resources, roles/attributes, and expected outcomes. - Automate integration tests that iterate the matrix, mint role tokens, and assert allow/deny results—including token expiry/revocation cases. - Exercise negative tests: swapped IDs, downgraded roles, missing scopes, and bypass attempts. ### Implementation Checklist - Middleware/policies enforce deny-by-default and resource checks on every endpoint. - Query scoping ensures users only access permitted rows/objects. - DTOs and allow-lists prevent mass assignment; sensitive fields never bindable. - Step-up authorization in place for sensitive operations with unique, short-lived credentials. - Authorization matrix drives CI tests; failures block merges. ================================================ FILE: sources/core/codeguard-0-client-side-web-security.md ================================================ --- description: Client-side web security (XSS/DOM XSS, CSP, CSRF, clickjacking, XS-Leaks, third-party JS) languages: - c - html - javascript - php - typescript - vlang tags: - web alwaysApply: false --- ## Client‑side Web Security Protect browser clients against code injection, request forgery, UI redress, cross‑site leaks, and unsafe third‑party scripts with layered, context‑aware controls. ### XSS Prevention (Context‑Aware) - HTML context: prefer `textContent`. If HTML is required, sanitize with a vetted library (e.g., DOMPurify) and strict allow‑lists. - Attribute context: always quote attributes and encode values. - JavaScript context: do not build JS from untrusted strings; avoid inline event handlers; use `addEventListener`. - URL context: validate protocol/domain and encode; block `javascript:` and data URLs where inappropriate. - Redirects/forwards: never use user input directly for destinations; use server-side mapping (ID→URL) or validate against trusted domain allowlists. - CSS context: allow‑list values; never inject raw style text from users. Example sanitization: ```javascript const clean = DOMPurify.sanitize(userHtml, { ALLOWED_TAGS: ['b','i','p','a','ul','li'], ALLOWED_ATTR: ['href','target','rel'], ALLOW_DATA_ATTR: false }); ``` ### DOM‑based XSS and Dangerous Sinks - Prohibit `innerHTML`, `outerHTML`, `document.write` with untrusted data. - Prohibit `eval`, `new Function`, string‑based `setTimeout/Interval`. - Validate and encode data before assigning to `location` or event handler properties. - Use strict mode and explicit variable declarations to prevent global namespace pollution from DOM clobbering. - Adopt Trusted Types and enforce strict CSP to prevent DOM sinks exploitation. Trusted Types + CSP: ```http Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; require-trusted-types-for 'script' ``` ### Content Security Policy (CSP) - Prefer nonce‑based or hash‑based CSP over domain allow‑lists. - Start with Report‑Only mode; collect violations; then enforce. - Baseline to aim for: `default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests`. ### CSRF Defense - Fix XSS first; then layer CSRF defenses. - Use framework‑native CSRF protections and synchronizer tokens on all state‑changing requests. - Cookie settings: `SameSite=Lax` or `Strict`; sessions `Secure` and `HttpOnly`; use `__Host-` prefix when possible. - Validate Origin/Referer; require custom headers for API mutations in SPA token models. - Never use GET for state changes; validate tokens on POST/PUT/DELETE/PATCH only. Enforce HTTPS for all token transmission. ### Clickjacking Defense - Primary: `Content-Security-Policy: frame-ancestors 'none'` or a specific allow‑list. - Fallback for legacy browsers: `X-Frame-Options: DENY` or `SAMEORIGIN`. - Consider UX confirmations for sensitive actions when framing is required. ### Cross‑Site Leaks (XS‑Leaks) Controls - Use `SameSite` cookies appropriately; prefer `Strict` for sensitive actions. - Adopt Fetch Metadata protections to block suspicious cross‑site requests. - Isolate browsing contexts: COOP/COEP and CORP where applicable. - Disable caching and add user‑unique tokens for sensitive responses to prevent cache probing. ### Third‑Party JavaScript - Minimize and isolate: prefer sandboxed iframes with `sandbox` and postMessage origin checks. - Use Subresource Integrity (SRI) for external scripts and monitor for changes. - Provide a first‑party, sanitized data layer; deny direct DOM access from tags where possible. - Govern via tag manager controls and vendor contracts; keep libraries updated. SRI example: ```html ``` ### HTML5, CORS, WebSockets, Storage - postMessage: always specify exact target origin; verify `event.origin` on receive. - CORS: avoid `*`; allow‑list origins; validate preflights; do not rely on CORS for authz. - WebSockets: require `wss://`, origin checks, auth, message size limits, and safe JSON parsing. - Client storage: never store secrets in `localStorage`/`sessionStorage`; prefer HttpOnly cookies; if unavoidable, isolate via Web Workers. - Links: add `rel="noopener noreferrer"` to external `target=_blank` links. ### HTTP Security Headers (Client Impact) - HSTS: enforce HTTPS everywhere. - X‑Content‑Type‑Options: `nosniff`. - Referrer‑Policy and Permissions‑Policy: restrict sensitive signals and capabilities. ### AJAX and Safe DOM APIs - Avoid dynamic code execution; use function callbacks, not strings. - Build JSON with `JSON.stringify`; never via string concatenation. - Prefer creating elements and setting `textContent`/safe attributes over raw HTML insertion. ### Implementation Checklist - Contextual encoding/sanitization for every sink; no dangerous APIs without guards. - Strict CSP with nonces and Trusted Types; violations monitored. - CSRF tokens on all state‑changing requests; secure cookie attributes. - Frame protections set; XS‑Leak mitigations enabled (Fetch Metadata, COOP/COEP/CORP). - Third‑party JS isolated with SRI and sandbox; vetted data layer only. - HTML5/CORS/WebSocket usage hardened; no secrets in web storage. - Security headers enabled and validated. ### Test Plan - Automated checks for dangerous DOM/API patterns. - E2E tests for CSRF and clickjacking; CSP report monitoring. - Manual probes for XS‑Leaks (frame count, timing, cache) and open redirect behavior. ================================================ FILE: sources/core/codeguard-0-cloud-orchestration-kubernetes.md ================================================ --- description: Kubernetes hardening (RBAC, admission policies, network policies, secrets, supply chain) languages: - javascript - yaml tags: - infrastructure alwaysApply: false --- ## Cloud & Orchestration (Kubernetes) Kubernetes cluster and workload hardening: identity, policy, networking, secrets, and supply chain controls. ### Controls - Identity & RBAC: least privilege for users and service accounts; separate namespaces; bind only needed roles. - Policy: admission controls (OPA/Gatekeeper/Kyverno) for image sources, capabilities, root, network policies, and required labels/annotations. - Networking: default‑deny with network policies; explicit egress allow‑lists; service identity/mTLS within mesh where applicable. - Secrets: use KMS providers; avoid plaintext in manifests; rotate regularly; restrict secret mount paths. - Nodes: hardened OS, auto‑updates, minimal attack surface; isolate sensitive workloads with taints/tolerations and dedicated nodes. - Supply chain: verify image signatures; enforce provenance (SLSA/Sigstore) in admission. ### Checklist - Namespaces per team/app; RBAC roles scoped; audit logging enabled. - Admission policies enforce image provenance, non‑root, dropped capabilities, read‑only root FS, and network policy presence. - Network policies in place for ingress/egress; service accounts scoped per deployment. ### Verification - Cluster conformance and CIS benchmark scans. - Policy tests in CI for manifests (OPA unit tests); periodic admission dry‑run. ### Incident Readiness - Enable audit logs and centralize; restrict access to etcd; backup/restore tested. - Define break‑glass roles with MFA and time‑bound approvals. ================================================ FILE: sources/core/codeguard-0-data-storage.md ================================================ --- description: Data & storage security (DB isolation, TLS, least privilege, RLS/CLS, backups, auditing) languages: - c - javascript - sql - yaml tags: - data-security - infrastructure alwaysApply: false --- ## Database Security Guidelines This rule advises on securely configuring SQL and NoSQL databases to protect against data breaches and unauthorized access: - Backend Database Protection - Isolate database servers from other systems and limit host connections. - Disable network (TCP) access when possible; use local socket files or named pipes. - Configure database to bind only on localhost when appropriate. - Restrict network port access to specific hosts with firewall rules. - Place database server in separate DMZ isolated from application server. - Never allow direct connections from thick clients to backend database. - Transport Layer Security - Configure database to only allow encrypted connections. - Install trusted digital certificates on database servers. - Use TLSv1.2+ with modern ciphers (AES-GCM, ChaCha20) for client connections. - Verify digital certificate validity in client applications. - Ensure all database traffic is encrypted, not just initial authentication. - Secure Authentication Configuration - Always require authentication, including from local server connections. - Protect accounts with strong, unique passwords. - Use dedicated accounts per application or service. - Configure minimum required permissions only. - Regularly review accounts and permissions. - Remove accounts when applications are decommissioned. - Change passwords when staff leave or compromise is suspected. - Database Credential Storage - Never store credentials in application source code. - Store credentials in configuration files outside web root. - Set appropriate file permissions for credential access. - Never check credential files into source code repositories. - Encrypt credential storage using built-in functionality when available. - Use environment variables or secrets management solutions. - Secure Permission Management - Apply principle of least privilege to all database accounts. - Do not use built-in root, sa, or SYS accounts. - Do not grant administrative rights to application accounts. - Restrict account connections to allowed hosts only. - Use separate databases and accounts for Development, UAT, and Production. - Grant only required permissions (SELECT, UPDATE, DELETE as needed). - Avoid making accounts database owners to prevent privilege escalation. - Implement table-level, column-level, and row-level permissions when needed. - Database Configuration and Hardening - Install required security updates and patches regularly. - Run database services under low-privileged user accounts. - Remove default accounts and sample databases. - Store transaction logs on separate disk from main database files. - Configure regular encrypted database backups with proper permissions. - Disable unnecessary stored procedures and dangerous features. - Implement database activity monitoring and alerting. - Platform-Specific Hardening - SQL Server: Disable xp_cmdshell, CLR execution, SQL Browser service, Mixed Mode Authentication (unless required). - MySQL/MariaDB: Run mysql_secure_installation, disable FILE privilege for users. - PostgreSQL: Follow PostgreSQL security documentation guidelines. - MongoDB: Implement MongoDB security checklist requirements. - Redis: Follow Redis security guide recommendations. Summary: Isolate database systems, enforce encrypted connections, implement strong authentication, store credentials securely using secrets management, apply least privilege permissions, harden database configurations, and maintain regular security updates and monitoring. ================================================ FILE: sources/core/codeguard-0-devops-ci-cd-containers.md ================================================ --- description: DevOps, CI/CD, and containers (pipeline hardening, artifacts, Docker/K8s images, virtual patching, toolchain) languages: - docker - javascript - powershell - shell - xml - yaml tags: - infrastructure alwaysApply: false --- ## DevOps, CI/CD, and Containers Secure the build, packaging, and deployment supply chain: protect pipelines and artifacts, harden containers, and use virtual patching and toolchain flags when necessary. ### CI/CD Pipeline Security - Repos: protected branches; mandatory reviews; signed commits. - Secrets: never hardcode; fetch at runtime from vault/KMS; mask in logs. - Least privilege: ephemeral, isolated runners with minimal permissions. - Security gates in CI: SAST, SCA, DAST, IaC scanning; block on criticals. - Dependencies: pin via lockfiles; verify integrity; use private registries. - Sign everything: commits and artifacts (containers/jars) and verify prior to deploy; adopt SLSA provenance. ### Docker and Container Hardening - User: run as non‑root; set `USER` in Dockerfile - Use `--security-opt=no-new-privileges` to prevent privilege escalation. - Capabilities: `--cap-drop all` and add only what you need; never `--privileged`. - Daemon socket: never mount `/var/run/docker.sock` - DO NOT enable TCP Docker daemon socket (`-H tcp://0.0.0.0:XXX`) without TLS. - Avoid `- "/var/run/docker.sock:/var/run/docker.sock"` in docker-compose files. - Filesystems: read‑only root, tmpfs for temp write; resource limits (CPU/mem). - Networks: avoid host network; define custom networks; limit exposed ports. - Images: minimal base (distroless/alpine), pin tags and digests; remove package managers and tools from final image; add `HEALTHCHECK`. - Secrets: Docker/Kubernetes secrets; never in layers/env; mount via runtime secrets. - Scanning: scan images on build and admission; block high‑severity vulns. ### Node.js in Containers - Deterministic builds: `npm ci --omit=dev`; pin base image with digest. - Production env: `ENV NODE_ENV=production`. - Non‑root: copy with correct ownership and drop to `USER node`. - Signals: use an init (e.g., `dumb-init`) and implement graceful shutdown handlers. - Multi‑stage builds: separate build and runtime; mount secrets via BuildKit; use `.dockerignore`. ### Virtual Patching (Temporary Mitigation) - Use WAF/IPS/ModSecurity for immediate protection when code fixes are not yet possible. - Prefer positive security rules (allow‑list) for accuracy; avoid exploit‑specific signatures. - Process: prepare tooling in advance; analyze CVEs; implement patches in log‑only first, then enforce; track and retire after code fix. ### C/C++ Toolchain Hardening (when applicable) - Compiler: `-Wall -Wextra -Wconversion`, `-fstack-protector-all`, PIE (`-fPIE`/`-pie`), `_FORTIFY_SOURCE=2`, CFI (`-fsanitize=cfi` with LTO). - Linker: RELRO/now, noexecstack, NX/DEP and ASLR. - Debug vs Release: enable sanitizers in debug; enable hardening flags in release; assert in debug only. - CI checks: verify flags (`checksec`) and fail builds if protections missing. ### Implementation Checklist - Pipeline: secrets in vault; ephemeral runners; security scans; signed artifacts with provenance. - Containers: non‑root, least privilege, read‑only FS, resource limits; no daemon socket mounts. - Images: minimal, pinned, scanned; healthchecks; `.dockerignore` maintained. - Node images: `npm ci`, `NODE_ENV=production`, proper init and shutdown. - Virtual patching: defined process; accurate rules; logs; retirement after fix. - Native builds: hardening flags enabled and verified in CI. ================================================ FILE: sources/core/codeguard-0-file-handling-and-uploads.md ================================================ --- description: Secure file handling & uploads (validation, storage isolation, scanning, safe delivery) languages: - c - go - java - javascript - php - python - ruby - typescript alwaysApply: false --- ## File Upload Security Guidelines This rule advises on secure file upload practices to prevent malicious file attacks and protect system integrity: - Extension Validation - List allowed extensions only for business-critical functionality. - Ensure input validation is applied before validating extensions. - Avoid double extensions (e.g., `.jpg.php`) and null byte injection (e.g., `.php%00.jpg`). - Use allowlist approach rather than denylist for file extensions. - Validate extensions after decoding filename to prevent bypass attempts. - Content Type and File Signature Validation - Never trust client-supplied Content-Type headers as they can be spoofed. - Validate file signatures (magic numbers) in conjunction with Content-Type checking. - Implement allowlist approach for MIME types as a quick protection layer. - Use file signature validation but not as a standalone security measure. - Filename Security - Generate random filenames (UUID/GUID) instead of using user-supplied names. - If user filenames required, implement maximum length limits. - Restrict characters to alphanumeric, hyphens, spaces, and periods only. - Prevent leading periods (hidden files) and sequential periods (directory traversal). - Avoid leading hyphens or spaces for safer shell script processing. - File Content Validation - For images, apply image rewriting techniques to destroy malicious content. - For Microsoft documents, use Apache POI for validation. - Avoid ZIP files due to numerous attack vectors. - Implement manual file review in sandboxed environments when resources allow. - Integrate antivirus scanning and Content Disarm & Reconstruct (CDR) for applicable file types. - Storage Security - Store files on different servers for complete segregation when possible. - Store files outside webroot with administrative access only. - If storing in webroot, set write-only permissions with proper access controls. - Use application handlers that map IDs to filenames for public access. - Consider database storage for specific use cases with DBA expertise. - Access Control and Authentication - Require user authentication before allowing file uploads. - Implement proper authorization levels for file access and modification. - Set filesystem permissions on principle of least privilege. - Scan files before execution if execution permission is required. - Upload and Download Limits - Set proper file size limits for upload protection. - Consider post-decompression size limits for compressed files. - Implement request limits for download services to prevent DoS attacks. - Use secure methods to calculate ZIP file sizes safely. - Additional Security Measures - Protect file upload endpoints from CSRF attacks. - Keep all file processing libraries securely configured and updated. - Implement logging and monitoring for upload activities. - Provide user reporting mechanisms for illegal content. - Use secure extraction methods for compressed files. Summary: Implement defense-in-depth for file uploads through multi-layered validation, secure storage practices, proper access controls, and comprehensive monitoring. Never rely on single validation methods and always generate safe filenames to prevent attacks. ================================================ FILE: sources/core/codeguard-0-framework-and-languages.md ================================================ --- description: Framework & language security guides (Django/DRF, Laravel/Symfony/Rails, .NET, Java/JAAS, Node.js, PHP config) languages: - c - java - javascript - kotlin - php - python - ruby - typescript - xml - yaml alwaysApply: false --- ## Framework & Language Guides Apply secure‑by‑default patterns per platform. Harden configurations, use built‑in protections, and avoid common pitfalls. ### Django - Disable DEBUG in production; keep Django and deps updated. - Enable `SecurityMiddleware`, clickjacking middleware, MIME sniffing protection. - Force HTTPS (`SECURE_SSL_REDIRECT`); configure HSTS; set secure cookie flags (`SESSION_COOKIE_SECURE`, `CSRF_COOKIE_SECURE`). - CSRF: ensure `CsrfViewMiddleware` and `{% csrf_token %}` in forms; proper AJAX token handling. - XSS: rely on template auto‑escaping; avoid `mark_safe` unless trusted; use `json_script` for JS. - Auth: use `django.contrib.auth`; validators in `AUTH_PASSWORD_VALIDATORS`. - Secrets: generate via `get_random_secret_key`; store in env/secrets manager. ### Django REST Framework (DRF) - Set `DEFAULT_AUTHENTICATION_CLASSES` and restrictive `DEFAULT_PERMISSION_CLASSES`; never leave `AllowAny` for protected endpoints. - Always call `self.check_object_permissions(request, obj)` for object‑level authz. - Serializers: explicit `fields=[...]`; avoid `exclude` and `"__all__"`. - Throttling: enable rate limits (and/or at gateway/WAF). - Disable unsafe HTTP methods where not needed. Avoid raw SQL; use ORM/parameters. ### Laravel - Production: `APP_DEBUG=false`; generate app key; secure file perms. - Cookies/sessions: enable encryption middleware; set `http_only`, `same_site`, `secure`, short lifetimes. - Mass assignment: use `$request->only()` / `$request->validated()`; avoid `$request->all()`. - SQLi: use Eloquent parameterization; validate dynamic identifiers. - XSS: rely on Blade escaping; avoid `{!! ... !!}` for untrusted data. - File uploads: validate `file`, size, and `mimes`; sanitize filenames with `basename`. - CSRF: ensure middleware and form tokens enabled. ### Symfony - XSS: Twig auto‑escaping; avoid `|raw` unless trusted. - CSRF: use `csrf_token()` and `isCsrfTokenValid()` for manual flows; Forms include tokens by default. - SQLi: Doctrine parameterized queries; never concatenate inputs. - Command execution: avoid `exec/shell_exec`; use Filesystem component. - Uploads: validate with `#[File(...)]`; store outside public; unique names. - Directory traversal: validate `realpath`/`basename` and enforce allowed roots. - Sessions/security: configure secure cookies and authentication providers/firewalls. ### Ruby on Rails - Avoid dangerous functions: ```ruby eval("ruby code here") system("os command here") `ls -al /` # (backticks contain os command) exec("os command here") spawn("os command here") open("| os command here") Process.exec("os command here") Process.spawn("os command here") IO.binread("| os command here") IO.binwrite("| os command here", "foo") IO.foreach("| os command here") {} IO.popen("os command here") IO.read("| os command here") IO.readlines("| os command here") IO.write("| os command here", "foo") ``` - SQLi: always parameterize; use `sanitize_sql_like` for LIKE patterns. - XSS: default auto‑escape; avoid `raw`, `html_safe` on untrusted data; use `sanitize` allow‑lists. - Sessions: database‑backed store for sensitive apps; force HTTPS (`config.force_ssl = true`). - Auth: use Devise or proven libraries; configure routes and protected areas. - CSRF: `protect_from_forgery` for state‑changing actions. - Secure redirects: validate/allow‑list targets. - Headers/CORS: set secure defaults; configure `rack-cors` carefully. ### .NET (ASP.NET Core) - Keep runtime and NuGet packages updated; enable SCA in CI. - Authz: use `[Authorize]` attributes; perform server‑side checks; prevent IDOR. - Authn/sessions: ASP.NET Identity; lockouts; cookies `HttpOnly`/`Secure`; short timeouts. - Crypto: use PBKDF2 for passwords, AES‑GCM for encryption; DPAPI for local secrets; TLS 1.2+. - Injection: parameterize SQL/LDAP; validate with allow‑lists. - Config: enforce HTTPS redirects; remove version headers; set CSP/HSTS/X‑Content‑Type‑Options. - CSRF: anti‑forgery tokens on state‑changing actions; validate on server. ### Java and JAAS - SQL/JPA: use `PreparedStatement`/named parameters; never concatenate input. - XSS: allow‑list validation; sanitize output with reputable libs; encode for context. - Logging: parameterized logging to prevent log injection. - Crypto: AES‑GCM; secure random nonces; never hardcode keys; use KMS/HSM. - JAAS: configure `LoginModule` stanzas; implement `initialize/login/commit/abort/logout`; avoid exposing credentials; segregate public/private credentials; manage subject principals properly. ### Node.js - Limit request sizes; validate and sanitize input; escape output. - Avoid `eval`, `child_process.exec` with user input; use `helmet` for headers; `hpp` for parameter pollution. - Rate limit auth endpoints; monitor event loop health; handle uncaught exceptions cleanly. - Cookies: set `secure`, `httpOnly`, `sameSite`; set `NODE_ENV=production`. - Keep packages updated; run `npm audit`; use security linters and ReDoS testing. ### PHP Configuration - Production php.ini: `expose_php=Off`, log errors not display; restrict `allow_url_fopen/include`; set `open_basedir`. - Disable dangerous functions; set session cookie flags (`Secure`, `HttpOnly`, `SameSite=Strict`); enable strict session mode. - Constrain upload size/number; set resource limits (memory, post size, execution time). - Use Snuffleupagus or similar for additional hardening. ### Implementation Checklist - Use each framework’s built‑in CSRF/XSS/session protections and secure cookie flags. - Parameterize all data access; avoid dangerous OS/exec functions with untrusted input. - Enforce HTTPS/HSTS; set secure headers. - Centralize secret management; never hardcode secrets; lock down debug in production. - Validate/allow‑list redirects and dynamic identifiers. - Keep dependencies and frameworks updated; run SCA and static analysis regularly. ================================================ FILE: sources/core/codeguard-0-iac-security.md ================================================ --- description: Infrastructure as Code Security languages: - c - d - javascript - powershell - ruby - shell - yaml tags: - infrastructure alwaysApply: false --- # Infrastructure as Code (IaC) Security When designing cloud infrastructure and writing Infrastructure as Code (IaC) in languages like Terraform and CloudFormation, always use secure practices and defaults such as preventing public exposure and follow the principle of least privilege. Actively identify security misconfigurations and provide secure alternatives. ## Critical Security Patterns In Infrastructure as Code ### Network security - **ALWAYS** restrict the access to remote administrative services, databases, LDAP, TACACS+, or other sensitive services. No service should be accessible from the entire Internet if it does not need to be. Instead, restrict access to a specific set of IP addresses or CIDR blocks which require access. - Security Group and ACL inbound rules should **NEVER** allow `0.0.0.0/0` to remote administration ports (such as SSH 22, RDP 3389). - Security Group and ACL inbound rules should **NEVER** allow `0.0.0.0/0` to database ports (such as 3306, 5432, 1433, 1521, 27017). - Kubernetes API endpoints allow lists should **NEVER** allow `0.0.0.0/0`. EKS, AKS, GKE, and any other Kubernetes API endpoint should be restricted to an allowed list of CIDR addresses which require administrative access. - **NEVER** expose cloud platform database services (RDS, Azure SQL, Cloud SQL) to all IP addresses `0.0.0.0/0`. - Generally prefer private networking, such as internal VPC, VNET, VPN, or other internal transit unless public network access is required. - **ALWAYS** enable VPC/VNET flow logs for network monitoring and security analysis. - **ALWAYS** implement default deny rules and explicit allow rules for required traffic only. - Generally prefer blocking egress traffic to the Internet by default. If egress is required appropriate traffic control solutions might include: - Egress firewall or proxy with rules allowing access to specific required services. - Egress security group (SG) or access control list (ACL) with rules allowing access to specific required IPs or CIDR blocks. - DNS filtering to prevent access to malicious domains. ### Data protection - **ALWAYS** configure data encryption at rest for all storage services including databases, file systems, object storage, and block storage. - Enable encryption for cloud storage services (S3, Azure Blob, GCS buckets). - Configure database encryption at rest for all database engines (RDS, Azure SQL, Cloud SQL, DocumentDB, etc.). - Enable EBS/disk encryption for virtual machine storage volumes. - **ALWAYS** configure encryption in transit for all data communications. - Use TLS 1.2 or higher for all HTTPS/API communications. - Configure SSL/TLS for database connections with certificate validation. - Enable encryption for inter-service communication within VPCs/VNETs. - Use encrypted protocols for remote access (SSH, HTTPS, secure RDP). - **ALWAYS** implement data classification and protection controls based on sensitivity levels. - Apply stricter encryption and access controls for PII, PHI, financial data, and intellectual property. - Use separate encryption keys for different data classification levels. - **ALWAYS** configure secure data retention and disposal policies. - Define data retention periods based on regulatory and business requirements. - Implement automated data lifecycle management with secure deletion. - **ALWAYS** enable comprehensive data access monitoring and auditing. - Log all data access, modification, and deletion operations. - Monitor for unusual data access patterns and potential data exfiltration. - Implement real-time alerting for sensitive data access violations. - **ALWAYS** encrypt data backups. - Encrypt all backup data using separate encryption keys from production data. - Store backups in geographically distributed locations with appropriate access controls. - Test backup restoration procedures regularly and verify backup integrity. ### Access control - **NEVER** leave critical administration or data services with anonymous access (backups, storage, container registries, file shares) unless otherwise labeled as public classification or intended to be public. - **NEVER** use wildcard permissions in IAM policies or cloud RBAC (`"Action": "*"`, `"Resource": "*"`) - **NEVER** overprivilege service accounts with Owner/Admin roles when it is not necessary. - **NEVER** use service API Keys and client secrets and instead use workload identity with role-based access control to eliminate the need for long-lived credentials. - **NEVER** enable or use the legacy Instance Metadata Service version 1 (IMDSv1) in AWS. - **NEVER** use legacy or outdated authentication methods (such as local users) when there is a more secure alternative such as OAuth. ### Container and VM images - **NEVER** use non-hardened VM and container images. - **ALWAYS** choose distroless or minimal container images. - **RECOMMEND** using secure baseline virtual machine images from trusted sources. - **RECOMMEND** using minimal distroless container images from trusted sources. ### Logging and administrative access - **NEVER** disable administrative activity logging for sensitive services. - **ALWAYS** enable audit logging for privileged operations. ### Secrets management - **NEVER** hardcode secrets, passwords, API keys, or certificates directly in IaC source code. - **ALWAYS** in Terraform mark secrets with "sensitive = true", in other IaC code use appropriate annotations or metadata to indicate sensitive values. ### Backup and data recovery - **NEVER** create backups without encryption at rest and in transit. - **ALWAYS** configure multi-region data storage for backups with cross-region replication. - **NEVER** configure backups without retention policies and lifecycle management. ================================================ FILE: sources/core/codeguard-0-input-validation-injection.md ================================================ --- description: Input validation and injection defense (SQL/SOQL/LDAP/OS), parameterization, prototype pollution languages: - apex - c - go - html - java - javascript - php - powershell - python - ruby - shell - sql - typescript tags: - web alwaysApply: false --- ## Input Validation & Injection Defense Ensure untrusted input is validated and never interpreted as code. Prevent injection across SQL, LDAP, OS commands, templating, and JavaScript runtime object graphs. ### Core Strategy - Validate early at trust boundaries with positive (allow‑list) validation and canonicalization. - Treat all untrusted input as data, never as code. Use safe APIs that separate code from data. - Parameterize queries/commands; escape only as last resort and context‑specific. ### Validation Playbook - Syntactic validation: enforce format, type, ranges, and lengths for each field. - Semantic validation: enforce business rules (e.g., start ≤ end date, enum allow‑lists). - Normalization: canonicalize encodings before validation; validate complete strings (regex anchors ^$); beware ReDoS. - Free‑form text: define character class allow‑lists; normalize Unicode; set length bounds. - Files: validate by content type (magic), size caps, and safe extensions; server‑generate filenames; scan; store outside web root. ### SQL Injection Prevention - Use prepared statements and parameterized queries for 100% of data access. - Use bind variables for any dynamic SQL construction within stored procedures and never concatenate user input into SQL. - Prefer least‑privilege DB users and views; never grant admin to app accounts. - Escaping is fragile and discouraged; parameterization is the primary defense. Example (Java PreparedStatement): ```java String custname = request.getParameter("customerName"); String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( ); ``` ### SOQL/SOSL Injection (Salesforce) SOQL and SOSL are query/search languages (no SQL-style DDL/DML). Data changes are performed via Apex DML or Database methods. Note: SOQL can lock rows via `FOR UPDATE`. - Primary risk: data exfiltration by bypassing intended query filters/business logic; impact is amplified when Apex runs with elevated access (system mode) or when CRUD/FLS aren't enforced. - Second-order risk (conditional): if queried records are passed to DML, injection can broaden the record set and cause unintended mass updates/deletes. - Prefer static SOQL/SOSL with bind variables: `[SELECT Id FROM Account WHERE Name = :userInput]` or `FIND :term`. - For dynamic SOQL, use `Database.queryWithBinds()`; for dynamic SOSL, use `Search.query()`. Allow‑list any dynamic identifiers. If concatenation is unavoidable, escape string values with `String.escapeSingleQuotes()`. - Enforce CRUD/FLS with `WITH USER_MODE` or `WITH SECURITY_ENFORCED` (don't combine both). Enforce record sharing with `with sharing` or user-mode operations. Use `Security.stripInaccessible()` before DML. ### LDAP Injection Prevention - Always apply context‑appropriate escaping: - DN escaping for `\ # + < > , ; " =` and leading/trailing spaces - Filter escaping for `* ( ) \ NUL` - Validate inputs with allow‑lists before constructing queries; use libraries that provide DN/filter encoders. - Use least‑privilege LDAP connections with bind authentication; avoid anonymous binds for application queries. ### OS Command Injection Defense - Prefer built‑in APIs instead of shelling out (e.g., library calls over `exec`). - If unavoidable, use structured execution that separates command and arguments (e.g., ProcessBuilder). Do not invoke shells. - Strictly allow‑list commands and validate arguments with allow‑list regex; exclude metacharacters (& | ; $ > < ` \ ! ' " ( ) and whitespace as needed). - Use `--` to delimit arguments where supported to prevent option injection. Example (Java ProcessBuilder): ```java ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "Arg1", "Arg2"); Map env = pb.environment(); pb.directory(new File("TrustedDir")); Process p = pb.start(); ``` ### Query Parameterization Guidance - Use the platform’s parameterization features (JDBC PreparedStatement, .NET SqlCommand, Ruby ActiveRecord bind params, PHP PDO, SQLx bind, etc.). - For stored procedures, ensure parameters are bound; never build dynamic SQL via string concatenation inside procedures. ### Prototype Pollution (JavaScript) - Developers should use `new Set()` or `new Map()` instead of using object literals - When objects are required, create with `Object.create(null)` or `{ __proto__: null }` to avoid inherited prototypes. - Freeze or seal objects that should be immutable; consider Node `--disable-proto=delete` as defense‑in‑depth. - Avoid unsafe deep merge utilities; validate keys against allow‑lists and block `__proto__`, `constructor`, `prototype`. ### Caching and Transport - Apply `Cache-Control: no-store` on responses containing sensitive data; enforce HTTPS across data flows. ### Implementation Checklist - Central validators: types, ranges, lengths, enums; canonicalization before checks. - 100% parameterization coverage for SQL; dynamic identifiers via allow‑lists only. - LDAP DN/filter escaping in use; inputs validated prior to query. - No shell invocation for untrusted input; if unavoidable, structured exec + allow‑list + regex validation. - JS object graph hardened: safe constructors, blocked prototype paths, safe merge utilities. - File uploads validated by content, size, and extension; stored outside web root and scanned. ### Test Plan - Static checks for string concatenation in queries/commands and dangerous DOM/merge sinks. - Fuzzing for SQL/LDAP/OS injection vectors; unit tests for validator edge cases. - Negative tests exercising blocked prototype keys and deep merge behavior. ================================================ FILE: sources/core/codeguard-0-logging.md ================================================ --- description: Logging & monitoring (structured telemetry, redaction, integrity, detection & alerting) languages: - c - javascript - yaml tags: - privacy alwaysApply: false --- ## Logging & Monitoring Produce structured, privacy‑aware telemetry that supports detection, response, and forensics without exposing secrets. ### What to Log - Authn/authz events; admin actions; config changes; sensitive data access; input validation failures; security errors. - Include correlation/request IDs, user/session IDs (non‑PII), source IP, user agent, timestamps (UTC, RFC3339). ### How to Log - Structured logs (JSON) with stable field names; avoid free‑form text for critical signals. - Sanitize all log inputs to prevent log injection (strip CR/LF/delimiters); validate data from other trust zones. - Redact/tokenize secrets and sensitive fields; never log credentials, tokens, recovery codes, or raw session IDs. - Ensure integrity: append‑only or WORM storage; tamper detection; centralized aggregation; access controls and retention policies. ### Detection & Alerting - Build alerts for auth anomalies (credential stuffing patterns, impossible travel), privilege changes, excessive failures, SSRF indicators, and data exfil patterns. - Tune thresholds; provide runbooks; ensure on‑call coverage; test alert flows. ### Storage & Protection - Isolate log storage (separate partition/database); strict file/directory permissions; store outside web‑accessible locations. - Synchronize time across systems; use secure protocols for transmission; implement tamper detection and monitoring. ### Privacy & Compliance - Maintain data inventory and classification; minimize personal data in logs; honor retention and deletion policies. - Provide mechanisms to trace and delete user‑linked log data where required by policy. ### Implementation Checklist - JSON logging enabled; log injection sanitization active; redaction filters active; correlation IDs on all requests. - Isolated log storage with tamper detection; centralized log pipeline with integrity protections; retention configured. - Security alerts defined and tested; dashboards and reports in place. ### Validation - Unit/integration tests assert presence/absence of key fields; redaction unit tests. - Periodic audits for secret/PII leakage; tabletop exercises for incident workflows. ================================================ FILE: sources/core/codeguard-0-mcp-security.md ================================================ --- description: MCP (Model Context Protocol) Security based on CoSAI MCP Security guidelines languages: - python - javascript - typescript - go - rust - java alwaysApply: false --- # MCP (Model Context Protocol) Security Guidelines NEVER deploy MCP servers or clients without implementing proper security controls. ### Workload Identity and Authentication - Use SPIFFE/SPIRE for cryptographic workload identities - SPIFFE (Secure Production Identity Framework For Everyone) provides a standard for service identity - SPIRE (SPIFFE Runtime Environment) issues and rotates short-lived cryptographic identities (SVIDs) ### Input and Data Sanitization - Validate ALL inputs using allowlists at every trust boundary - Sanitize file paths through canonicalization - Use parameterized queries for database operations - Apply context-aware output encoding (SQL, shell, HTML) - Sanitize tool outputs: return only minimum fields, redact all PII and sensitive data - Treat ALL inputs, tool schemas, metadata, prompts, and resource content as untrusted input - Deploy prompt injection detection systems - Use strict JSON schemas to maintain boundaries between instructions and data ### Sandboxing and Isolation - Design MCP servers to execute with least privilege - MCP servers interacting with host environment (files, commands, network) MUST implement sandboxing controls - LLM-generated code MUST NOT run with full user privileges - Implement additional sandboxing layers: gVisor, Kata Containers, SELinux sandboxes ### Cryptographic Verification of Resources - Provide cryptographic signatures and SBOMs for all server code - Implement signature verification in your MCP client before loading servers - Use TLS for ALL data in transit - Implement remote attestation capabilities to verify servers are running expected code ### Transport Layer Security #### stdio Transport (Local Servers) - STRONGLY RECOMMENDED for local MCP to eliminate DNS rebinding risks - Direct pipe-based stream communication - Implement sandbox to prevent privilege escalation #### HTTP Streaming Transport (Remote Servers) Required security controls to implement: - Payload Limits (prevent large payload and recursive payload DoS) - Rate limiting for tool calls and transport requests - Client-Server Authentication/Authorization - Mutual TLS Authentication - TLS Encryption - CORS Protection - CSRF Protection - Integrity Checks (prevent replay, spoofing, poisoned responses) ### Secure Tool and UX Design - Create single-purpose tools with explicit boundaries; avoid "do anything" tools - Do not rely on the LLM for validation or authorization decisions - Use two-stage commit for high-impact actions: draft/preview first, explicit commit with confirmation second - Provide rollback/undo paths (draft IDs, snapshots, reversible actions) and time-bound commits when possible ### Human-in-the-Loop - Implement confirmation prompts for risky operations in your MCP server - Use elicitation on MCP server side to request user confirmation of risky actions - Security-relevant messages MUST clearly indicate implications - Do NOT rely solely on human approval (users can become fatigued) ### Logging and Observability - Implement logging in your MCP servers and clients - Log: tools that were used, parameters, originating prompt - Use OpenTelemetry for end-to-end linkability of actions - Maintain immutable records of actions and authorizations --- ## Deployment Pattern Security ### All-Local (stdio or http) - Security depends entirely on host system posture - Use `stdio` transport to avoid DNS rebinding risks - Use sandboxing to limit privilege escalation attacks - Appropriate for development and personal use ### Single-Tenant Remote (http) - Authentication between client and server is REQUIRED - Use secure credential storage (OS keychains, secret managers) - Communication MUST be authenticated and encrypted - Enterprise clients should enforce authenticated server discovery with explicit allowlists ### Multi-Tenant Remote (http) - Require robust tenant isolation, identity, and access control - Implement strong multi-tenancy controls (per-tenant encryption, role-based access control) - Prefer MCP servers hosted directly by service provider - Provide remote attestation when possible ================================================ FILE: sources/core/codeguard-0-mobile-apps.md ================================================ --- description: 'Mobile app security (iOS/Android): storage, transport, code integrity, biometrics, permissions' languages: - java - javascript - kotlin - matlab - perl - swift - xml alwaysApply: false --- ## Mobile Application Security Guidelines Essential security practices for developing secure mobile applications across iOS and Android platforms. ### Architecture and Design Implement secure design principles from the start: - Follow least privilege and defense in depth principles - Use standard secure authentication protocols (OAuth2, JWT) - Perform all authentication and authorization checks server-side - Request only necessary permissions for app and backend services - Establish security controls for app updates, patches, and releases - Use only trusted and validated third-party libraries and components ### Authentication and Authorization Never trust the client for security decisions: - Perform authentication/authorization server-side only - Do not store user passwords on device; use revocable access tokens - Avoid hardcoding credentials in the mobile app - Encrypt credentials in transmission - Use platform-specific secure storage (iOS Keychain, Android Keystore) - Require password complexity and avoid short PINs (4 digits) - Implement session timeouts and remote logout functionality - Require re-authentication for sensitive operations - Use platform-supported biometric authentication with secure fallbacks ### Data Storage and Privacy Protect sensitive data at rest and in transit: - Encrypt sensitive data using platform APIs; avoid custom encryption - Leverage hardware-based security features (Secure Enclave, Strongbox) - Store private data on device's internal storage only - Minimize PII collection to necessity and implement automatic expiration - Avoid caching, logging, or background snapshots of sensitive data - Always use HTTPS for network communications ### Network Communication Assume all network communication is insecure: - Use HTTPS for all network communication - Do not override SSL certificate validation for self-signed certificates - Use strong, industry standard cipher suites with appropriate key lengths - Use certificates signed by trusted CA providers - Consider certificate pinning for additional security - Encrypt data even if sent over SSL - Avoid sending sensitive data via SMS ### Code Quality and Integrity Maintain application security throughout development: - Use static analysis tools to identify vulnerabilities - Make security a focal point during code reviews - Keep all libraries up to date to patch known vulnerabilities - Disable debugging in production builds - Include code to validate integrity of application code - Obfuscate the app binary - Implement runtime anti-tampering controls: - Check for debugging, hooking, or code injection - Detect emulator or rooted/jailbroken devices - Verify app signatures at runtime ### Platform-Specific Security #### Android Security - Use Android's ProGuard for code obfuscation - Avoid storing sensitive data in SharedPreferences - Disable backup mode to prevent sensitive data in backups - Use Android Keystore with hardware backing (TEE or StrongBox) - Implement Google's Play Integrity API for device and app integrity checks #### iOS Security - Configure Shortcuts permissions to require device unlock for sensitive actions - Set Siri intent `requiresUserAuthentication` to true for sensitive functionality - Implement authentication checks on deep link endpoints - Use conditional logic to mask sensitive widget content on lock screen - Store sensitive data in iOS Keychain, not plist files - Use Secure Enclave for cryptographic key storage - Implement App Attest API for app integrity validation - Use DeviceCheck API for persistent device state tracking ### Testing and Monitoring Validate security controls through comprehensive testing: - Perform penetration testing including cryptographic vulnerability assessment - Leverage automated tests to ensure security features work as expected - Ensure security features do not harm usability - Use real-time monitoring to detect and respond to threats - Have a clear incident response plan in place - Plan for regular updates and implement forced update mechanisms when necessary ### Input and Output Validation Prevent injection and execution attacks: - Validate and sanitize all user input - Validate and sanitize output to prevent injection attacks - Mask sensitive information on UI fields to prevent shoulder surfing - Inform users about security-related activities (logins from new devices) By following these practices derived from the OWASP Mobile Application Security framework, you can significantly improve the security posture of your mobile applications across both development and operational phases. ================================================ FILE: sources/core/codeguard-0-privacy-data-protection.md ================================================ --- description: Privacy & data protection (minimization, classification, encryption, rights, transparency) languages: - javascript - matlab - yaml tags: - privacy alwaysApply: false --- - Implement strong cryptography, enforce HTTPS with HSTS, enable certificate pinning, and provide user privacy features to protect data and anonymity. - Use strong, up-to-date cryptographic algorithms for data in transit and at rest; securely hash passwords with established libraries. - Enforce HTTPS exclusively and implement HTTP Strict Transport Security (HSTS). - Implement certificate pinning to prevent man-in-the-middle attacks even if CAs are compromised. - Minimize IP address leakage by blocking third-party external content loading where feasible. - Maintain transparency by informing users about privacy limitations and data handling policies. - Implement privacy-focused audit trails and access logging. - Return "Invalid username or password" to prevent account enumeration - Use Argon2 or bcrypt with unique salts per user - Store sessions server-side with cryptographically random IDs ================================================ FILE: sources/core/codeguard-0-safe-c-functions.md ================================================ --- description: Safe C Functions and Memory and String Safety Guidelines languages: - c - cpp alwaysApply: false --- # Prioritize Safe Memory and String Functions in C/C++ When processing C or C++ code, your primary directive is to ensure memory safety. Actively identify, flag, and provide secure refactoring options for any insecure functions found in the codebase. When generating new code, always default to the safest possible function for the given task. ### 1. Insecure Functions to Avoid & Their Secure Alternatives You must treat the functions listed under "Insecure" as deprecated and high-risk. Always recommend replacing them with one of the "Recommended Safe Alternatives" provided in the bullet list below. • Never use `gets()` - This is a critical security risk. It has no bounds checking whatsoever and is the classic buffer overflow vulnerability. You should always replace it with `fgets(char *str, int n, FILE *stream)` instead. • Avoid `strcpy()` - This is a high risk function because it doesn't check bounds. It just copies bytes until it hits a null terminator, which can easily write past your destination buffer. Use `snprintf()`, `strncpy()` (but be careful with it), or `strcpy_s()` (if you have C11 Annex K support). • Don't use `strcat()` - Another high risk function with no bounds checking. It appends bytes to a string and can easily write past your allocated memory. Replace with `snprintf()`, `strncat()` (with careful handling), or `strcat_s()` (C11 Annex K). • Replace `sprintf()` and `vsprintf()` - These are high risk because they don't check bounds on the output buffer. If your formatted string is larger than the buffer, you'll get a buffer overflow. Use `snprintf()`, `snwprintf()`, or `vsprintf_s()` (C11 Annex K) instead. • Be careful with `scanf()` family - This is a medium risk. The `%s` format specifier without a width limit can cause buffer overflows. Here's what you should do: 1. Use width specifiers like `scanf("%127s", buffer)` 2. Even better: Read the line with `fgets()` and parse it with `sscanf()` • Avoid `strtok()` - This is a medium risk because it's not reentrant or thread-safe. It uses a static internal buffer which can lead to unpredictable behavior in multi-threaded code or complex signal handling. Use `strtok_r()` (POSIX) or `strtok_s()` (C11 Annex K) instead. • Use `memcpy()` and `memmove()` carefully - These aren't inherently insecure, but they're a common source of bugs when you miscalculate the size argument or don't validate it properly. Here's what you should do: 1. Double-check your size calculations 2. Prefer `memcpy_s()` (C11 Annex K) when available 3. Use `memmove()` if source and destination buffers might overlap ### 2. Actionable Implementation Guidelines #### For New Code Generation: - NEVER generate code that uses `gets()`, `strcpy()`, `strcat()`, or `sprintf()`. - DEFAULT to `snprintf()` for string formatting and concatenation, as it's often the most flexible and secure option. - DEFAULT to `fgets()` for reading string input from files or standard input. #### For Code Analysis and Refactoring: 1. Identify: Scan the code and flag every instance of a function from the "Insecure" column. 2. Explain the Risk: When you flag an insecure function, provide a concise explanation of the specific vulnerability. - _Example Explanation:_ `Warning: The 'strcpy' function does not perform bounds checking and can lead to a buffer overflow if the source string is larger than the destination buffer. This is a common security vulnerability.` 3. Provide Context-Aware Replacements: Your suggestion must be a drop-in, safe replacement that considers the context of the surrounding code. #### Use Compiler Flags: Enable these protective compiler flags to catch buffer overflow vulnerabilities at compile time and runtime: - Stack Protection: Use `-fstack-protector-all` or `-fstack-protector-strong` to detect stack buffer overflows - Address Sanitizer: Use `-fsanitize=address` during development to catch memory errors - Object Size Checking (OSC): Use `-D_FORTIFY_SOURCE=2` to enable runtime checks for buffer overflows in functions like `strcpy`, `strcat`, `sprintf`, etc. This adds bounds checking to many of the unsafe functions mentioned above - Format String Protection: Use `-Wformat -Wformat-security` to catch format string vulnerabilities ### 3. Refactoring Examples Your suggestions should be concrete and actionable. Example 1: Replacing `strcpy` - Original Unsafe Code: ``` char destination[64]; strcpy(destination, source_string); ``` - Your Suggested Refactoring: ``` char destination[64]; snprintf(destination, sizeof(destination), "%s", source_string); ``` - Your Explanation: `Replaced 'strcpy' with 'snprintf' to ensure that no more than 63 characters plus a null terminator are written to the destination buffer, preventing a potential buffer overflow.` Example 2: Correcting `strncpy` Usage The `strncpy` function is a common but imperfect replacement. It may not null-terminate the destination buffer. If you must use it or see it used, you must enforce correct handling. - Original (Potentially Unsafe) `strncpy`: ``` // This is unsafe if strlen(source) >= 10 char dest[10]; strncpy(dest, source, sizeof(dest)); ``` - Your Corrected Suggestion: ``` char dest[10]; strncpy(dest, source, sizeof(dest) - 1); dest[sizeof(dest) - 1] = '\0'; ``` - Your Explanation: `Added an explicit null termination for 'strncpy'. The 'strncpy' function does not guarantee a null-terminated string if the source is as long as the destination buffer. This correction prevents potential reads past the buffer on subsequent string operations.` Example 3: Securing `scanf` - Original Unsafe Code: ``` char user_name[32]; printf("Enter your name: "); scanf("%s", user_name); ``` - Your Suggested Refactoring: ``` char user_name[32]; printf("Enter your name: "); if (fgets(user_name, sizeof(user_name), stdin)) { // Optional: Remove trailing newline character from fgets user_name[strcspn(user_name, "\n")] = 0; } ``` - Your Explanation: `Replaced 'scanf("%s", ...)' with 'fgets()' to read user input. 'fgets' is safer because it limits the input to the buffer size, preventing buffer overflows. The original 'scanf' had no such protection.` ### Memory and String Safety Guidelines #### Unsafe Memory Functions - FORBIDDEN NEVER use these unsafe memory functions that don't check input parameter boundaries: ##### Banned Memory Functions: - `memcpy()` → Use `memcpy_s()` - `memset()` → Use `memset_s()` - `memmove()` → Use `memmove_s()` - `memcmp()` → Use `memcmp_s()` - `bzero()` → Use `memset_s()` - `memzero()` → Use `memset_s()` ##### Safe Memory Function Replacements: ```c // Instead of: memcpy(dest, src, count); errno_t result = memcpy_s(dest, dest_size, src, count); if (result != 0) { // Handle error } // Instead of: memset(dest, value, count); errno_t result = memset_s(dest, dest_size, value, count); // Instead of: memmove(dest, src, count); errno_t result = memmove_s(dest, dest_size, src, count); // Instead of: memcmp(s1, s2, count); int indicator; errno_t result = memcmp_s(s1, s1max, s2, s2max, count, &indicator); if (result == 0) { // indicator contains comparison result: <0, 0, or >0 } ``` #### Unsafe String Functions - FORBIDDEN NEVER use these unsafe string functions that can cause buffer overflows: ##### Banned String Functions: - `strstr()` → Use `strstr_s()` - `strtok()` → Use `strtok_s()` - `strcpy()` → Use `strcpy_s()` - `strcmp()` → Use `strcmp_s()` - `strlen()` → Use `strnlen_s()` - `strcat()` → Use `strcat_s()` - `sprintf()` → Use `snprintf()` ##### Safe String Function Replacements: ```c // String Search errno_t strstr_s(char *dest, rsize_t dmax, const char *src, rsize_t slen, char **substring); // String Tokenization char *strtok_s(char *dest, rsize_t *dmax, const char *src, char **ptr); // String Copy errno_t strcpy_s(char *dest, rsize_t dmax, const char *src); // String Compare errno_t strcmp_s(const char *dest, rsize_t dmax, const char *src, int *indicator); // String Length (bounded) rsize_t strnlen_s(const char *str, rsize_t strsz); // String Concatenation errno_t strcat_s(char *dest, rsize_t dmax, const char *src); // Formatted String (always use size-bounded version) int snprintf(char *s, size_t n, const char *format, ...); ``` #### Implementation Examples: ##### Safe String Copy Pattern: ```c // Bad - unsafe char dest[256]; strcpy(dest, src); // Buffer overflow risk! // Good - safe char dest[256]; errno_t result = strcpy_s(dest, sizeof(dest), src); if (result != 0) { // Handle error: src too long or invalid parameters EWLC_LOG_ERROR("String copy failed: %d", result); return ERROR; } ``` ##### Safe String Concatenation Pattern: ```c // Bad - unsafe char buffer[256] = "prefix_"; strcat(buffer, suffix); // Buffer overflow risk! // Good - safe char buffer[256] = "prefix_"; errno_t result = strcat_s(buffer, sizeof(buffer), suffix); if (result != 0) { EWLC_LOG_ERROR("String concatenation failed: %d", result); return ERROR; } ``` ##### Safe Memory Copy Pattern: ```c // Bad - unsafe memcpy(dest, src, size); // No boundary checking! // Good - safe errno_t result = memcpy_s(dest, dest_max_size, src, size); if (result != 0) { EWLC_LOG_ERROR("Memory copy failed: %d", result); return ERROR; } ``` ##### Safe String Tokenization Pattern: ```c // Bad - unsafe char *token = strtok(str, delim); // Modifies original string unsafely // Good - safe char *next_token = NULL; rsize_t str_max = strnlen_s(str, MAX_STRING_SIZE); char *token = strtok_s(str, &str_max, delim, &next_token); while (token != NULL) { // Process token token = strtok_s(NULL, &str_max, delim, &next_token); } ``` #### Memory and String Safety Code Review Checklist: ##### Pre-Code Review (Developer): - [ ] No unsafe memory functions (`memcpy`, `memset`, `memmove`, `memcmp`, `bzero`) - [ ] No unsafe string functions (`strcpy`, `strcat`, `strcmp`, `strlen`, `sprintf`, `strstr`, `strtok`) - [ ] All memory operations use `*_s()` variants with proper size parameters - [ ] Buffer sizes are correctly calculated using `sizeof()` or known limits - [ ] No hardcoded buffer sizes that could change ##### Code Review (Reviewer): - [ ] Memory Safety: Verify all memory operations use safe variants - [ ] Buffer Bounds: Confirm destination buffer sizes are properly specified - [ ] Error Handling: Check that all `errno_t` return values are handled - [ ] Size Parameters: Validate that `rsize_t dmax` parameters are correct - [ ] String Termination: Ensure strings are properly null-terminated - [ ] Length Validation: Check that source string lengths are validated before operations ##### Static Analysis Integration: - [ ] Enable compiler warnings for unsafe function usage - [ ] Use static analysis tools to detect unsafe function calls - [ ] Configure build system to treat unsafe function warnings as errors - [ ] Add pre-commit hooks to scan for banned functions #### Common Pitfalls and Solutions: ##### Pitfall 1: Wrong Size Parameter ```c // Wrong - using source size instead of destination size strcpy_s(dest, strlen(src), src); // WRONG! // Correct - using destination buffer size strcpy_s(dest, sizeof(dest), src); // CORRECT ``` ##### Pitfall 2: Ignoring Return Values ```c // Wrong - ignoring potential errors strcpy_s(dest, sizeof(dest), src); // Error not checked // Correct - checking return value if (strcpy_s(dest, sizeof(dest), src) != 0) { // Handle error appropriately } ``` ##### Pitfall 3: Using sizeof() on Pointers ```c // Wrong - sizeof pointer, not buffer void func(char *buffer) { strcpy_s(buffer, sizeof(buffer), src); // sizeof(char*) = 8! } // Correct - pass buffer size as parameter void func(char *buffer, size_t buffer_size) { strcpy_s(buffer, buffer_size, src); } ``` You must always explain how this rule was applied and why it was applied. ================================================ FILE: sources/core/codeguard-0-session-management-and-cookies.md ================================================ --- description: Session management and secure cookies (rotation, fixation, timeouts, theft detection) languages: - c - go - html - java - javascript - php - python - ruby - typescript tags: - authentication - web alwaysApply: false --- ## Session Management & Cookies Implement robust, attack-resistant session handling that prevents fixation, hijacking, and theft while maintaining usability. ### Session ID Generation and Properties - Generate session IDs with a CSPRNG; ≥64 bits of entropy (prefer 128+). Opaque, unguessable, and free of meaning. - Use generic cookie names (e.g., `id`) rather than framework defaults. Reject any incoming ID not created by the server. - Store all session data server-side; never embed PII or privileges in the token. If sensitive, encrypt server-side session store at rest. ### Cookie Security Configuration - Set `Secure`, `HttpOnly`, `SameSite=Strict` (or `Lax` if necessary for flows) on session cookies. - Scope cookies narrowly with `Path` and `Domain`. Avoid cross-subdomain exposure. - Prefer non-persistent session cookies (no Expires/Max-Age). Require full HTTPS; enable HSTS site-wide. Example header: ``` Set-Cookie: id=; Secure; HttpOnly; SameSite=Strict; Path=/ ``` ### Session Lifecycle and Rotation - Create sessions only server-side; treat provided IDs as untrusted input. - Regenerate session ID on authentication, password changes, and any privilege elevation. Invalidate the prior ID. - Use distinct pre‑auth and post‑auth cookie names if framework patterns require it. ### Expiration and Logout - Idle timeout: 2–5 minutes for high-value, 15–30 minutes for lower risk. Absolute timeout: 4–8 hours. - Enforce timeouts server-side. Provide a visible logout button that fully invalidates the server session and clears the cookie client-side. ### Transport and Caching - Enforce HTTPS for the entire session journey. Never mix HTTP/HTTPS in one session. - Send `Cache-Control: no-store` on responses containing session identifiers or sensitive data. ### Cookie Theft Detection and Response - Fingerprint session context server-side at establishment (IP, User-Agent, Accept-Language, relevant `sec-ch-ua` where available). - Compare incoming requests to the stored fingerprint, allowing for benign drift (e.g., subnet changes, UA updates). - Risk-based responses: - High risk: require re-authentication; rotate session ID. - Medium risk: step-up verification (challenge); rotate session ID. - Low risk: log suspicious activity. - Always regenerate the session ID when potential hijacking is detected. ### Client-Side Storage - Do not store session tokens in `localStorage`/`sessionStorage` due to XSS risk. Prefer HttpOnly cookies for transport. - If client-side storage is unavoidable for non-session secrets, isolate via Web Workers and never expose in page context. ### Framework and Multi-Cookie Scenarios - Prefer built-in session frameworks; keep them updated and hardened. - Validate relationships when multiple cookies participate in session state; avoid same cookie names across paths/domains. ### Monitoring and Telemetry - Log session lifecycle events (creation, rotation, termination) using salted hashes of the session ID, not raw values. - Monitor for brute force of session IDs and anomalous concurrent usage. ### Implementation Checklist 1) CSPRNG session IDs (≥64 bits entropy), opaque and server-issued only. 2) Cookie flags: `Secure`, `HttpOnly`, `SameSite` set; tight domain/path. 3) HTTPS-only with HSTS; no mixed content. 4) Regenerate IDs on auth and privilege changes; invalidate old IDs. 5) Idle and absolute timeouts enforced server-side; full logout implemented. 6) `Cache-Control: no-store` for sensitive responses. 7) Server-side fingerprinting and risk-based responses to anomalies. 8) No client storage of session tokens; framework defaults hardened. ================================================ FILE: sources/core/codeguard-0-supply-chain-security.md ================================================ --- description: Dependency & supply chain security (pinning, SBOM, provenance, integrity, private registries) languages: - docker - javascript - yaml alwaysApply: false --- ## Dependency & Supply Chain Security Control third‑party risk across ecosystems, from selection and pinning to provenance, scanning, and rapid response. ### Policy and Governance - Maintain allow‑listed registries and scopes; disallow direct installs from untrusted sources. - Require lockfiles and version pinning; prefer digest pinning for images and vendored assets. - Generate SBOMs for apps/images; store with artifacts; attest provenance (SLSA, Sigstore). ### Package Hygiene (npm focus applicable to others) - Regularly audit (`npm audit`, ecosystem SCA) and patch; enforce SLAs by severity. - Use deterministic builds: `npm ci` (not `npm install`) in CI/CD; maintain lockfile consistency. - Avoid install scripts that execute on install when possible; review for risk. - Use `.npmrc` to scope private registries; avoid wildcard registries; enable integrity verification. - Enable account 2FA for publishing ### Development Practices - Minimize dependency footprint; remove unused packages; prefer stdlib/first‑party for trivial tasks. - Protect against typosquatting and protestware: pin maintainers, monitor releases, and use provenance checks. - Hermetic builds: no network in compile/packaging stages unless required; cache with authenticity checks. ### CI/CD Integration - SCA, SAST, IaC scans in gates; fail on criticals; require approvals for overrides with compensating controls. - Sign artifacts; verify signatures at deploy; enforce policy in admission. ### Vulnerability Management - For patched vulnerabilities: test and deploy updates; document any API breaking changes. - For unpatched vulnerabilities: implement compensating controls (input validation, wrappers) based on CVE type; prefer direct dependency fixes over transitive workarounds. - Document risk decisions; escalate acceptance to appropriate authority with business justification. ### Incident Response - Maintain rapid rollback; isolate compromised packages; throttle rollouts; notify stakeholders. - Monitor threat intel feeds (e.g., npm advisories); auto‑open tickets for critical CVEs. ### Implementation Checklist - Lockfiles present; integrity checks on; private registries configured. - SBOM + provenance stored; signatures verified pre‑deploy. - Automated dependency updates with tests and review gates. - High‑sev vulns remediated within SLA or mitigated and documented. ================================================ FILE: sources/core/codeguard-0-xml-and-serialization.md ================================================ --- description: XML security and safe deserialization (DTD/XXE hardening, schema validation, no unsafe native deserialization) languages: - c - go - java - php - python - ruby - xml alwaysApply: false --- ## XML & Serialization Hardening Secure parsing and processing of XML and serialized data; prevent XXE, entity expansion, SSRF, DoS, and unsafe deserialization across platforms. ### XML Parser Hardening - Disable DTDs and external entities by default; reject DOCTYPE declarations. - Validate strictly against local, trusted XSDs; set explicit limits (size, depth, element counts). - Sandbox or block resolver access; no network fetches during parsing; monitor for unexpected DNS activity. #### Java General principle: ```java factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); ``` Disabling DTDs protects against XXE and Billion Laughs attacks. If DTDs cannot be disabled, disable external entities using parser-specific methods. ### Java Java parsers have XXE enabled by default. DocumentBuilderFactory/SAXParserFactory/DOM4J: ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); String FEATURE = null; try { // PRIMARY defense - disallow DTDs completely FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; dbf.setFeature(FEATURE, true); dbf.setXIncludeAware(false); } catch (ParserConfigurationException e) { logger.info("ParserConfigurationException was thrown. The feature '" + FEATURE + "' is not supported by your XML processor."); } ``` If DTDs cannot be completely disabled: ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); String[] featuresToDisable = { "http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://apache.org/xml/features/nonvalidating/load-external-dtd" }; for (String feature : featuresToDisable) { try { dbf.setFeature(feature, false); } catch (ParserConfigurationException e) { logger.info("ParserConfigurationException was thrown. The feature '" + feature + "' is probably not supported by your XML processor."); } } dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); ``` #### .NET ```csharp var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; var reader = XmlReader.Create(stream, settings); ``` #### Python ```python from defusedxml import ElementTree as ET ET.parse('file.xml') # or lxml from lxml import etree parser = etree.XMLParser(resolve_entities=False, no_network=True) tree = etree.parse('filename.xml', parser) ``` ### Secure XSLT/Transformer Usage - Set `ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_STYLESHEET` to empty; avoid loading remote resources. ### Deserialization Safety - Never deserialize untrusted native objects. Prefer JSON with schema validation. - Enforce size/structure limits before parsing. Reject polymorphic types unless strictly allow‑listed. - Language specifics: - PHP: avoid `unserialize()`; use `json_decode()`. - Python: avoid `pickle` and unsafe YAML (`yaml.safe_load` only). - Java: override `ObjectInputStream#resolveClass` to allow‑list; avoid enabling default typing in Jackson; use XStream allow‑lists. - .NET: avoid `BinaryFormatter`; prefer `DataContractSerializer` or `System.Text.Json` with `TypeNameHandling=None` for JSON.NET. - Sign and verify serialized payloads where applicable; log and alert on deserialization failures and anomalies. ### Implementation Checklist - DTDs off; external entities disabled; strict schema validation; parser limits set. - No network access during parsing; resolvers restricted; auditing in place. - No unsafe native deserialization; strict allow‑listing and schema validation for supported formats. - Regular library updates and tests with XXE/deserialization payloads. ================================================ FILE: sources/core/codeguard-1-crypto-algorithms.md ================================================ --- description: Cryptographic Security Guidelines & Post-Quantum Readiness languages: [] alwaysApply: true --- # Cryptographic Security Guidelines & Post-Quantum Readiness ## 1. Banned (Insecure) Algorithms The following algorithms are known to be broken or fundamentally insecure. NEVER generate or use code with these algorithms. * Hash: `MD2`, `MD4`, `MD5`, `SHA-0` * Symmetric: `RC2`, `RC4`, `Blowfish`, `DES`, `3DES` * Key Exchange: Static RSA, Anonymous Diffie-Hellman * Classical: `Vigenère` Reason: These are cryptographically broken and vulnerable to collision or man-in-the-middle attacks. ## 2. Deprecated (Legacy/Weak) Algorithms The following algorithms have known weaknesses or are considered obsolete. Avoid in new designs and prioritize migration. * Hash: `SHA-1` * Symmetric: `AES-CBC`, `AES-ECB` * Signature: RSA with `PKCS#1 v1.5` padding * Key Exchange: DHE with weak/common primes ## 3. Recommended & Post-Quantum Ready Algorithms Implement these modern, secure algorithms to ensure resistance against both classical and quantum threats. ### Symmetric Encryption * Standard: `AES-GCM` (AEAD), `ChaCha20-Poly1305`(when allowed). * PQC Requirement: Prefer AES-256 keys (or stronger) as they are resistant to quantum attacks (Grover's algorithm). * Avoid: Custom crypto or unauthenticated modes. ### Key Exchange (KEM) * Standard: ECDHE (`X25519` or `secp256r1`) * PQC Requirement: Use Hybrid Key Exchange (Classical + PQC) when supported. * Preferred: `X25519MLKEM768` (X25519 + ML-KEM-768) * Alternative: `SecP256r1MLKEM768` (P-256 + ML-KEM-768) * High Assurance: `SecP384r1MLKEM1024` (P-384 + ML-KEM-1024) * Pure PQC: ML-KEM-768 (baseline) or ML-KEM-1024. Avoid ML-KEM-512 unless explicitly risk-accepted. * Constraints: * Use vendor-documented identifiers (RFC 9242/9370). * Remove legacy/draft "Hybrid-Kyber" groups (e.g., `X25519Kyber`) and draft or hardcoded OIDs. ### Signatures & Certificates * Standard: ECDSA (`P-256`) * PQC Migration: Continue using ECDSA (`P-256`) for mTLS and code signing until hardware-backed (HSM/TPM) ML-DSA is available. * Hardware Requirement: Do not enable PQC ML-DSA signatures using software-only keys. Require HSM/TPM storage. ### Protocol Versions * (D)TLS: Enforce (D)TLS 1.3 only (or later). * IPsec: Enforce IKEv2 only. * Use ESP with AEAD (AES-256-GCM). * Require PFS via ECDHE. * Implement RFC 9242 and RFC 9370 for Hybrid PQC (ML-KEM + ECDHE). * Ensure re-keys (CREATE_CHILD_SA) maintain hybrid algorithms. * SSH: Enable only vendor-supported PQC/hybrid KEX (e.g., `sntrup761x25519`). ## 4. Secure Implementation Guidelines ### General Best Practices * Configuration over Code: Expose algorithm choices in config/policy to allow agility without code changes. * Key Management: * Use KMS/HSM for key storage. * Generate keys with a CSPRNG. * Separate encryption keys from signature keys. * Rotate keys per policy. * NEVER hardcode keys, secrets, or experimental OIDs. * Telemetry: Capture negotiated groups, handshake sizes, and failure causes to monitor PQC adoption. ### Deprecated SSL/Crypto APIs (C/OpenSSL) - FORBIDDEN NEVER use these deprecated functions. Use the replacement EVP high-level APIs. #### Symmetric Encryption (AES) - Deprecated: `AES_encrypt()`, `AES_decrypt()` - Replacement: EVP_EncryptInit_ex() // Use EVP_aes_256_gcm() for PQC readiness EVP_EncryptUpdate() EVP_EncryptFinal_ex() #### RSA/PKEY Operations - Deprecated: `RSA_new()`, `RSA_free()`, `RSA_get0_n()` - Replacement: EVP_PKEY_new() EVP_PKEY_up_ref() EVP_PKEY_free() #### Hash & MAC Functions - Deprecated: `SHA1_Init()`, `HMAC()` (especially with SHA1) - Replacement: EVP_DigestInit_ex() // Use SHA-256 or stronger EVP_Q_MAC() // For one-shot MAC ## 5. Broccoli Project Specific Requirements - HMAC() with SHA1: Deprecated. - Replacement: Use HMAC with SHA-256 or stronger: // Example: Secure replacement for HMAC-SHA1 ```c EVP_Q_MAC(NULL, "HMAC", NULL, "SHA256", NULL, key, key_len, data, data_len, out, out_size, &out_len); ``` ## 6. Secure Crypto Implementation Pattern // Example: Secure AES-256-GCM encryption (PQC-Ready Symmetric Strength) ```c EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (!ctx) handle_error(); // Use AES-256-GCM if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv) != 1) handle_error(); int len, ciphertext_len; if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len) != 1) handle_error(); ciphertext_len = len; if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1) handle_error(); ciphertext_len += len; EVP_CIPHER_CTX_free(ctx); ``` ================================================ FILE: sources/core/codeguard-1-digital-certificates.md ================================================ --- description: Certificate Best Practices languages: [] tags: - secrets alwaysApply: true --- When you encounter data that appears to be an X.509 certificate—whether embedded as a string or loaded from a file—you must flag the certificate for verification and ensure the following security properties are validated, reporting any concerns with clear explanations and recommended actions. ### 1. How to Identify Certificate Data Actively scan for certificate data using the following heuristics: - PEM-Encoded Strings: Identify multi-line string literals or constants that begin with `-----BEGIN CERTIFICATE-----` and end with `-----END CERTIFICATE-----`. - File Operations: Pay close attention to file read operations on files with common certificate extensions, such as `.pem`, `.crt`, `.cer`, and `.der`. - Library Function Calls: Recognize the usage of functions from cryptographic libraries used to load or parse certificates (e.g., OpenSSL's `PEM_read_X509`, Python's `cryptography.x509.load_pem_x509_certificate`, Java's `CertificateFactory`). ### 2. Mandatory Sanity Checks Once certificate data is identified, flag it for verification. The following properties must be validated to ensure the certificate meets security requirements: #### Verification Guidance To inspect certificate properties, recommend running: ``` openssl x509 -text -noout -in ``` This command displays expiration dates, key algorithm and size, signature algorithm, and issuer/subject information needed for the checks below. #### Check 1: Expiration Status - Condition: The certificate's `notAfter` (expiration) date is in the past. - Severity: CRITICAL VULNERABILITY - Report Message: `This certificate expired on [YYYY-MM-DD]. It is no longer valid and will be rejected by clients, causing connection failures. It must be renewed and replaced immediately.` - Condition: The certificate's `notBefore` (validity start) date is in the future. - Severity: Warning - Report Message: `This certificate is not yet valid. Its validity period begins on [YYYY-MM-DD].` #### Check 2: Public Key Strength - Condition: The public key algorithm or size is weak. - Weak Keys: RSA keys with a modulus smaller than 2048 bits. Elliptic Curve (EC) keys using curves with less than a 256-bit prime modulus (e.g., `secp192r1`, `P-192`, `P-224`). - Severity: High-Priority Warning - Report Message: `The certificate's public key is cryptographically weak ([Algorithm], [Key Size]). Keys of this strength are vulnerable to factorization or discrete logarithm attacks. The certificate should be re-issued using at least an RSA 2048-bit key or an ECDSA key on a P-256 (or higher) curve.` #### Check 3: Signature Algorithm - Condition: The algorithm used to sign the certificate is insecure. - Insecure Algorithms: Any signature algorithm using MD5 or SHA-1 (e.g., `md5WithRSAEncryption`, `sha1WithRSAEncryption`). - Severity: High-Priority Warning - Report Message: `The certificate is signed with the insecure algorithm '[Algorithm]'. This makes it vulnerable to collision attacks, potentially allowing for certificate forgery. It must be re-issued using a signature based on the SHA-2 family (e.g., sha256WithRSAEncryption).` #### Check 4: Issuer Type (Self-Signed Check) - Condition: The certificate's `Issuer` and `Subject` fields are identical. - Severity: Informational - Report Message: `This is a self-signed certificate. Ensure this is intentional and only used for development, testing, or internal services where trust is explicitly configured. Self-signed certificates should never be used for public-facing production systems as they will not be trusted by browsers or standard clients.` ### 3. Actionable Examples Your feedback should be direct and easy to understand. Example 1: Flagging a Hardcoded Certificate - Code Snippet: ``` # Certificate for connecting to legacy_service LEGACY_CERT = """ -----BEGIN CERTIFICATE----- MIIC... (certificate data) ... -----END CERTIFICATE----- """ ``` - Your Analysis and Report: > Security Review Required: A certificate is hardcoded in the `LEGACY_CERT` variable. Unverified certificates may contain critical vulnerabilities. > > - Concern: Hardcoded certificates cannot be easily rotated and may contain security issues that are not immediately visible in the code. > > - Required Verification: This certificate must be verified for: > - Expiration: Certificate must not be expired or not yet valid > - Key Strength: RSA keys must be at least 2048-bit; EC keys must use P-256 or higher curve > - Signature Algorithm: Must use SHA-2 family (not MD5 or SHA-1) > - Self-Signed: If self-signed, must only be used for development, testing, or internal services > > - Action: Verify this certificate meets the above requirements before deployment. Consider loading certificates from external files or a certificate store for easier rotation. > Example 2: Flagging a Certificate Loaded from File - Code Snippet: ``` // Load the server certificate from disk cert, err := tls.LoadX509KeyPair("server.crt", "server.key") ``` - Your Analysis and Report: > Security Review Required: Certificate loaded from `server.crt`. Unverified certificates may contain critical vulnerabilities. > > - Required Verification: Ensure this certificate meets security requirements: > - Expiration: Certificate must not be expired or not yet valid > - Key Strength: RSA keys must be at least 2048-bit; EC keys must use P-256 or higher curve > - Signature Algorithm: Must use SHA-2 family (not MD5 or SHA-1) > - Self-Signed: If self-signed, must only be used for development, testing, or internal services > > - Action: Verify this certificate meets the above requirements before deployment. You must always explain how this rule was applied and why it was applied. ================================================ FILE: sources/core/codeguard-1-hardcoded-credentials.md ================================================ --- description: No Hardcoded Credentials languages: [] tags: - secrets alwaysApply: true --- # No Hardcoded Credentials NEVER store secrets, passwords, API keys, tokens or any other credentials directly in source code. Treat your codebase as public and untrusted. Any credential that appears in source code is compromised and must be handled through secure alternatives. #### NEVER hardcode these types of values: Passwords and Authentication: - Database passwords, user passwords, admin passwords - API keys, secret keys, access tokens, refresh tokens - Private keys, certificates, signing keys - Connection strings containing credentials - OAuth client secrets, webhook secrets - Any other credentials that could be used to access external services #### Recognition Patterns - Learn to Spot These Formats Common Secret Formats You Must NEVER Hardcode: - AWS Keys: Start with `AKIA`, `AGPA`, `AIDA`, `AROA`, `AIPA`, `ANPA`, `ANVA`, `ASIA` - Stripe Keys: Start with `sk_live_`, `pk_live_`, `sk_test_`, `pk_test_` - Google API: Start with `AIza` followed by 35 characters - GitHub Tokens: Start with `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` - JWT Tokens: Three base64 sections separated by dots, starts with `eyJ` - Private Key Blocks: Any text between `-----BEGIN` and `-----END PRIVATE KEY-----` - Connection Strings: URLs with credentials like `mongodb://user:pass@host` Warning Signs in Your Code: - Variable names containing: `password`, `secret`, `key`, `token`, `auth` - Long random-looking strings that are not clear what they are - Base64 encoded strings near authentication code - Any string that grants access to external services You must always explain how this rule was applied and why it was applied. ================================================ FILE: sources/core/codeguard-SKILLS.md.template ================================================ --- name: software-security description: A software security skill that integrates with Project CodeGuard to help AI coding agents write secure code and prevent common vulnerabilities. Use this skill when writing, reviewing, or modifying code to ensure secure-by-default practices are followed. codeguard-version: "x.x.x" framework: "Project CodeGuard" purpose: "Embed secure-by-default practices into AI coding workflows" --- # Software Security Skill (Project CodeGuard) This skill provides comprehensive security guidance to help AI coding agents generate secure code and prevent common vulnerabilities. It is based on **Project CodeGuard**, an open-source, model-agnostic security framework that embeds secure-by-default practices into AI coding workflows. ## When to Use This Skill This skill should be activated when: - Writing new code in any language - Reviewing or modifying existing code - Implementing security-sensitive features (authentication, cryptography, data handling, etc.) - Working with user input, databases, APIs, or external services - Configuring cloud infrastructure, CI/CD pipelines, or containers - Handling sensitive data, credentials, or cryptographic operations ## How to Use This Skill When writing or reviewing code: 1. Always-Apply Rules: Some rules MUST be checked on every code operation: - `codeguard-1-hardcoded-credentials.md` - Never hardcode secrets, passwords, API keys, or tokens - `codeguard-1-crypto-algorithms.md` - Use only modern, secure cryptographic algorithms - `codeguard-1-digital-certificates.md` - Validate and manage digital certificates securely 2. Context-Specific Rules: Apply rules from /rules directory based on the language of the feature being implemented using the table given below: 3. Proactive Security: Don't just avoid vulnerabilities-actively implement secure patterns: - Use parameterized queries for database access - Validate and sanitize all user input - Apply least-privilege principles - Use modern cryptographic algorithms and libraries - Implement defense-in-depth strategies ## CodeGuard Security Rules The security rules are available in the `rules/` directory. ### Usage Workflow When generating or reviewing code, follow this workflow: ### 1. Initial Security Check Before writing any code: - Check: Will this handle credentials? → Apply codeguard-1-hardcoded-credentials - Check: What language am I using? → Identify applicable language-specific rules - Check: What security domains are involved? → Load relevant rule files ### 2. Code Generation While writing code: - Apply secure-by-default patterns from relevant Project CodeGuard rules - Add security-relevant comments explaining choices ### 3. Security Review After writing code: - Review against implementation checklists in each rule - Verify no hardcoded credentials or secrets - Validate that all the rules have been successfully followed when applicable. - Explain which security rules were applied - Highlight security features implemented ================================================ FILE: sources/owasp/codeguard-0-ajax-security.md ================================================ --- description: AJAX Security Best Practices for Client-Side Scripts languages: - c - html - javascript - php - typescript alwaysApply: false --- It is crucial to follow AJAX security best practices to prevent common web vulnerabilities. Here are some guidelines to keep in mind: ### 1. Avoid Dangerous JavaScript Functions Dynamically evaluating code with functions like `eval()`, `new Function()`, `setTimeout()`, and `setInterval()` with dynamic, unvalidated string arguments is a significant security risk. User input or untrusted data can lead to code injection vulnerabilities. Best Practice: Instead of using these functions with dynamic strings, use safer alternatives. For example, use anonymous functions for `setTimeout` and `setInterval`. Example of what to avoid: ```javascript // Unsafe: susceptible to injection setTimeout("alert('hello')", 1000); // Safe: setTimeout(() => alert('hello'), 1000); ``` ### 2. Prevent Cross-Site Scripting (XSS) with `innerHTML` Using `.innerHTML` to insert content into your web page can lead to XSS if the content is not properly sanitized. Best Practice: Use `.innerText` or `.textContent` when you only need to insert text. If you must insert HTML, use context-aware sanitization libraries before using `.innerHTML`. Example: ```javascript // Unsafe: document.getElementById("div1").innerHTML = untrusted_user_input; // Safe for text content: document.getElementById("div1").textContent = untrusted_user_input; ``` ### 3. Secure Client-Side Encryption and Secret Handling Never perform encryption or handle secrets on the client side. Client-side code is visible and can be manipulated by attackers. Best Practice: All sensitive operations, including encryption and secret management, must be performed on the server. ### 4. Safe JSON and XML Creation Building JSON or XML using string concatenation is error-prone and can lead to injection vulnerabilities. Best Practice: Use built-in browser APIs like `JSON.stringify()` or trusted third-party libraries to serialize data. Example: ```javascript // Unsafe: let jsonString = '{"name":"' + name + '","email":"' + email + '"}'; // Safe: let jsonString = JSON.stringify({ name: name, email: email }); ``` ### 5. Server-Side Enforcement of Security and Business Logic Client-side validation is for user experience, not security. An attacker can easily bypass it. Best Practice: Always enforce all security checks and business logic on the server. The server should never trust any data coming from the client. ### Additional Recommendations: * Input Validation: Rigorously validate all inputs on the server, as AJAX services can be called directly by attackers. * CSRF Protection: Use anti-CSRF tokens for any state-changing AJAX requests. Store authentication tokens securely with HttpOnly and Secure flags for cookies. * JSON Hijacking: Return JSON responses with an object as the outermost element to prevent JSON hijacking in older browsers. * Schema Validation: Use JSON or XML schemas to validate the structure and types of data in AJAX requests and responses. * OWASP Resources: The [OWASP Java Encoder Project](https://owasp.org/www-project-java-encoder/) is an excellent resource for server-side encoding. ================================================ FILE: sources/owasp/codeguard-0-attack-surface-analysis.md ================================================ --- description: Attack Surface Analysis Best Practices languages: - c - go - java - javascript - matlab - php - python - ruby - typescript - yaml alwaysApply: false --- Understanding and managing your application's attack surface is a fundamental part of building secure software. Your application's attack surface is the sum of all points where an unauthorized user (an attacker) can try to enter data, extract data, or invoke execution. Here’s how to approach it: ### 1. Identify and Document Your Attack Surface You can't protect what you don't know about. The first step is to map out all the entry and exit points of your application. **Best Practices:** * **Catalog Entry Points:** Identify all user interfaces (UIs), APIs (REST, GraphQL, etc.), file uploads, database connections, message queue consumers, and webhooks. Examples include `/api/users`, file upload endpoints, database connection strings, and Redis/RabbitMQ consumers. * **Map Data Flows:** Document how data enters, is processed, and exits your system. This includes data formats being used (e.g., JSON, XML, serialized objects). * **Integrate with CI/CD:** Add automated checks in your CI/CD pipeline to detect new endpoints or changes to existing ones. Use tools like OpenAPI spec validation or endpoint discovery to flag changes for security review. * **Keep Documentation Current:** Maintain a living document, such as a `ATTACK_SURFACE.md` file in your repository, that details these components. Assign responsibility for updates to the development team lead and review quarterly. ### 2. Analyze and Prioritize Once you have a map, you need to assess the risk associated with each part of the attack surface. **Best Practices:** * **Categorize Components:** Classify each entry point based on its exposure (e.g., public-facing vs. internal) and the sensitivity of the data it handles. * **Secure APIs and Integrations:** For each API endpoint, ensure proper input validation, rate limiting (e.g., 100 requests/minute per user), authentication (OAuth2, JWT), and authorization checks. Regularly review third-party integration credentials and permissions. * **Handle Authentication and Authorization:** Implement proper access controls for all endpoints. Document which user roles can access which resources. Regularly audit deprecated endpoints and remove or secure them properly. * **Prioritize Reviews:** Focus your security efforts, such as code reviews and penetration testing, on the most exposed and highest-risk components. An unauthenticated public API handling user data is a higher priority than an internal admin dashboard. * **Threat Model:** Use threat modeling to think like an attacker and identify potential vulnerabilities in your design. ### 3. Reduce and Monitor A smaller attack surface is easier to defend. **Best Practices:** * **Principle of Least Privilege:** If a feature, endpoint, or dependency is not needed, remove it. Disable unused features and interfaces. * **Minimize Dependencies:** Every third-party library you add can potentially increase your attack surface. Regularly audit and remove unused dependencies. * **Continuously Reassess:** Your application is always evolving. Make attack surface analysis a regular part of your development lifecycle, not a one-time activity. ### 4. Implement Runtime Defenses Secure coding is essential, but it should be part of a defense-in-depth strategy with operational controls. **Best Practices:** * **Deploy Web Application Firewalls (WAFs):** Configure WAF rules to block common attack patterns (SQL injection, XSS) and implement custom rules for your application's specific attack vectors. * **Implement Rate Limiting:** Set up application-level rate limiting for critical endpoints (e.g., login, API calls) and infrastructure-level DDoS protection. * **Enable Anomaly Detection:** Monitor for unusual traffic patterns, failed authentication attempts, and unexpected data access patterns. Set up alerts for suspicious activity. * **Network Segmentation:** Use firewalls and network controls to limit communication between components. These are often defined in Infrastructure-as-Code (IaC) files (e.g., Terraform, CloudFormation), which should be reviewed for security. * **Regular Security Monitoring:** Implement logging and monitoring for all entry points, with weekly reviews of security logs and monthly assessments of attack surface changes. ================================================ FILE: sources/owasp/codeguard-0-authentication.md ================================================ --- description: Authentication Security Best Practices languages: - c - go - java - javascript - php - python - ruby - typescript alwaysApply: false --- Secure authentication is one of the most critical aspects of application development. - Use non-public, random, and unique identifiers for users internally. For login, allow users to use their verified email address or a username, but ensure error messages are generic (e.g., "Invalid username or password") to prevent attackers from guessing valid accounts. - Implement proper password strength controls: minimum 8 characters, maximum 64+ characters to support passphrases, allow all characters including unicode and whitespace, and avoid composition rules (no requirements for uppercase/lowercase/numbers/special characters). - Block common and previously breached passwords using services like HaveIBeenPwned's Pwned Passwords API, and include a password strength meter to help users create stronger passwords. - Store user passwords using a modern, strong, and slow hashing algorithm like Argon2 (preferred) or bcrypt with recommended parameters. Use a unique salt for each user. - Support Password Managers: Use standard `` fields and allow pasting to ensure compatibility with password managers. - Use TLS Everywhere: All communication transmitting credentials, session tokens, or any sensitive data must be over HTTPS. - When comparing password hashes, use a secure, constant-time comparison function to prevent timing attacks. - Protect against automated attacks: implement account lockout after failed login attempts, use CAPTCHA to prevent brute force attacks, and consider rate limiting on authentication endpoints. - Require multi-factor authentication (MFA) using TOTP (authenticator apps) or WebAuthn (hardware keys) for sensitive accounts. Consider making MFA mandatory for all users. - Implement secure session management: use HttpOnly and Secure flags for session cookies, rotate session IDs after login, and set appropriate session timeouts. - Before a user can change their password, require them to re-enter their current password. Require re-authentication for all sensitive features and transactions (password changes, email updates, financial transactions). - Implement secure password recovery mechanisms that don't reveal whether an account exists ("If that email address is in our database, we will send you an email to reset your password"). - Enable comprehensive logging and monitoring: log all authentication failures, successful logins, account lockouts, and password changes for security monitoring and incident response. - Internal or administrative accounts should not be accessible from public login forms. Use a separate, more secure authentication system for internal users. - For delegated or federated authentication, use established protocols like OAuth 2.0, OpenID Connect (OIDC), or SAML. DO NOT build your own. ================================================ FILE: sources/owasp/codeguard-0-authorization-testing-automation.md ================================================ --- description: Authorization Testing Automation Best Practices languages: - go - java - javascript - python - ruby - typescript - xml - yaml alwaysApply: false --- Enforce Automated Authorization Testing Using a Formal Authorization Matrix Automate authorization tests driven by a formal authorization matrix to detect regressions early and ensure reliable access control enforcement. 1. **Define a formal authorization matrix file** (preferably XML or YAML) that lists: - All features/services/endpoints. - Logical roles and data filters if applicable. - Expected HTTP response codes for allowed and denied accesses. - Optional test payloads per service for richer testing. 2. **Secure the authorization matrix**: Store matrix files encrypted at rest with appropriate access controls. Version control the matrix and restrict write access to authorized personnel only. 3. **Automate integration tests** to: - Dynamically load and iterate over the matrix entries. - Generate role-based access tokens (e.g., JWT) matching each logical role. - Handle token lifecycle: refresh, expiration, and revocation scenarios. - Call each service endpoint as each role. - Validate actual HTTP response codes against expected allowed/denied codes from the matrix. - Report any discrepancies immediately, specifying involved role, service, and unexpected response. 4. **Environment-specific configuration**: Support different authorization matrices and token configurations for development, testing, and production environments. 5. **Secure the test environment**: Isolate test environments, use dedicated test accounts, and ensure test tokens cannot access production resources. 6. Factorize test logic to centralize token creation, service calls, and response validation while isolating role-based POVs for clear error profiling. 7. Maintain the authorization matrix as a living document alongside code; update it whenever authorization changes occur. 8. Provide a readable, auditable view of the authorization matrix (HTML via XSLT or similar) accessible to developers and auditors for verification. ================================================ FILE: sources/owasp/codeguard-0-authorization.md ================================================ --- description: Authorization Security Best Practices languages: - c - go - java - javascript - php - python - ruby - typescript - yaml alwaysApply: false --- Implementing robust authorization is critical to ensure users can only access the data and features they are permitted to. While authentication confirms who a user is, authorization determines what they can do. ### Core Principles of Secure Authorization 1. **Deny by Default:** The default for any access request should be 'deny'. Explicitly grant permissions to roles or users rather than explicitly denying them. When no allow rule matches, return HTTP 403 Forbidden. 2. **Principle of Least Privilege:** Grant users the minimum level of access required to perform their job functions. Regularly audit permissions to ensure they are not excessive. 3. **Validate Permissions on Every Request:** Check authorization for every single request, regardless of source (AJAX, API, direct). Use middleware/filters to ensure consistent enforcement. 4. **Prefer ABAC/ReBAC over RBAC:** Use Attribute-Based Access Control (ABAC) or Relationship-Based Access Control (ReBAC) for fine-grained permissions instead of simple role-based access control. ### Server-Side Enforcement is Non-Negotiable All authorization decisions must be enforced on the server-side for every request. Client-side checks are for user experience only and can be easily bypassed. **What to Avoid (Anti-Pattern):** ```javascript // Insecure: Client-side check that can be bypassed by an attacker. if (currentUser.isAdmin) { showAdminDashboard(); } // The server must also check if the user is an admin before returning data. ``` **Best Practice:** Use centralized middleware or decorators in your backend framework to enforce authorization checks consistently across all relevant endpoints. **Example (Express.js middleware showing deny-by-default):** ```javascript function canViewProject(req, res, next) { const project = await db.getProject(req.params.id); // Explicit allow conditions if (project.ownerId === req.user.id) { return next(); // Owner can view } if (req.user.isAdmin) { return next(); // Admin can view } if (project.isPublic && req.user.isVerified) { return next(); // Verified users can view public projects } // Deny by default - no allow rule matched return res.status(403).json({ error: 'Access denied', message: 'You do not have permission to view this resource' }); } app.get('/projects/:id', isAuthenticated, canViewProject, (req, res) => { // return project data }); ``` ### Prevent Insecure Direct Object References (IDOR) An IDOR vulnerability occurs when an application uses a user-supplied identifier (like a database ID) to access an object directly, without verifying the user has permission to access *that specific object*. **What to Avoid (Anti-Pattern):** ```javascript // Insecure: The code checks if the user is authenticated, but not if they // are authorized to view the invoice with the given ID. app.get('/invoices/:id', isAuthenticated, (req, res) => { const invoice = await db.getInvoice(req.params.id); // Attacker can cycle through IDs res.json(invoice); }); ``` **Best Practice:** Always verify that the authenticated user has the necessary permissions for the specific object they are requesting. ### Additional Best Practices * **Token Lifecycle Management:** Implement token revocation for logout/role changes and session invalidation when permissions change. * **Centralized Error Handling:** Return generic error messages (403 Forbidden or 404 Not Found) when authorization fails to avoid information leakage. * **Comprehensive Logging:** Log all authorization failures with user ID, resource, action, and timestamp for security monitoring. * **Testing:** Write unit and integration tests for authorization logic. Test both positive (should have access) and negative (should be denied) cases. * **Static Resources:** Apply authorization checks to static files, cloud storage, and other resources, not just API endpoints. ================================================ FILE: sources/owasp/codeguard-0-bean-validation.md ================================================ --- description: Bean Validation Security Best Practices languages: - java - xml alwaysApply: false --- Using a declarative, centralized approach to validation is crucial for security and maintainability. The Java Bean Validation standard (now Jakarta Validation) and its primary implementation, Hibernate Validator, provide a powerful way to handle this. ### Why Use Bean Validation? Instead of scattering validation logic throughout your business layer, you define validation rules directly on your domain models (your "beans"). This keeps your validation logic in one place, making it consistent and easy to manage. ### 1. Setting Up Your Project Add Hibernate Validator to your `pom.xml`: ```xml org.hibernate.validator hibernate-validator 8.0.0.Final ``` If you're using Spring Boot, the `spring-boot-starter-web` dependency includes Hibernate Validator automatically. ### 2. Annotating Your Beans Apply standard validation annotations directly to the fields of your model classes. **Always combine @NotNull/@NotBlank with @Size constraints for sensitive fields.** **Example (`UserForm.java`):** ```java public class UserForm { @NotBlank @Size(min = 2, max = 50) private String name; @NotBlank @Email @Size(max = 254) private String email; @NotBlank @Size(min = 8, max = 128) @Pattern(regexp = "[A-Za-z0-9@#$%^&+=]+") private String password; // ... getters and setters } ``` ### 3. Triggering Validation In a web context (like a Spring MVC controller), use the `@Valid` annotation on your model attribute to trigger the validation process automatically. **Example (Spring Controller):** ```java @RestController public class UserController { @PostMapping("/register") public ResponseEntity register(@Valid @RequestBody UserForm form, BindingResult result) { if (result.hasErrors()) { logger.warn("Validation failed: {}", result.getFieldErrors()); return ResponseEntity.badRequest().body(result.getFieldErrors()); } userService.create(form); return ResponseEntity.ok("Success"); } } ``` ### 4. Validating Nested Objects If your model contains other objects that also need validation, just annotate them with `@Valid`. **Example:** ```java public class Order { @Valid @NotNull private Address shippingAddress; } ``` ### Best Practices Summary * **Centralize Rules:** Define validation constraints on your domain models. * **Use Standard Annotations:** Leverage the rich set of built-in annotations (`@NotNull`, `@Size`, `@Pattern`, `@Min`, `@Max`, `@Email`, etc.). * **Automate with `@Valid`:** Let your framework trigger validation automatically in your controllers. * **Handle Errors Gracefully:** Use `BindingResult` to capture validation errors and return a meaningful `400 Bad Request` response. Never expose sensitive system information in error messages. * **Create Custom Constraints:** For complex business rules that aren't covered by standard annotations, create your own custom validation constraints. ================================================ FILE: sources/owasp/codeguard-0-browser-extension-vulnerabilities.md ================================================ --- description: Browser Extension Security Best Practices languages: - c - javascript - typescript alwaysApply: false --- A browser extension can access sensitive user data and modify web page content, making security a top priority. Here are the key areas to focus on when developing extensions. ### 1. The Manifest: Your Security Foundation Your `manifest.json` file is the heart of your extension's security model. Configure it with the principle of least privilege. * **Permissions:** Only request the permissions your extension absolutely needs to function. Avoid broad host permissions like `` or `http://*/*`. If you only need to access a few sites, specify them explicitly. * **Content Security Policy (CSP):** Define a strict CSP to mitigate XSS and other injection attacks. A good starting point is: ```json "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self'" } ``` This policy disallows inline scripts and `eval()`, and restricts script and object sources to your extension's own package. ### 2. Secure Coding Practices * **Avoid Dynamic Code Execution:** Never use `eval()`, `new Function()`, `setTimeout()` with strings, or dynamic `import()` of remote URLs. These are major security risks. * **Sanitize DOM Inputs:** To prevent XSS from content scripts, never use `.innerHTML` with data that isn't fully sanitized. Prefer safer APIs like `.textContent`, or use a trusted library like DOMPurify. **Example:** ```javascript // Insecure: document.getElementById('user-greeting').innerHTML = `Welcome, ${userInput}!`; // Secure: document.getElementById('user-greeting').textContent = `Welcome, ${userInput}!`; ``` ### 3. Data Storage and Communication * **Use `chrome.storage`:** Avoid `localStorage` for storing any sensitive information. `localStorage` is accessible by any script on the same origin, including potentially malicious scripts injected into the page. Use the `chrome.storage` API instead, which is isolated to your extension. * **Encrypt Sensitive Data:** Before storing any sensitive user data, encrypt it. * **Use HTTPS:** All network communication must use HTTPS (`wss://` for WebSockets) to protect data in transit. Monitor network requests to prevent unauthorized data exfiltration. ### 4. Interacting with Web Pages * **Isolate Sensitive UI:** Do not inject sensitive information directly into a web page's DOM. A malicious script on the page could scrape this data. Instead, display sensitive information in extension-owned UI elements like popups, sidebars, or options pages. * **Use Message Passing:** Use the standard message passing APIs (`chrome.runtime.sendMessage`, `chrome.tabs.sendMessage`) for communication between your content scripts and background scripts. Do not use the DOM as a communication channel. ### 5. Supply Chain Security * **Audit Dependencies:** Regularly audit your third-party libraries using tools like `npm audit`. A malicious or vulnerable dependency can compromise your entire extension. * **No Remote Code:** Do not fetch and execute remote code. All of your extension's logic should be included in its initial package. This is a requirement for most browser extension marketplaces. ================================================ FILE: sources/owasp/codeguard-0-c-based-toolchain-hardening.md ================================================ --- description: C/C++ Toolchain Hardening Best Practices languages: - c - matlab alwaysApply: false --- The security of your compiled application depends heavily on the options you pass to your C/C++ compiler and linker. Modern toolchains provide a powerful set of features to harden your binaries against common exploitation techniques. ### 1. Compiler Flags for Hardening These flags should be a standard part of your release build configuration. **Note**: Some flags have platform-specific support. * **Enable All Warnings:** Warnings often point to latent bugs. Start with a strong baseline. * **GCC/Clang:** `-Wall -Wextra -Wconversion` * **Stack Smashing Protection:** This adds a "canary" to the stack to detect buffer overflows before they can be exploited. * **GCC/Clang:** `-fstack-protector-all` * **Position-Independent Executables (PIE):** This allows the operating system to load the application at a random memory address (ASLR), making it much harder for attackers to predict memory layouts. * **Compiler:** `-fPIE` (Linux/Windows), `-fpie` (macOS) * **Linker:** `-pie` * **Fortify Source:** This adds checks to common library functions (like `strcpy`, `printf`) to prevent buffer overflows. * **GCC/Clang:** `-D_FORTIFY_SOURCE=2` (Note: requires optimization `-O1` or higher). * **Control Flow Integrity (CFI):** Guards against ROP/JOP attacks (Clang 3.5+). * **Clang:** `-fsanitize=cfi` (requires `-flto`) ### 2. Linker Flags for Hardening These flags control how your final executable is constructed. * **Relocation Read-Only (RELRO):** This makes parts of the binary read-only after the dynamic linker has done its work, preventing certain exploitation techniques like GOT overwrites. * **GCC/Clang Linker:** `-Wl,-z,relro,-z,now` * **Non-Executable Stack (NX):** This prevents code from being executed from the stack, a hallmark of many exploits. * **GCC/Clang Linker:** `-Wl,-z,noexecstack` * **Additional Runtime Protections:** * **Linux:** `-Wl,-z,noexecheap` (prevent heap execution) * **Windows:** `/NXCOMPAT /DYNAMICBASE` (DEP and ASLR support) ### 3. Build Configurations: Debug vs. Release Maintain separate, distinct build configurations for development and production. * **Debug Builds:** * Disable optimizations (`-O0`) and enable full debugging information (`-g3`). * Define the `DEBUG` macro (`-DDEBUG`) and do **not** define `NDEBUG`. * Use sanitizers to detect memory errors at runtime (e.g., `-fsanitize=address,undefined,leak`). * **Linux only:** Create a separate build with `fsanitize=memory` added to the compiler and linker flags. Do **not** add other sanitizers to this build. * **Release Builds:** * Enable optimizations (e.g., `-O2`). * Define the `NDEBUG` macro (`-DNDEBUG`) to disable assertions and debugging code. Do **not** define `DEBUG`. * Include all the hardening flags mentioned above. ### 4. Using Assertions Effectively Assertions are a powerful tool for catching bugs early. * **Best Practice:** Use `assert()` liberally in your code to check for pre-conditions, post-conditions, and invariants. Assertions are automatically disabled in release builds (when `NDEBUG` is defined), so they have no performance impact on your production code. ```c void process_data(char *data, size_t len) { assert(data != NULL && "Data pointer cannot be null!"); // ... } ``` ### 5. CI/CD Integration Enforce security flags in your build pipeline: **CMakeLists.txt example:** ```cmake if(CMAKE_BUILD_TYPE STREQUAL "Release") target_compile_options(${PROJECT_NAME} PRIVATE -fstack-protector-all -fPIE -D_FORTIFY_SOURCE=2) target_link_options(${PROJECT_NAME} PRIVATE -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack) endif() ``` **Verification:** Add security checks to CI pipeline: ```bash # Linux: Verify hardening flags were applied checksec --file=./your_binary || exit 1 ``` ### 6. Verifying Your Binary Don't just trust that the flags worked. Use a tool to check the security properties of your final executable. * **Linux:** Use the `checksec` tool. * **Windows:** Use Microsoft's BinScope. * **Dependency Security:** Regularly audit third-party libraries with tools like `npm audit` or OWASP Dependency-Check. By integrating these toolchain hardening practices into your CI/CD pipeline, you can significantly raise the bar for attackers and build more resilient and secure C/C++ applications. ================================================ FILE: sources/owasp/codeguard-0-choosing-and-using-security-questions.md ================================================ --- description: Security Questions Implementation Guidelines languages: - c - go - java - javascript - php - python - ruby - typescript alwaysApply: false --- Security questions are no longer considered a strong authentication factor in authentication systems. Modern best practices strongly recommend against using them as a standalone method for authentication or account recovery. ### Preferred Alternatives to Security Questions * **Multi-Factor Authentication (MFA):** Implement time-based one-time passwords (TOTP), push notifications, or hardware security keys as your primary account recovery mechanism. * **One-Time Recovery Codes:** Generate and provide users with a set of single-use recovery codes when they set up their account. * **Email-Based Recovery:** Send a time-limited, single-use recovery link to a verified email address. ### If You Must Use Security Questions (Legacy Systems) If your organization requires security questions for legacy or compliance reasons, implement these critical safeguards: #### 1. Question Selection * **Provide a Curated List:** Offer a predefined set of strong questions rather than allowing free-form user-created ones. * **Question Quality:** Choose questions that are: * **Memorable:** Users can consistently recall the answer over time. * **Stable:** The answer doesn't change over the user's lifetime. * **Confidential:** Not easily discoverable through social media or public records. * **Specific:** Has a single, precise answer rather than multiple possible answers. #### 2. Answer Handling * **Secure Storage:** Hash all answers using Argon2id or bcrypt with per-answer unique salt and system-wide pepper. Store data encrypted at rest with AES-256. * **Normalization:** Before comparing answers, normalize them by removing extra spaces, converting to lowercase, and removing punctuation. * **Input Validation:** * Enforce a minimum length but allow legitimate short answers. * Implement a denylist for weak answers like "password", "123456", or the user's own username/email. #### 3. Implementation Best Practices * **Multi-Layered Security:** Use multiple questions together for increased security. * **Consistent Question:** When a user fails to answer correctly, don't rotate to a different question—this helps prevent attackers from learning all the answers through multiple attempts. * **Brute-Force Protection:** Implement rate limiting (max 5 attempts per hour), progressive delays, CAPTCHA after 3 failed attempts, and account lockout to prevent automated attacks. * **Verify Email First:** Always verify ownership of the recovery email address before presenting security questions. * **Require Authentication:** Require re-authentication (password or MFA) before allowing users to change their security questions or answers. * **Secure Transport:** Use HTTPS/TLS 1.3+ for all recovery endpoints and implement certificate pinning where possible to prevent man-in-the-middle attacks. By following these guidelines, you can minimize the risks associated with security questions while working toward implementing more secure authentication methods. ================================================ FILE: sources/owasp/codeguard-0-ci-cd-security.md ================================================ --- description: CI/CD Security Best Practices languages: - javascript - powershell - shell - xml - yaml alwaysApply: false --- The CI/CD pipeline is the backbone of a software development process. It's also a high-value target for attackers. Securing the pipeline is essential for protecting code, infrastructure, and users. ### 1. Secure Your Source Code The pipeline starts with your source code repository. * **Protected Branches:** Configure protected branches (e.g., `main`, `develop`) in your SCM (GitHub, GitLab, etc.). Require code reviews and passing status checks before any code can be merged. * **Commit Signing:** Enforce commit signing (e.g., with GPG keys) to verify the author of every commit and prevent spoofing. ### 2. Don't Hardcode Secrets Never, ever hardcode secrets (API keys, passwords, tokens) in your pipeline configuration files or source code. * **Best Practice:** Use a dedicated secrets management solution (like HashiCorp Vault, AWS Secrets Manager, or your CI platform's built-in secret store). Your pipeline should fetch secrets at runtime. Ensure that secrets are masked and never appear in logs. **Example (GitHub Actions):** steps: - name: Deploy to production run: ./deploy.sh env: API_KEY: ${{ secrets.PROD_API_KEY }} # Fetches from GitHub's encrypted secrets ``` ### 3. Harden Your Pipeline Configuration * **Least Privilege:** Grant the minimum level of permissions necessary to your pipeline's identities and build agents. If a job only needs to build code, it shouldn't have deployment credentials. * **Isolated Build Environments:** Use ephemeral, isolated build environments (containers or VMs) that are destroyed after each job to prevent cross-contamination and lateral movement. * **Automated Security Scanning:** Integrate security scanning directly into your pipeline. This creates a security gate that prevents vulnerabilities from moving down the line. * **SAST (Static Analysis):** Scans your source code for vulnerabilities. * **SCA (Software Composition Analysis):** Scans your dependencies for known vulnerabilities. * **DAST (Dynamic Analysis):** Scans your running application in a test environment. * **IaC Scanning:** Scans your Infrastructure-as-Code files (Terraform, CloudFormation) for misconfigurations. ### 4. Secure Your Dependencies Your software is only as secure as its dependencies. * **Pin Versions:** Use a lock file (`package-lock.json`, `yarn.lock`, `Gemfile.lock`) to pin your dependencies to specific, trusted versions. This prevents a malicious package from being automatically pulled in. * **Validate Integrity:** Use package manager features that validate package integrity using hashes or checksums. * **Use Private Registries:** For sensitive internal packages, use a private registry to avoid dependency confusion attacks. ### 5. Sign Everything To ensure the integrity of your supply chain, cryptographically sign your important assets. * **Best Practice:** * Sign your Git commits. * Sign your build artifacts (e.g., Docker images, JAR files). * **Verify signatures** before deployment: ensure all artifacts are signed by trusted keys and reject unsigned or invalidly signed artifacts. * Consider frameworks like **SLSA (Supply-chain Levels for Software Artifacts)** to create a verifiable chain of custody for your software. By embedding these practices into your daily workflow, you can build a CI/CD pipeline that is not only fast and efficient but also secure and resilient. ================================================ FILE: sources/owasp/codeguard-0-clickjacking-defense.md ================================================ --- description: Clickjacking Defense Best Practices languages: - c - html - javascript - php - typescript alwaysApply: false --- ## Protecting Your Web Application Against Clickjacking Clickjacking (UI redress attacks) can trick users into performing unintended actions by hiding or disguising interactive elements. These attacks embed your site in an invisible iframe, allowing attackers to capture clicks meant for their site and redirect them to your application. ### Defense Strategy: Multiple Layers of Protection #### 1. HTTP Headers: Your First Line of Defense **Content Security Policy (CSP)** is the modern, recommended approach that supersedes X-Frame-Options in modern browsers: ```http Content-Security-Policy: frame-ancestors 'none'; ``` This directive prevents any site from framing your content. If you need to allow specific sites to frame your content, use: ```http Content-Security-Policy: frame-ancestors 'self' https://trusted-site.com; ``` **Important:** CSP frame-ancestors takes precedence over X-Frame-Options when both are present. For older browsers that don't support CSP, implement the **X-Frame-Options** header as a fallback: ```http X-Frame-Options: DENY ``` or ```http X-Frame-Options: SAMEORIGIN ``` **Important:** Never use `X-Frame-Options: ALLOW-FROM` as it's obsolete and not supported by modern browsers. #### 2. Cookie Protection Protect your session cookies from being included in cross-origin requests: ```http Set-Cookie: sessionid=abc123; SameSite=Lax; Secure; HttpOnly ``` Options for the SameSite attribute: - `Strict`: Cookies are only sent in first-party context (most secure) - `Lax`: Cookies are sent when navigating to your site from another site (good balance) #### 3. JavaScript Frame-Buster For legacy browsers or as an additional layer, implement this defensive code in your page's `` section: ```html ``` This approach first hides the page content, then only reveals it if the page is not framed. If framed, it attempts to break out of the frame. **Note:** Frame-busters can be defeated by advanced attackers and should not be your only defense. #### 4. Special Cases: When Your Site Must Be Framed If your application legitimately needs to be framed (e.g., it's designed to be embedded): 1. Use CSP to whitelist only specific domains: ```http Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com; ``` 2. Implement additional confirmation for sensitive actions: ```javascript if (sensitiveAction && window !== window.top) { if (!window.confirm('Confirm this action?')) { return false; // Cancel the action if not confirmed } } ``` ### Implementation Best Practices 1. **Apply Globally:** Add these protections to all pages, not just sensitive ones. 2. **Automate Header Injection:** Configure your web server, CDN, or application framework to automatically inject headers rather than manually adding them to each page. 3. **Use CSP Report-Only for Testing:** Deploy `Content-Security-Policy-Report-Only: frame-ancestors 'none';` first to monitor violations before enforcing. 4. **Test Thoroughly:** Verify your defenses work across different browsers and with proxies. 5. **Defense in Depth:** Combine all three protection methods for maximum security. 6. **Monitor and Verify:** Use tools like the OWASP ZAP scanner to confirm your headers are properly set and monitor CSP reports for violations. By implementing these defenses, you significantly reduce the risk of clickjacking attacks against your web application. ================================================ FILE: sources/owasp/codeguard-0-content-security-policy.md ================================================ --- description: Content Security Policy (CSP) Best Practices languages: - c - html - javascript - php - typescript alwaysApply: false --- ## Content Security Policy (CSP): A Defense-in-Depth Strategy Implementing a strong Content Security Policy (CSP) is one of the most effective ways to mitigate cross-site scripting (XSS), clickjacking, and other injection attacks. CSP works by declaring which dynamic resources are allowed to load, effectively creating an allowlist that the browser enforces. ### Implementation #### 1. Deliver CSP via HTTP Headers The most effective way to implement CSP is through HTTP response headers: ```http Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; ``` When testing a new policy, use the report-only mode to monitor without blocking: ```http Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; ``` **Note:** Avoid using the meta tag approach (``) except when you cannot modify HTTP headers, as it provides less protection and doesn't support all directives. #### 2. Adopt a Strict CSP Strategy Modern CSP best practices favor nonce-based or hash-based approaches over domain whitelisting: **Nonce-based approach:** ```http Content-Security-Policy: script-src 'nonce-random123' 'strict-dynamic'; ``` With corresponding HTML: ```html ``` **Important:** Generate a unique, cryptographically strong nonce for each page load. The nonce should be at least 128 bits of entropy encoded in base64. **Server-side nonce generation examples:** ```javascript // Node.js: crypto.randomBytes(16).toString('base64') // Python: base64.b64encode(secrets.token_bytes(16)).decode('utf-8') ``` **Hash-based alternative:** ```http Content-Security-Policy: script-src 'sha256-hashOfYourScriptContent' 'strict-dynamic'; ``` #### 3. Baseline CSP for Getting Started ```http Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests; ``` This policy: - Restricts resources to the same origin - Allows inline styles (necessary for many applications initially) - Prevents clickjacking by controlling framing - Limits form submissions to the same origin - Blocks plugin content (Flash, Java applets) - Prevents base tag injection attacks - Automatically upgrades HTTP requests to HTTPS (when `upgrade-insecure-requests` is used) #### 4. Refactor Your Code for CSP Compatibility To make CSP implementation easier: 1. **Move inline code to external files:** ```html