GHSA-3H35-4JQ7-HV45
Unrestricted Path Traversal in Document API allows Arbitrary .md File Read/Write/Delete + mkdir
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-3H35-4JQ7-HV45 divulgada · CVSS 9.1 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Remediación | Parche 0.30.0 | knowns · 2 d desde divulgación | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Overview
Verified. The core Document API lets an unauthenticated attacker perform arbitrary file operations (Create, Read, Update, Delete) anywhere on the host's filesystem, restricted only by a `.md` extension suffix. The application blindly concatenates user-controlled paths with the target storage directory without sanitizing directory traversal sequences (`../`). This completely shatters the intended filesystem sandbox, exposing sensitive cross-project secrets and serving as the perfect payload-planting mechanism for a full remote code execution chain.
Affected paths
| File Path | Role | Vulnerability & Execution Impact |
| :--- | :--- | :--- |
| `internal/server/routes/docs.go` | Entry Point | Missing Input Sanitization: Strips slashes and the `.md` suffix via `cleanDocPath()`, but performs no neutralization of `../` traversal sequences. The raw `doc.Path` is forwarded unfiltered to the storage layer. |
| `internal/storage/doc_store.go` | Vulnerable Sink | Unsafe Path Concatenation: Uses `filepath.Join` + `filepath.FromSlash` without any sandbox containment check. Directly triggers out-of-bounds operations: `os.MkdirAll` (Create), `atomicWrite`/`os.WriteFile` (Write), `os.ReadFile` (Read), and `os.Remove` (Delete). |
Root cause
The vulnerability stems from a dangerous assumption in the file path construction logic. The HTTP handler in `routes/docs.go` decodes the wildcard URL parameter via `decodedDocWildcard()` and normalises it with `cleanDocPath()` - which trims leading/trailing slashes and drops the `.md` suffix - before setting it as `doc.Path` and passing the struct to the storage layer. Downstream, `doc_store.go` attempts to isolate file operations by calling `filepath.Join(ds.docsDir(), filepath.FromSlash(doc.Path)+".md")`. However, `filepath.Join` natively resolves `../` sequences. Because the application lacks a containment check to verify if the final resolved path is still physically inside `docsDir`, an attacker can easily traverse upwards and manipulate files outside the project root.
Attack Vector
Scenario:
- The Knowns server is running in its default deployment (where the Management API is unauthenticated and bound to all interfaces).
- An attacker sends an unauthenticated `POST /api/docs` request, injecting a traversal payload into the JSON body: `{"path": "../../../../tmp/knowns_pwn_marker"}`.
- `routes/docs.go` accepts the path, sets it on a `models.Doc` struct, and forwards it to `doc_store.go`'s `Create` method.
- The storage layer executes `filepath.Join(ds.docsDir(), "../../../../tmp/knowns_pwn_marker.md")`, successfully breaking out of the sandbox. It calls `os.MkdirAll` on the resolved directory, then writes the file via `atomicWrite`.
- The attacker verifies the write by fetching `GET /api/docs/..%2F..%2F..%2F..%2Ftmp%2Fknowns_pwn_marker`, dumping the full file content including YAML frontmatter.
Consequences: An unauthenticated external attacker can read API secrets or environment variables stored in other projects' documentation, corrupt critical system files via arbitrary overwrite/delete (`os.Remove`), and flood the server with rogue directories. More critically, this arbitrary write primitive acts as "Stage 1" to plant malicious configurations, directly enabling an RCE chain.
Analysis
We started by tracing the unauthenticated `POST /api/docs` route to see how it handles user input. The handler decodes the JSON body into a `models.Doc`, optionally auto-generates a path from the title, and forwards it directly to the storage layer without any traversal sanitization:
// internal/server/routes/docs.go (create handler, abridged)
var doc models.Doc
if err := decodeJSON(r, &doc); err != nil {
respondError(w, http.StatusBadRequest, "invalid request body: "+err.Error())
return
}
// Auto-generate path from title+folder when not provided - traversal still passes through.
if doc.Path == "" && doc.Title != "" {
slug := slugifyTitle(doc.Title)
if doc.Folder != "" {
doc.Path = doc.Folder + "/" + slug
} else {
doc.Path = slug
}
}
// doc.Path is set directly from attacker-controlled JSON; no `../` stripping occurs.
if err := dr.getStore().Docs.Create(&doc); err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}Similarly, the `GET /api/docs/*` handler calls `docPathParam(r)` → `cleanDocPath(decodedDocWildcard(r))`, which only trims slashes and drops `.md` - it does not strip `../` segments before passing the path to `DocStore.Get`.
Following the execution flow into the storage layer, the vulnerability becomes blatantly obvious. Across multiple CRUD operations (`Create`, `Update`, `Rename`, `Get`, `Delete`), `doc_store.go` relies solely on `filepath.Join` + `filepath.FromSlash` to build the destination path:
// internal/storage/doc_store.go - Create
func (ds *DocStore) Create(doc *models.Doc) error {
if doc.Path == "" {
return fmt.Errorf("doc path is required")
}
// The traversal payload resolves successfully, escaping docsDir.
absPath := filepath.Join(ds.docsDir(), filepath.FromSlash(doc.Path)+".md")
// MkdirAll blindly creates any out-of-bounds directories supplied by the attacker.
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
return fmt.Errorf("create doc dir: %w", err)
}
return ds.writeFile(absPath, doc)
}
// internal/storage/doc_store.go - Delete (same pattern)
func (ds *DocStore) Delete(path string) error {
path = strings.TrimSuffix(path, ".md")
absPath := filepath.Join(ds.docsDir(), filepath.FromSlash(path)+".md")
return os.Remove(absPath)
}There is absolutely no containment guard - such as evaluating symlinks (`filepath.EvalSymlinks`) or checking `strings.HasPrefix(finalPath, ds.docsDir())` - before the file operations trigger. Because `os.MkdirAll`, `os.Remove`, and `ds.writeFile` all execute with the privileges of the Go process, the application acts as an unauthenticated proxy for arbitrary filesystem manipulation.
Fix
*Patch is available right now at New Release https://github.com/knowns-dev/knowns/releases.*
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
npmknowns |
Corregida | 0.30.0 | 2 d | 0.35.0 no afectada |
0.30.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-3h35-4jq7-hv45Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
