### Install Pre-release Version with Gemini CLI Source: https://github.com/gemini-cli-extensions/security/blob/main/docs/releases.md Use this command to install a pre-release version of the extension for testing purposes. Ensure you are on the draft release page on GitHub to get the correct URL. ```bash gemini extensions install https://github.com/gemini-cli-extensions/security --pre-release ``` -------------------------------- ### Install Gemini CLI Security Extension Source: https://context7.com/gemini-cli-extensions/security/llms.txt Install the extension using the Gemini CLI. Use the --pre-release flag for testing. ```bash gemini extensions install https://github.com/gemini-cli-extensions/security # Install a pre-release version for testing gemini extensions install https://github.com/gemini-cli-extensions/security --pre-release ``` -------------------------------- ### Install Gemini CLI Security Extension Source: https://github.com/gemini-cli-extensions/security/blob/main/README.md Install the Security extension using this command. Requires Gemini CLI v0.4.0 or newer. ```bash gemini extensions install https://github.com/gemini-cli-extensions/security ``` -------------------------------- ### Install PoC dependencies with `install_dependencies` Source: https://context7.com/gemini-cli-extensions/security/llms.txt Executes a dependency installation script for a PoC file, automatically locating the nearest package manager file (`package.json`, `requirements.txt`, `go.mod`) and running the script in that context. ```typescript const result = await mcpClient.callTool('install_dependencies', { scriptPath: '/project/.gemini_security/poc/install_deps_poc_sqli.sh', targetFile: '/project/.gemini_security/poc/poc_other_1748923000000.ts', // cwd is optional; auto-detected from targetFile's nearest package root }); // Success: { content: [{ text: '{"stdout":"...","stderr":""}' }] } // Error: { isError: true, content: [{ text: '{"error":"...","stdout":"","stderr":""}' }] } ``` -------------------------------- ### Identify Hardcoded Secrets in JavaScript Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This example demonstrates patterns to look for when identifying hardcoded API keys and credentials in JavaScript code. Ensure secrets are not committed directly into source code. ```javascript const apiKey = "sk_live_123abc456def789ghi"; const client = new S3Client({ credentials: { accessKeyId: "AKIAIOSFODNN7EXAMPLE", secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", }, }); ``` -------------------------------- ### Secure File Reading in Node.js Source: https://github.com/gemini-cli-extensions/security/blob/main/mcp-server/src/knowledge/path_traversal.md Use path.resolve() to create an absolute path and then validate that it starts with the safe root directory before accessing the file. This prevents attackers from accessing files outside the intended directory. ```typescript 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'); } ``` -------------------------------- ### `find_line_numbers` — Locate a code snippet's line range Source: https://context7.com/gemini-cli-extensions/security/llms.txt Finds the exact start and end line numbers of a multi-line code snippet within a specified file. It includes protection against path traversal and rejects files outside the current working directory. ```APIDOC ## `find_line_numbers` — Locate a code snippet's line range ### Description Finds the exact start and end line numbers of a multi-line code snippet within a file. Used during Phase 3 of the analysis workflow to annotate each finding with precise line numbers. Includes path traversal protection: rejects paths outside the current working directory. ### Method `mcpClient.callTool('find_line_numbers', { filePath: string, snippet: string }) ` ### Parameters #### Body Parameters - **filePath** (string) - Required - The path to the file to search within. - **snippet** (string) - Required - The multi-line code snippet to locate. ### Request Example ```typescript const result = await mcpClient.callTool('find_line_numbers', { filePath: 'src/api/users.ts', snippet: `const query = "SELECT * FROM users WHERE id = " + userId;`, }); ``` ### Response #### Success Response - **content** (array) - Contains the line number information. - **text** (string) - A JSON string representing the start and end line numbers, e.g., `{"startLine":32,"endLine":32}`. #### Error Responses - **content** (array) - Contains error messages. - **text** (string) - Error message, e.g., `{"error":"Snippet was not found."}` or `{"error":"File path is outside of the current working directory."}`. ``` -------------------------------- ### Locate Code Snippet Line Range Source: https://context7.com/gemini-cli-extensions/security/llms.txt Finds the exact start and end line numbers of a multi-line code snippet within a specified file. It includes path traversal protection and rejects paths outside the current working directory. Used in Phase 3 of the analysis workflow for precise annotation. The underlying function is `findLineNumbers` in `security.ts`. ```typescript const result = await mcpClient.callTool('find_line_numbers', { filePath: 'src/api/users.ts', snippet: `const query = "SELECT * FROM users WHERE id = " + userId;`, }); ``` ```typescript import { findLineNumbers } from './security.js'; const output = await findLineNumbers( { filePath: 'src/api/users.ts', snippet: 'const query = ...' }, { fs, path } // injectable dependencies for testing ); ``` -------------------------------- ### Set up PoC workspace with `poc_context` Source: https://context7.com/gemini-cli-extensions/security/llms.txt Creates a PoC workspace directory and returns context variables for exploit generation. Auto-detects project language and generates language-specific scaffolding. ```typescript const result = await mcpClient.callTool('poc_context', { problemStatement: 'The findLineNumbers function may be vulnerable to path traversal via the filePath parameter.', vulnerabilityType: 'path_traversal', // 'path_traversal' | 'other' sourceCodeLocation: 'mcp-server/src/security.ts:findLineNumbers()', }); // result.content[0].text → JSON string: // { // "context": { // "problemStatement": "...", // "sourceCodeLocation": "mcp-server/src/security.ts:findLineNumbers()", // "vulnerabilityType": "path_traversal", // "language": "Node.js" // }, // "pocDir": "/project/.gemini_security/poc", // "pocFileName": "poc_path_traversal_1748923456789.ts", // "extraInstructions": "* **Path Traversal Verification:**\n * A temporary file will automatically be created at '/project/gcli_secext_path_traversal_test.txt'..." // } ``` -------------------------------- ### Add entries to vulnerability allowlist with `security:note-adder` Source: https://context7.com/gemini-cli-extensions/security/llms.txt MCP prompt for managing the `.gemini_security/vuln_allowlist.txt` file. Used to suppress findings by providing vulnerability details and justification. ```text # Invoked automatically by the model when a user disputes a finding. # Produces or appends to .gemini_security/vuln_allowlist.txt in this format: Vulnerability: Reflected XSS in bio field Location: src/profile/render.ts:88 Line Content: return
; Justification: The bio field is sanitized server-side by DOMPurify before storage. ``` -------------------------------- ### Fetch patch context with `security_patch_context` Source: https://context7.com/gemini-cli-extensions/security/llms.txt Loads vulnerability knowledge base and target file content to create a structured prompt for the `security-patcher` skill. Requires vulnerability type, file paths, and a context description. ```typescript const result = await mcpClient.callTool('security_patch_context', { vulnerability: 'path_traversal', // VulnerabilityType enum value filePath: '/project/mcp-server/src/security.ts', pocFilePath: '/project/.gemini_security/poc/poc_path_traversal_1748923456789.ts', vulnerabilityContext: 'findLineNumbers() resolves filePath without rejecting paths outside CWD. Lines 23-37.', }); // Returns a formatted context block containing: // - Knowledge base article for path_traversal (secure patterns, vulnerable vs secure comparison) // - The full file content of security.ts // - PoC file path reference // - "Next Steps: Invoke the security-patcher skill..." ``` -------------------------------- ### Analyze Entire Repository with Gemini CLI Source: https://context7.com/gemini-cli-extensions/security/llms.txt Run a full SAST workflow over all auditable files in the repository. Prompts for confirmation if the line count exceeds 20,000. ```bash /security:analyze-full ``` -------------------------------- ### GitHub Actions PR Analysis with Gemini CLI Source: https://context7.com/gemini-cli-extensions/security/llms.txt Configure a GitHub Actions workflow to use the Gemini CLI for security analysis on pull requests. Posts findings as inline review comments. ```yaml # .github/workflows/gemini-review.yml name: Gemini Security Review on: pull_request: issue_comment: types: [created] jobs: security-analysis: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: google-github-actions/run-gemini-cli@v0 with: prompt_file: .gemini/security-pr-prompt.txt env: REPOSITORY: ${{ github.repository }} PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} ``` -------------------------------- ### Execute a PoC file with `run_poc` Source: https://context7.com/gemini-cli-extensions/security/llms.txt Runs a generated PoC script in a sandboxed environment, supporting various languages. Validates file location within `.gemini_security/poc/` and handles language-specific execution environments. ```typescript const result = await mcpClient.callTool('run_poc', { filePath: '/project/.gemini_security/poc/poc_path_traversal_1748923456789.ts', }); // Success output: // "## PoC Execution\n#### stdout\n```\n[traversal output]\n```\n\n#### stderr\n```\n\n```" // Security error (file outside pocDir): // { isError: true, content: [{ text: "Security Error: PoC execution is restricted to files within '...'" }] } ``` ```typescript import { runPoc } from './poc.js'; const output = await runPoc({ filePath: '/project/.gemini_security/poc/poc_other_1748923456789.py' }); // Returns: RunPocResult { stdout, stderr, error?, isSecurityError? } ``` -------------------------------- ### Python: Insecure Direct Object Reference (IDOR) - Secure Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This Python code snippet shows the secure way to handle object references by verifying ownership before returning a resource. It includes a check to ensure the authenticated user is authorized to access the requested order. ```python # SECURE - Verifies ownership def get_order(order_id, current_user): order = db.orders.find_one({"_id": order_id}) if order.user_id != current_user.id: raise AuthorizationError("User cannot access this order") return order ``` -------------------------------- ### Analyze Code Changes with Security Extension Source: https://github.com/gemini-cli-extensions/security/blob/main/README.md Use the /security:analyze command to analyze code changes on your current branch. This provides a first-pass analysis and is not a complete security audit. Currently designed for interactive use. ```bash /security:analyze Analyze all the source code under the script folder. Skip the docs, config files and package files. ``` ```bash /security:analyze --json ``` ```bash /security:analyze Return the report in JSON format. ``` -------------------------------- ### List Auditable Source Files Source: https://context7.com/gemini-cli-extensions/security/llms.txt Returns all tracked and untracked git files, excluding common non-auditable directories and file types like `node_modules`, `dist`, `build`, test files, lock files, documentation, and media. The underlying filter logic is defined in `filesystem.ts`. ```typescript const result = await mcpClient.callTool('get_files_to_audit', {}); ``` ```typescript import { getFilesToAudit } from './filesystem.js'; const files = getFilesToAudit(); ``` -------------------------------- ### `get_files_to_audit` — List auditable source files Source: https://context7.com/gemini-cli-extensions/security/llms.txt Returns a list of all tracked and untracked git files that are considered auditable. It filters out common non-auditable files and directories such as `node_modules`, `dist`, test files, and lock files. ```APIDOC ## `get_files_to_audit` — List auditable source files ### Description Returns all tracked and untracked git files, filtered to exclude `node_modules`, `dist`, `build`, test files, lock files, documentation, media, and other non-auditable content as defined in `IGNORED_FOLDERS`, `IGNORED_FILES`, and `IGNORED_EXTENSIONS` constants. ### Method `mcpClient.callTool('get_files_to_audit', {}) ` ### Request Example ```typescript const result = await mcpClient.callTool('get_files_to_audit', {}); // result.content[0].text → newline-separated list of relative file paths ``` ### Response #### Success Response - **content** (array) - Contains the list of files. - **text** (string) - A newline-separated string of relative file paths. ``` -------------------------------- ### Scan for Vulnerable Dependencies Source: https://github.com/gemini-cli-extensions/security/blob/main/README.md Automate dependency scanning to identify vulnerabilities in your project's dependencies using OSV-Scanner. This helps secure your software supply chain. ```bash /security:scan-deps ``` -------------------------------- ### Load Vulnerability Knowledge Base Article Source: https://context7.com/gemini-cli-extensions/security/llms.txt Reads a Markdown knowledge base article for a given vulnerability type. Sanitizes the vulnerability name to prevent path injection. Falls back to a generic message for unknown types. ```typescript import { loadKnowledge, VulnerabilityType } from './knowledge.js'; // Load a known article const article = await loadKnowledge(VulnerabilityType.PathTraversal); // Returns full Markdown content of path_traversal.md: // "# Path Traversal Remediation\n## Description\n..." // Unknown vulnerability type const fallback = await loadKnowledge('xss'); // Returns: "No specific knowledge base article found for vulnerability: xss. please rely on your general security knowledge." ``` -------------------------------- ### Detect Primary Project Language Source: https://context7.com/gemini-cli-extensions/security/llms.txt Inspects the current working directory for language indicator files to return a normalized language string. This string is used to select the correct PoC file extension and runtime. ```typescript import { detectProjectLanguage } from './filesystem.js'; const lang = await detectProjectLanguage(); // 'Node.js' → package.json present, or .ts/.js extensions found // 'Go' → go.mod present, or .go extensions found // 'Python' → requirements.txt or pyproject.toml present, or .py extensions found // 'Unknown' → no indicators found // Used by poc_context to determine PoC file extension: // Node.js → .ts | Python → .py | Go → .go | fallback → .js ``` -------------------------------- ### Secure Path Resolution and Validation in Node.js Source: https://github.com/gemini-cli-extensions/security/blob/main/mcp-server/src/knowledge/path_traversal.md This secure pattern resolves the path using path.resolve() and then explicitly checks if the resolved path begins with the intended safe root directory, including the path separator. This is a robust defense against path traversal. ```typescript // 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'); ``` -------------------------------- ### SQL: Vulnerable Query Construction Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This SQL snippet illustrates a common SQL injection vulnerability. It constructs a database query by directly concatenating user input into the query string, which can be exploited by malicious input. ```sql query = "SELECT * FROM users WHERE username = '" + user_input + "';" ``` -------------------------------- ### Log PII Directly (Python) Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md Avoid logging Personally Identifiable Information (PII) directly. Ensure sensitive data is masked or redacted before being written to logs. ```python # INSECURE - PII is written directly to logs logger.info(f"Processing request for user: {user_email}") ``` -------------------------------- ### Analyze Current Branch Changes with Gemini CLI Source: https://context7.com/gemini-cli-extensions/security/llms.txt Analyze security vulnerabilities and privacy violations in current branch changes. Supports default diff, specific file analysis, JSON output, and explicit branch comparison. ```bash /security:analyze ``` ```bash /security:analyze Analyze all the source code under the scripts folder. Skip docs, config, and package files. ``` ```bash /security:analyze --json ``` ```bash /security:analyze Compare the main and feature/auth branches. ``` -------------------------------- ### Python: Insecure Direct Object Reference (IDOR) - Vulnerable Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This Python code snippet demonstrates an Insecure Direct Object Reference (IDOR) vulnerability. It accesses a database record using a provided ID without verifying if the current user owns the resource. ```python # INSECURE - No ownership check def get_order(order_id, current_user): return db.orders.find_one({"_id": order_id}) ``` -------------------------------- ### Convert Markdown Report to JSON Source: https://context7.com/gemini-cli-extensions/security/llms.txt Reads the `.gemini_security/DRAFT_SECURITY_REPORT.md` file and converts it into a structured JSON array saved at `.gemini_security/security_report.json`. This is triggered only when the user requests `--json` output. The resulting JSON structure conforms to the `Finding` interface defined in `parser.ts`. ```typescript const result = await mcpClient.callTool('convert_report_to_json', {}); ``` ```json [ { "vulnerability": "SQL Injection", "vulnerabilityType": "Security", "severity": "Critical", "dataType": null, "sourceLocation": { "file": "src/api/users.ts", "startLine": 15, "endLine": 15 }, "sinkLocation": { "file": "src/api/users.ts", "startLine": 32, "endLine": 32 }, "lineContent": "const query = \"SELECT * FROM users WHERE id = \" + userId;", "description": "User-supplied `userId` is concatenated directly into the SQL query...", "recommendation": "Use parameterized queries or a trusted ORM method.", "codeSuggestion": "const query = db.prepare('SELECT * FROM users WHERE id = ?');\nquery.run(userId);" } ] ``` -------------------------------- ### `convert_report_to_json` — Convert Markdown report to JSON Source: https://context7.com/gemini-cli-extensions/security/llms.txt Reads the draft security report in Markdown format (`.gemini_security/DRAFT_SECURITY_REPORT.md`) and converts it into a structured JSON array, saving it as `.gemini_security/security_report.json`. This function is triggered when JSON output is requested. ```APIDOC ## `convert_report_to_json` — Convert Markdown report to JSON ### Description Reads `.gemini_security/DRAFT_SECURITY_REPORT.md` and converts it to a structured JSON array at `.gemini_security/security_report.json`. Triggered only when the user requests `--json` output. ### Method `mcpClient.callTool('convert_report_to_json', {}) ` ### Request Example ```typescript const result = await mcpClient.callTool('convert_report_to_json', {}); // result.content[0].text → "Successfully created JSON report at /project/.gemini_security/security_report.json" ``` ### Response #### Success Response - **content** (array) - Contains the success message. - **text** (string) - A confirmation message indicating the JSON report was created successfully and its location. ``` -------------------------------- ### Retrieve Git Diff for Analysis Source: https://context7.com/gemini-cli-extensions/security/llms.txt Retrieves the git diff for the current changes. Falls back to `git diff` for the working directory if no base or head are specified and the repository is not a GitHub remote. Called automatically by `/security:analyze`. ```typescript const result = await mcpClient.callTool('get_audit_scope', { base: 'main', head: 'feature/login', }); ``` ```typescript const workingDirResult = await mcpClient.callTool('get_audit_scope', {}); ``` -------------------------------- ### Python: Command Injection Vulnerability Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This Python code snippet shows a command injection vulnerability. It constructs a shell command using an f-string that directly incorporates user input, allowing an attacker to execute arbitrary system commands. ```python import os # User can inject commands like "; rm -rf /" filename = user_input os.system(f"grep 'pattern' {filename}") ``` -------------------------------- ### Parse Markdown Report to Structured Findings Source: https://context7.com/gemini-cli-extensions/security/llms.txt Converts free-form Markdown security reports into a typed `Finding[]` array. Handles various Markdown elements including code blocks for recommendations. ```typescript import { parseMarkdownToDict, Finding } from './parser.js'; const markdown = ` ## VULN-001 **Vulnerability:** SQL Injection **Vulnerability Type:** Security **Severity:** Critical **Source Location:** src/api/users.ts:15 **Sink Location:** src/api/users.ts:32 **Line Content:** ``` const query = "SELECT * FROM users WHERE id = " + userId; ``` **Description:** Raw user input concatenated into SQL query. **Recommendation:** Use parameterized queries. ```typescript db.prepare('SELECT * FROM users WHERE id = ?').run(userId); ``` `; const findings: Finding[] = parseMarkdownToDict(markdown); ``` -------------------------------- ### Vulnerable File Path Concatenation in Node.js Source: https://github.com/gemini-cli-extensions/security/blob/main/mcp-server/src/knowledge/path_traversal.md Avoid directly concatenating user input with a base directory. This method is vulnerable to path traversal attacks, as inputs like "../../etc/passwd" can be used to access sensitive files. ```typescript // VULNERABLE: Direct concatenation allows inputs like "../../etc/passwd" const targetPath = path.join('/var/www/uploads', userInput); return fs.readFile(targetPath, 'utf-8'); ``` -------------------------------- ### Count Total Lines Across Files Source: https://context7.com/gemini-cli-extensions/security/llms.txt Calculates the total line count for a given list of file paths. This is used by `/security:analyze-full` to gate large repository scans. The underlying function is `getLineCount` in `filesystem.ts`. ```typescript const result = await mcpClient.callTool('get_line_count', { files: ['src/auth/login.ts', 'src/api/users.ts', 'src/utils/crypto.ts'], }); ``` ```typescript import { getLineCount } from './filesystem.js'; const total = getLineCount(['src/auth/login.ts', 'src/api/users.ts']); ``` -------------------------------- ### `get_line_count` — Count total lines across files Source: https://context7.com/gemini-cli-extensions/security/llms.txt Calculates the total number of lines for a given list of file paths. This function is primarily used to gate large repository scans by checking the total line count. ```APIDOC ## `get_line_count` — Count total lines across files ### Description Returns the total line count for a list of file paths. Used by `/security:analyze-full` to gate large-repository scans. ### Method `mcpClient.callTool('get_line_count', { files: string[] }) ` ### Parameters #### Path Parameters - **files** (string[]) - Required - An array of file paths for which to count lines. ### Request Example ```typescript const result = await mcpClient.callTool('get_line_count', { files: ['src/auth/login.ts', 'src/api/users.ts', 'src/utils/crypto.ts'], }); // result.content[0].text → "342" (total lines as string) ``` ### Response #### Success Response - **content** (array) - Contains the total line count. - **text** (string) - The total number of lines across all specified files, as a string. ``` -------------------------------- ### React JSX: Cross-Site Scripting (XSS) Vulnerability Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md This React JSX code snippet demonstrates a Cross-Site Scripting (XSS) vulnerability. It uses `dangerouslySetInnerHTML` to render raw HTML from user-provided input, which can lead to arbitrary code execution in the browser. ```jsx function UserBio({ bio }) { // This is a classic XSS vulnerability return
; } ``` -------------------------------- ### Send Raw PII to Analytics (JavaScript) Source: https://github.com/gemini-cli-extensions/security/blob/main/GEMINI.md Do not send raw Personally Identifiable Information (PII) to third-party analytics services. Implement data masking or tokenization before transmission. ```javascript // INSECURE - Raw PII sent to an analytics service analytics.track("User Signed Up", { email: user.email, fullName: user.name }); ``` -------------------------------- ### `get_audit_scope` — Retrieve git diff for analysis Source: https://context7.com/gemini-cli-extensions/security/llms.txt Retrieves the git diff representing the current changes. It can optionally take base and head branches or commit hashes. If no arguments are provided and the repository is not a GitHub remote, it falls back to `git diff` for the working directory. ```APIDOC ## `get_audit_scope` — Retrieve git diff for analysis ### Description Returns the git diff representing the current changes. Falls back to `git diff` (working directory) if no base/head are provided and the repository is not a GitHub remote. ### Method `mcpClient.callTool('get_audit_scope', { base: 'main', head: 'feature/login' }) ` ### Parameters #### Optional Parameters - **base** (string) - The base branch or commit hash for comparison. - **head** (string) - The head branch or commit hash for comparison. ### Request Example ```typescript const result = await mcpClient.callTool('get_audit_scope', { base: 'main', head: 'feature/login' }); // result.content[0].text → unified diff string const workingDirResult = await mcpClient.callTool('get_audit_scope', {}); ``` ### Response #### Success Response - **content** (array) - Contains the diff output. - **text** (string) - The unified diff string. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.