Skip to content

Harden CodeQL and CI against activation injection regressions #3464

Closed

Description

@gaborbernat

The custom CodeQL pack under .github/codeql/queries and the activation test suite are our regression guards for the injection class behind the activation and seeding advisories. This issue collects what CodeQL and the surrounding GitHub tooling can add, what they cannot, and the follow-ups worth doing.

What CodeQL can and cannot do here

CodeQL has no shell extractor. Its languages are C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, Rust, Swift and GitHub Actions. activate.sh, activate.fish, activate.csh, activate.nu and activate.bat are invisible to it, and that is where most of the activation advisories lived. Everything below either hardens the Python side of the boundary (the activator classes, quote(), template substitution) or brings a different tool to the templates.

1. Merge protection on code scanning results

A repository ruleset can require code scanning results from CodeQL before a merge, with two thresholds: alerts (Errors / Errors and Warnings / All) and security alerts (Critical / High or higher / Medium or higher / All). Today a finding from our custom pack shows up as a pull request annotation only; with the ruleset it blocks the merge. Settings → Rules → Rulesets → branch ruleset on main → "Require code scanning results" → tool CodeQL, Alerts = Errors, Security alerts = High or higher. Our custom queries carry @security-severity 7.3 to 7.8, so they gate. The same rule can be set through the REST rules API (code_scanning rule type). Docs: Set code scanning merge protection. This is a repository setting, not code; it is listed here so the whole picture is in one place.

2. Query liveness job with mutant patches

codeql test run checks a query against its own fixture, so a query can keep passing after the production code it was written for is refactored out from under it. Two of the three queries in the pack had drifted that way: one sank on a .replace() call that the single-pass template substitution no longer makes, the other on a write_text call that became write_file. Their fixtures were self-contained, so codeql test run stayed green for weeks while the queries matched nothing in src/virtualenv. Nothing off the shelf detects this; it needs a job that turns "the query exists" into "the query still sees production code".

Add a job to check.yaml that keeps a .github/codeql/mutants/<Query>.patch per query, applies each to a scratch copy of src/virtualenv, builds one database with codeql database create, runs the query with codeql database analyze, and fails unless it reports at least one result. The same job runs every query on the clean tree and fails on any result. The mutants are the ones used while writing the queries, so this mostly formalises existing work.

3. Model pack for the activation boundary

Since April 2026, CodeQL data extensions can declare sanitizers and validators (barrierModel, barrierGuardModel) for Python, next to the existing sourceModel, sinkModel, typeModel and summaryModel: CodeQL now supports sanitizers and validators in models-as-data, Customizing library models for Python. The extension is a YAML file with an extensions list; each entry names the pack and predicate it adds to (addsTo) and the tuples (data).

Declaring ViaTemplateActivator.quote() and CShellActivator._prompt_literal() as sanitizers and the template substitution as a command-injection sink lets the built-in py/command-line-injection and py/code-injection queries cover the activators. Two advantages over our hand-written taint queries: the built-in queries track flow through comprehensions, ** splats and f-strings for us, so the model does not go stale when instantiate_template or substitutions() changes shape (the failure mode in item 2); and the same model file feeds Copilot Autofix. The custom queries stay for the shapes the standard queries do not know, such as the substitutions() dict and the launcher shebang. Verify with the mutants from item 2 which built-in queries fire. Model packs are usable with advanced setup, which is what we run; default setup cannot load custom packs.

4. Weekly bash version matrix

CI runs the activation tests on bash 5.2 (ubuntu-24.04) and 3.2 (macOS /bin/bash) only. ${var//pat/rep} replacement, promptvars, posix mode and patsub_replacement differ across 4.x and 5.x, and BASH_COMPAT on a 5.x binary is an emulation of the older behaviour, not the real thing. Add a scheduled workflow with a matrix over the bash:3.2, 4.0, 4.1, 4.2, 4.3, 4.4, 5.0, 5.1, 5.2, 5.3 container images that runs tests/unit/activation/test_bash.py -k prompt on each, so a prompt-escaping change is checked on every bash the activator claims to support. Nothing in CI exercises 4.x today, which is where the replacement behaviour differs.

5. Semgrep rules for the shell templates

Semgrep's Bash support is in its experimental tier: syntax patterns, the ... operator and basic metavariables, no taint, best-effort issue handling (Supported languages, Scanning shell scripts with Semgrep). That is enough for structural rules with a real parser behind them: PS1= must not read VIRTUAL_ENV_PROMPT directly, export PS1 must not appear, and the escaping passes must precede the PS1 assignment. A pre-commit hook such as semgrep --config .semgrep/activation.yml src/virtualenv/activation runs in seconds. This guards structure only; the state-matrix tests stay the behavioural guard. fish, csh and nushell have no Semgrep parser, so the rules cover bash and zsh only.

6. Containment query for metadata deletes

PipInstall._uninstall_dist deletes paths it builds from top_level.txt and RECORD entries and keeps them inside the environment with a root not in resolved.parents check. A taint query from read_text().splitlines() to unlink/safe_delete with that check as the barrier would guard the fix, but codeql/python-all does not carry taint from name through env_dir / name into the delete call: an explicit isAdditionalTaintStep on the / operator, a loop-variable source, and TaintTracking::localTaint all left the sink unreachable. The query needs either a data extension that models pathlib.Path.__truediv__ as a taint step or a syntactic form that ties the loop variable to the delete argument.

Considered and rejected

  • ShellCheck: no custom rules, and it would not have flagged any of the activation advisories. Skip.
  • security-and-quality suite: we run security-extended with threat-models: local, which is right for a CLI tool (argv, environment and files as sources). security-and-quality adds maintainability queries; worth a one-off run to see the noise level, not a standing change (About CodeQL query suites).
  • codeql pack lint / codeql query format --check in codeql.yaml: small, catches query syntax drift at lint time instead of analysis time; fold into item 2 if convenient.

Metadata

Metadata

Assignees

No one assigned

    Labels

    github_actionssecuritytests

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions