Gemini CLI Security Extension

repository·main·Indexed 21 days ago

https://github.com/gemini-cli-extensions/security

An open-source tool for the Gemini CLI (v0.4.0+) that provides AI-powered code analysis and dependency scanning. It features the `/security:analyze` command for identifying vulnerabilities like SQL injection, XSS, and hardcoded secrets using a Two-Pass 'Recon & Investigate' workflow, and the `/security:scan-deps` command which integrates OSV-Scanner to cross-reference dependencies with the OSV.dev database. The extension can be integrated into CI/CD pipelines via the run-gemini-cli GitHub Action.

Tokens
7.2K
Snippets
16
Records
29
Agent score
74%

What's inside Gemini CLI Security Extension

  1. Compare Vulnerable vs Secure Path Construction

    main

    When handling file system access, avoid direct concatenation or simple joining of user input with a base directory. Use the 'Resolve + Prefix Check' pattern instead.

    Vulnerable Pattern (Do Not Use): Using path.join() with user input allows attackers to use ../ sequences to escape the intended directory.

    Secure Pattern:

    1. Resolve the safeRoot to an absolute path.
    2. Resolve the targetPath using the safeRoot and userInput.
    3. Use .startsWith() to ensure targetPath is contained within safeRoot (including the path separator).
    ### Vulnerable (Do Not Use)
    ```typescript
    // VULNERABLE: Direct concatenation allows inputs like "../../etc/passwd"
    const targetPath = path.join('/var/www/uploads', userInput);
    return fs.readFile(targetPath, 'utf-8');

    Secure

    // SECURE: Resolve + Prefix Check
    const safeRoot = path.resolve('/var/www/uploads');
    const targetPath = path.resolve(safeRoot, userInput);
    
    if (!targetPath.startsWith(safeRoot + path.sep)) {
      throw new Error('Path traversal detected');
    }
    return fs.readFile(targetPath, 'utf-8');
  2. Vulnerability types detected by the Security extension

    main

    The extension scans for several categories of security risks:

    Secrets Management

    • Hardcoded secrets: API keys, private keys, passwords, connection strings, and symmetric encryption keys.

    Insecure Data Handling

    • Weak cryptographic algorithms: Use of DES, Triple DES, RC4, or ECB mode.
    • Logging of sensitive information: Writing PII, passwords, or API keys to logs.
    • PII handling violations: Improper storage or transmission of personally identifiable information.
    • Insecure deserialization: Deserializing untrusted data without validation.

    Injection Vulnerabilities

    • Cross-site scripting (XSS): Unsanitized user input rendered in HTML.
    • SQL injection (SQLi): Unparameterized string concatenation in database queries.
    • Command injection: Executing system commands using unsanitized user input.
    • Server-side request forgery (SSRF): Unvalidated network requests to user-provided URLs.
    • Server-side template injection (SSTI): User input embedded directly into server-side templates.

    Authentication

    • Authentication bypass: Improper session validation or insecure 'remember me' logic.
    • Weak session tokens: Predictable or low-entropy tokens.
    • Insecure password reset: Predictable reset tokens or leakage in logs/URLs.

    LLM Safety

    • Insecure Prompt Handling (Prompt Injection): Risks from untrusted user data in prompts or embedding sensitive info in prompts.
    • Improper Output Handling: Unsafe use of LLM-generated content (e.g., passing it to eval() or using it for XSS/SQLi).
    • Insecure Plugin and Tool Usage: Overly permissive tools or unsafe data flows during LLM tool interaction.
  3. Integrate Security Analysis into GitHub Workflows

    main

    You can automate security analysis in your CI/CD pipeline using GitHub Actions.

    If you already use run-gemini-cli workflows:

    Replace your existing gemini-review.yml with the updated workflow provided by the extension to include the Security Analysis step.

    If you do NOT use [run-gemini-cli] workflows yet:

    1. Follow the Quick Start for run-gemini-cli.
    2. Create a .github/workflows directory in your repository root.
    3. Copy the Example Workflow into that directory.
    4. Commit and push the workflow file.
    5. Open a new pull request or comment @gemini-cli /review on an existing PR to trigger both Code Review and Security Analysis.
  4. Remediate Path Traversal vulnerabilities in Node.js

    main

    Path traversal occurs when user input is used to construct file paths without validation, allowing access to arbitrary files (e.g., /etc/passwd). To prevent this, follow a three-step remediation strategy:

    1. Resolve the Path: Use path.resolve() to create an absolute path combining a predefined safe root directory and the user input.
    2. Validate the Path: Verify that the resulting absolute path starts with the safe root directory string.
    3. Reject Invalid Paths: If the path is outside the safe root, throw an error or reject the request immediately.

    Note: When performing the prefix check, append path.sep to the safe root to ensure you are matching a directory boundary and not just a partial directory name.

    import path from 'path';
    import fs from 'fs/promises';
    
    async function safeReadFile(userInput: string) {
      const SAFE_ROOT = path.resolve('/var/www/uploads');
      const targetPath = path.resolve(SAFE_ROOT, userInput);
    
      // Critical: Check if the resolved path starts with the safe root
      if (!targetPath.startsWith(SAFE_ROOT + path.sep)) {
        throw new Error('Access denied: Invalid file path.');
      }
    
      return fs.readFile(targetPath, 'utf-8');
    }
  5. Configure the security analysis scope and limits

    main

    When running a full security analysis, the tool follows specific operational constraints regarding repository size:

    • File Discovery: The tool uses get_files_to_audit to determine the scope.
    • Line Count Limit: The tool calculates the total lines of code using get_line_count.
    • Threshold: If the total line count exceeds 20,000 lines, the analysis will pause and MUST ask the user for confirmation to proceed. If the user denies, the analysis stops immediately.

    This ensures that large-scale scans are intentional and do not consume excessive resources without consent.

  6. How the Two-Pass 'Recon & Investigate' model works

    main

    The security analysis uses a specific mental model to prevent missing vulnerabilities while maintaining speed. This is known as the Two-Pass Investigation Model.

    1. The Reconnaissance Pass (SAST Recon)

    In this phase, the analyst scans a file to identify Sources (where untrusted data enters, e.g., req.query.id) and Sinks (where data is used, e.g., db.run()).

    • Goal: Identify all potential starting points.
    • Action: Instead of tracing immediately, the tool creates a task in SECURITY_ANALYSIS_TODO.md to investigate that specific variable later.

    2. The Investigation Pass

    Once the scan is complete, the tool moves to the tasks created during Recon.

    • Goal: Perform deep-dive data-flow tracing.
    • Action: Trace the variable through function calls, reassignments, and object properties to see if it reaches a Sink without being sanitized, validated, or escaped.

    Key Concepts

    • Source: An entry point for untrusted or sensitive input.
    • Sink: A location where data is executed, rendered, or stored.
    • Taint Analysis: The process of tracing untrusted data from a Source to a Sink.
  7. Format for Location strings

    main

    The parser uses parseLocation to convert string-based file paths and line numbers into structured Location objects.

    Supported string formats include:

    • File with range: path/to/file.ext:startLine-endLine (e.g., app.js:10-20)
    • File with single line: path/to/file.ext:lineNumber (e.g., db.js:50)
    • File only: path/to/file.ext (e.g., config.json)

    Note: Backticks (`) in the location string are automatically stripped.

  8. Analyze GitHub Pull Requests for security vulnerabilities

    main

    The analyze-github-pr command is designed exclusively for use with the run-gemini-cli GitHub Action. It performs a security and privacy audit of code changes within a GitHub Pull Request, looking for common vulnerabilities (like SQLi, XSS, and Command Injection) and privacy violations (like PII leaks).

    Operational Workflow

    The analysis follows a strict Two-Pass "Recon & Investigate" Workflow to ensure high coverage and minimize false positives:

    1. Reconnaissance Pass (SAST Recon): A fast scan of the entire file to identify Sources (entry points for untrusted or sensitive data). When a source is found, the tool flags it for later investigation.
    2. Investigation Pass: A deep-dive trace of the identified source to see if it reaches a Sink (an execution, rendering, or storage point) without proper sanitization or validation.

    Integration Requirements

    • Environment: Must run within a secure GitHub Actions environment.
    • Required Action: run-gemini-cli GitHub Action.
    • Output: Results are reported back to the GitHub Pull Request as a pending review containing inline comments, code suggestions, and a summary report.
    # This command is a configuration for the run-gemini-cli GitHub Action.
    # It is not a standalone CLI command you run manually in a terminal,
    # but rather a definition for the automated security audit process.
  9. Run a full repository security analysis

    main

    The /security:analyze command (defined by the analyze-full.toml configuration) performs a comprehensive security and privacy audit of an entire repository. It uses a specialized Two-Pass "Recon & Investigate" Workflow to identify vulnerabilities like SQL injection, XSS, and command injection by tracing data from Sources (untrusted input) to Sinks (execution/storage points).

    How the analysis works:

    1. Scope Definition: The tool identifies files to audit and calculates the total line count. If the repository exceeds 20,000 lines, it will prompt for user confirmation before proceeding.
    2. Reconnaissance Pass: The tool performs a high-speed scan of each file to flag potential Sources of untrusted data. It creates sub-tasks in a .gemini_security/SECURITY_ANALYSIS_TODO.md file for every suspicious entry point found.
    3. Investigation Pass: The tool performs a deep-dive trace for each flagged source, following the data through function calls and assignments to see if it reaches a Sink without proper sanitization.
    4. Reporting: Findings are compiled into a DRAFT_SECURITY_REPORT.md and then refined into a final report.

    Output and Artifacts:

    • .gemini_security/: A temporary directory created during analysis.
    • security_report.json: If requested via the --json flag or natural language, a machine-readable version of the report is saved here.
    • Final Report: The cleaned, reviewed findings are output directly to the user.
    • Cleanup: Temporary files (SECURITY_ANALYSIS_TODO.md and DRAFT_SECURITY_REPORT.md) are removed after completion, but security_report.json is preserved if generated.
    # Example of requesting a JSON report during analysis
    gemini-cli /security:analyze --json
  10. Customize the /security:analyze command scope and format

    main

    You can customize the /security:analyze command using natural language instructions or flags:

    Customize Scope

    Provide instructions to include or exclude specific files or folders.

    /security:analyze Analyze all the source code under the script folder. Skip the docs, config files and package files.

    Request JSON Output

    You can obtain the security report in JSON format using the --json flag or by requesting it via natural language.

    /security:analyze --json
    # OR
    /security:analyze Return the report in JSON format.
    /security:analyze --json
  11. Scan for vulnerable dependencies with /security:scan-deps

    main

    The /security:scan-deps command automates dependency scanning by integrating OSV-Scanner. It cross-references your project's dependencies with the OSV.dev vulnerability database.

    The resulting report includes:

    • Vulnerable dependencies.
    • Specific vulnerability details (severity and identifiers).
    • Remediation guidance (e.g., which version to upgrade to).
    /security:scan-deps