dotnet-codeql
Use the open-source CodeQL ecosystem for .NET security analysis. Use when a repo needs CodeQL query packs, CLI-based analysis on open source codebases, or GitHub Action setup with explicit licensing caveats for private repositories.
Install
npx skills add https://github.com/Postpartum-genushyacinthus29/dotnet-skills/tree/main/skills/dotnet-codeql
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install postpartum-genushyacinthus29-dotnet-skills@llmmart
git clone https://github.com/Postpartum-genushyacinthus29/dotnet-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole postpartum-genushyacinthus29/dotnet-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
CodeQL for .NET
Trigger On
- the repo uses or wants CodeQL for .NET security analysis
- GitHub code scanning is part of the CI plan
Value
- produce a concrete project delta: code, docs, config, tests, CI, or review artifact
- reduce ambiguity through explicit planning, verification, and final validation skills
- leave reusable project context so future tasks are faster and safer
Do Not Use For
- teams that need a tool with no private-repo licensing caveat
Inputs
- the nearest
AGENTS.md - hosting model: open-source repo, private repo, or manual CLI workflow
- current GitHub Actions workflow
Quick Start
- Read the nearest
AGENTS.mdand confirm scope and constraints. - Run this skill's
Workflowthrough theRalph Loopuntil outcomes are acceptable. - Return the
Required Result Formatwith concrete artifacts and verification evidence.
Workflow
- Treat CodeQL as a security-analysis tool, not as a style checker.
- Make the licensing and hosting model explicit before proposing it as the default gate.
- Prefer manual build mode for compiled .NET projects when precision matters.
Bootstrap When Missing
If CodeQL is not configured yet:
- Detect current state:
rg -n "codeql-action|security-events|CodeQL" .github/workflowscommand -v codeql
- Prefer CI-first setup for repository scanning using
github/codeql-action/initandgithub/codeql-action/analyze. - Configure explicit .NET build mode in workflow (
manualwhen precision matters). - Add local CLI usage only when the task requires local query work.
- Run the workflow or local analyze path and return
status: configuredorstatus: improved. - If licensing or hosting constraints reject CodeQL for this repo, return
status: not_applicablewith caveat documented.
Deliver
- explicit CodeQL setup or an explicit rejection with caveat documented
- reproducible CI or local commands for running CodeQL in this repo
Validate
- the chosen CodeQL path is allowed for the repo type
- build mode is documented and reproducible
Ralph Loop
Use the Ralph Loop for every task, including docs, architecture, testing, and tooling work.
- Plan first (mandatory):
- analyze current state
- define target outcome, constraints, and risks
- write a detailed execution plan
- list final validation skills to run at the end, with order and reason
- Execute one planned step and produce a concrete delta.
- Review the result and capture findings with actionable next fixes.
- Apply fixes in small batches and rerun the relevant checks or review steps.
- Update the plan after each iteration.
- Repeat until outcomes are acceptable or only explicit exceptions remain.
- If a dependency is missing, bootstrap it or return
status: not_applicablewith explicit reason and fallback path.
Required Result Format
status:complete|clean|improved|configured|not_applicable|blockedplan: concise plan and current iteration stepactions_taken: concrete changes madevalidation_skills: final skills run, or skipped with reasonsverification: commands, checks, or review evidence summaryremaining: top unresolved items ornone
For setup-only requests with no execution, return status: configured and exact next commands.
Load References
references/codeql.mdreferences/queries.mdreferences/workflow.md
Example Requests
- "Set up CodeQL for this public .NET repo."
- "Explain the CodeQL caveat for private repos."
Files (dotnet-skills)
-
references
-
codeql.md 1.4 KB
# CodeQL ## Open/Free Status - open-source query packs and tooling exist - usable on open-source codebases - important caveat: GitHub-hosted scanning for private repositories is not universally free and may require GitHub Advanced Security ## Install For GitHub Actions, use the official action: - `github/codeql-action/init` - `github/codeql-action/analyze` For CLI and query work on open-source codebases, use the CodeQL bundle and CLI from the official CodeQL docs and releases. ## Verify First Before proposing install steps, check whether the repo already has CodeQL configured: ```bash rg -n "codeql-action|security-events|CodeQL" .github/workflows command -v codeql ``` ## Common Usage Typical GitHub Actions flow: 1. initialize CodeQL 2. build the .NET project in `manual` or `autobuild` mode 3. analyze and upload results ## CI Fit - strong fit for security scanning - best used with explicit build mode for compiled .NET repos - document the private-repo licensing caveat before standardizing on it ## When Not To Use - when the team requires a tool that is unambiguously open/free for private repos without platform caveats ## Sources - [CodeQL tools](https://codeql.github.com/docs/codeql-overview/codeql-tools/) - [CodeQL Action](https://github.com/github/codeql-action) - [About code scanning with CodeQL](https://docs.github.com/en/code-security/code-scanning/introduction-to-code-scanning/about-code-scanning-with-codeql) -
queries.md 5.2 KB
# Common CodeQL Queries for .NET ## Built-in Query Suites CodeQL ships with pre-built query suites for C#/.NET security analysis. ### Default Security Suites ```yaml # In your CodeQL workflow queries: - uses: security-extended - uses: security-and-quality ``` Available suites for `csharp`: | Suite | Purpose | |-------|---------| | `csharp-code-scanning.qls` | Default code scanning queries | | `csharp-security-extended.qls` | Extended security queries | | `csharp-security-and-quality.qls` | Security plus code quality | | `csharp-security-experimental.qls` | Experimental security queries | ## Common Security Queries ### SQL Injection Query ID: `cs/sql-injection` Detects unsanitized user input flowing into SQL queries. ```csharp // Vulnerable pattern detected: string query = "SELECT * FROM Users WHERE Name = '" + userInput + "'"; cmd.CommandText = query; // Safe pattern: cmd.CommandText = "SELECT * FROM Users WHERE Name = @name"; cmd.Parameters.AddWithValue("@name", userInput); ``` ### Path Injection Query ID: `cs/path-injection` Detects file path manipulation from user input. ```csharp // Vulnerable pattern detected: string path = Path.Combine(basePath, userInput); File.ReadAllText(path); // Safe pattern: string safePath = Path.GetFullPath(Path.Combine(basePath, userInput)); if (!safePath.StartsWith(Path.GetFullPath(basePath))) throw new SecurityException("Path traversal detected"); ``` ### Cross-Site Scripting (XSS) Query ID: `cs/web/xss` Detects unencoded user input in web responses. ```csharp // Vulnerable pattern detected: Response.Write(userInput); // Safe pattern: Response.Write(HttpUtility.HtmlEncode(userInput)); ``` ### Insecure Deserialization Query ID: `cs/unsafe-deserialization-untrusted-input` Detects dangerous deserialization of untrusted data. ```csharp // Vulnerable pattern detected: BinaryFormatter formatter = new BinaryFormatter(); object obj = formatter.Deserialize(untrustedStream); // Safe pattern: // Use System.Text.Json or explicitly typed serializers var obj = JsonSerializer.Deserialize<MyType>(jsonString); ``` ### Hardcoded Credentials Query ID: `cs/hardcoded-credentials` Detects passwords and secrets in source code. ```csharp // Vulnerable pattern detected: string connectionString = "Server=db;Password=secret123;"; // Safe pattern: string connectionString = configuration.GetConnectionString("Default"); ``` ### LDAP Injection Query ID: `cs/ldap-injection` Detects unsanitized input in LDAP queries. ```csharp // Vulnerable pattern detected: string filter = "(uid=" + userInput + ")"; searcher.Filter = filter; // Safe pattern: string safeInput = userInput.Replace("\\", "\\5c").Replace("*", "\\2a"); string filter = "(uid=" + safeInput + ")"; ``` ### Command Injection Query ID: `cs/command-line-injection` Detects OS command injection vulnerabilities. ```csharp // Vulnerable pattern detected: Process.Start("cmd.exe", "/c " + userInput); // Safe pattern: var psi = new ProcessStartInfo("myapp.exe"); psi.ArgumentList.Add(userInput); // Properly escaped Process.Start(psi); ``` ### XML External Entity (XXE) Query ID: `cs/xml/insecure-dtd-handling` Detects insecure XML parsing configurations. ```csharp // Vulnerable pattern detected: XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; // Safe pattern: XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Prohibit; settings.XmlResolver = null; ``` ## Running Custom Queries ### CLI Query Execution ```bash # Run a specific query codeql query run path/to/query.ql --database=my-csharp-db # Run a query suite codeql database analyze my-csharp-db csharp-security-extended.qls \ --format=sarif-latest \ --output=results.sarif ``` ### Query Pack Installation ```bash # Download standard query packs codeql pack download codeql/csharp-queries # List available queries codeql resolve queries codeql/csharp-queries ``` ## Custom Query Example Create a custom query to find specific patterns: ```ql /** * @name Find Console.WriteLine calls * @description Finds all Console.WriteLine method calls * @kind problem * @problem.severity recommendation * @id custom/find-console-writeline */ import csharp from MethodCall mc where mc.getTarget().hasQualifiedName("System.Console", "WriteLine") select mc, "Console.WriteLine call found" ``` Save as `custom-queries/find-console.ql` and run: ```bash codeql query run custom-queries/find-console.ql --database=my-csharp-db ``` ## Filtering Results ### Severity Levels - `error` - Critical security issues - `warning` - Potential security concerns - `recommendation` - Code quality improvements - `note` - Informational findings ### Excluding False Positives Create a `.github/codeql/codeql-config.yml`: ```yaml name: "Custom CodeQL Config" queries: - uses: security-extended paths-ignore: - "**/Tests/**" - "**/test/**" - "**/*.Designer.cs" - "**/Migrations/**" query-filters: - exclude: id: cs/hardcoded-credentials tags contain: test ``` ## Sources - [CodeQL for C# documentation](https://codeql.github.com/docs/codeql-language-guides/codeql-for-csharp/) - [C# CodeQL queries on GitHub](https://github.com/github/codeql/tree/main/csharp/ql/src) - [CodeQL query help](https://codeql.github.com/codeql-query-help/csharp/) -
workflow.md 6.3 KB
# CodeQL GitHub Actions Setup for .NET ## Basic Workflow Create `.github/workflows/codeql.yml`: ```yaml name: "CodeQL" on: push: branches: [main, master] pull_request: branches: [main, master] schedule: - cron: '30 5 * * 1' # Weekly Monday 5:30 AM UTC jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ['csharp'] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} - name: Setup .NET uses: actions/setup-dotnet@v4 with: dotnet-version: '8.0.x' - name: Build run: dotnet build --configuration Release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{ matrix.language }}" ``` ## Build Modes ### Manual Build (Recommended for .NET) Explicit control over the build process: ```yaml - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: csharp build-mode: manual - name: Build run: | dotnet restore dotnet build --no-restore --configuration Release ``` ### Autobuild Let CodeQL detect and run the build: ```yaml - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: csharp build-mode: autobuild ``` Autobuild limitations: - May not find all projects in complex solutions - Custom build steps are not executed - May miss conditional compilation ### None (Interpreted Languages Only) Not applicable for C#/.NET compiled code. ## Advanced Configuration ### Custom Query Suite Create `.github/codeql/codeql-config.yml`: ```yaml name: "Custom CodeQL Config" queries: - uses: security-extended - uses: security-and-quality paths: - src paths-ignore: - "**/Tests/**" - "**/*.Designer.cs" - "**/Migrations/**" - "**/obj/**" - "**/bin/**" ``` Reference in workflow: ```yaml - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: csharp config-file: .github/codeql/codeql-config.yml ``` ### Multi-Project Solutions For solutions with multiple projects: ```yaml - name: Build Solution run: | dotnet restore MySolution.sln dotnet build MySolution.sln --no-restore -c Release # Or build specific projects - name: Build Projects run: | dotnet build src/Api/Api.csproj -c Release dotnet build src/Core/Core.csproj -c Release ``` ### .NET Framework Projects For legacy .NET Framework: ```yaml jobs: analyze: runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: csharp build-mode: manual - name: Setup MSBuild uses: microsoft/setup-msbuild@v2 - name: Setup NuGet uses: NuGet/setup-nuget@v2 - name: Restore NuGet packages run: nuget restore MySolution.sln - name: Build run: msbuild MySolution.sln /p:Configuration=Release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 ``` ## Workflow Triggers ### On Pull Request ```yaml on: pull_request: branches: [main] paths: - '**.cs' - '**.csproj' - '**.sln' ``` ### Scheduled Scans ```yaml on: schedule: # Daily at 2 AM UTC - cron: '0 2 * * *' ``` ### Manual Trigger ```yaml on: workflow_dispatch: inputs: query-suite: description: 'Query suite to use' required: false default: 'security-extended' ``` ## SARIF Upload and Results ### Upload to GitHub Security Tab Automatic with `github/codeql-action/analyze`: ```yaml - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:csharp" output: sarif-results upload: always # or 'failure-only' or 'never' ``` ### Upload Custom SARIF ```yaml - name: Upload SARIF uses: github/codeql-action/upload-sarif@v3 with: sarif_file: results.sarif category: "custom-analysis" ``` ### Artifact Storage ```yaml - name: Upload SARIF as artifact uses: actions/upload-artifact@v4 with: name: sarif-results path: sarif-results retention-days: 5 ``` ## Performance Optimization ### Caching Dependencies ```yaml - name: Cache NuGet packages uses: actions/cache@v4 with: path: ~/.nuget/packages key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} restore-keys: | ${{ runner.os }}-nuget- ``` ### Parallel Analysis ```yaml strategy: fail-fast: false matrix: include: - project: src/Api/Api.csproj name: api - project: src/Web/Web.csproj name: web ``` ### Timeout Configuration ```yaml jobs: analyze: timeout-minutes: 60 ``` ## Security Permissions ### Minimum Required Permissions ```yaml permissions: actions: read # Required for workflow runs contents: read # Required to checkout code security-events: write # Required to upload SARIF ``` ### For Pull Requests from Forks ```yaml permissions: pull-requests: read security-events: write ``` ## Troubleshooting ### Debug Logging ```yaml - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: csharp debug: true ``` ### Build Failures Check autobuild logs: ```yaml - name: Autobuild uses: github/codeql-action/autobuild@v3 continue-on-error: true - name: Manual build fallback if: failure() run: dotnet build ``` ### Database Verification ```yaml - name: Check database run: | ls -la ${{ runner.temp }}/codeql_databases/ ``` ## Private Repository Licensing For private repositories: - GitHub Advanced Security license required for GitHub-hosted scanning - Self-hosted runners with CodeQL CLI may have different licensing - Verify licensing requirements with GitHub before enabling ## Sources - [CodeQL Action documentation](https://github.com/github/codeql-action) - [Configuring CodeQL scanning](https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning) - [CodeQL CLI manual](https://codeql.github.com/docs/codeql-cli/)
-
-
SKILL.md 3.9 KB
--- name: dotnet-codeql version: "1.0.0" category: "Metrics" description: "Use the open-source CodeQL ecosystem for .NET security analysis. Use when a repo needs CodeQL query packs, CLI-based analysis on open source codebases, or GitHub Action setup with explicit licensing caveats for private repositories." compatibility: "Requires a GitHub-based or CLI-based CodeQL workflow; respects the repo's `AGENTS.md` commands first." --- # CodeQL for .NET ## Trigger On - the repo uses or wants CodeQL for .NET security analysis - GitHub code scanning is part of the CI plan ## Value - produce a concrete project delta: code, docs, config, tests, CI, or review artifact - reduce ambiguity through explicit planning, verification, and final validation skills - leave reusable project context so future tasks are faster and safer ## Do Not Use For - teams that need a tool with no private-repo licensing caveat ## Inputs - the nearest `AGENTS.md` - hosting model: open-source repo, private repo, or manual CLI workflow - current GitHub Actions workflow ## Quick Start 1. Read the nearest `AGENTS.md` and confirm scope and constraints. 2. Run this skill's `Workflow` through the `Ralph Loop` until outcomes are acceptable. 3. Return the `Required Result Format` with concrete artifacts and verification evidence. ## Workflow 1. Treat CodeQL as a security-analysis tool, not as a style checker. 2. Make the licensing and hosting model explicit before proposing it as the default gate. 3. Prefer manual build mode for compiled .NET projects when precision matters. ## Bootstrap When Missing If `CodeQL` is not configured yet: 1. Detect current state: - `rg -n "codeql-action|security-events|CodeQL" .github/workflows` - `command -v codeql` 2. Prefer CI-first setup for repository scanning using `github/codeql-action/init` and `github/codeql-action/analyze`. 3. Configure explicit .NET build mode in workflow (`manual` when precision matters). 4. Add local CLI usage only when the task requires local query work. 5. Run the workflow or local analyze path and return `status: configured` or `status: improved`. 6. If licensing or hosting constraints reject CodeQL for this repo, return `status: not_applicable` with caveat documented. ## Deliver - explicit CodeQL setup or an explicit rejection with caveat documented - reproducible CI or local commands for running CodeQL in this repo ## Validate - the chosen CodeQL path is allowed for the repo type - build mode is documented and reproducible ## Ralph Loop Use the Ralph Loop for every task, including docs, architecture, testing, and tooling work. 1. Plan first (mandatory): - analyze current state - define target outcome, constraints, and risks - write a detailed execution plan - list final validation skills to run at the end, with order and reason 2. Execute one planned step and produce a concrete delta. 3. Review the result and capture findings with actionable next fixes. 4. Apply fixes in small batches and rerun the relevant checks or review steps. 5. Update the plan after each iteration. 6. Repeat until outcomes are acceptable or only explicit exceptions remain. 7. If a dependency is missing, bootstrap it or return `status: not_applicable` with explicit reason and fallback path. ### Required Result Format - `status`: `complete` | `clean` | `improved` | `configured` | `not_applicable` | `blocked` - `plan`: concise plan and current iteration step - `actions_taken`: concrete changes made - `validation_skills`: final skills run, or skipped with reasons - `verification`: commands, checks, or review evidence summary - `remaining`: top unresolved items or `none` For setup-only requests with no execution, return `status: configured` and exact next commands. ## Load References - `references/codeql.md` - `references/queries.md` - `references/workflow.md` ## Example Requests - "Set up CodeQL for this public .NET repo." - "Explain the CodeQL caveat for private repos."
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.