mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-24 17:11:28 +01:00
`/cso` no longer stops on a repository that tracks a symlink, such as gstack's own `connect-chrome` or `CLAUDE.md -> AGENTS.md`: each link is listed in the report by its target string, or as withheld when the target matches a secret pattern, and it is never followed. Why: a security audit that refuses ordinary repositories audits nothing, and following a link would let it point the scanner at `/etc/passwd` or out through `..`. Nothing to do. FIFOs, sockets and devices are still refused, and `--paths` now limits that check to the audited directories. Co-authored-by: nathanshox <196341+nathanshox@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/red-team#3 reader=red-team Review-Finding: p2/red-team#1 reader=red-team Review-Finding: p3/outside-voice#1 reader=outside-voice
This commit is contained in:
6 files changed
+359
-24
No files matched your search
+112
-8
@@ -1,6 +1,6 @@
|
||||
import * as fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { dirname, isAbsolute, join, resolve, relative, sep } from 'node:path';
|
||||
import { dirname, isAbsolute, join, posix, resolve, relative, sep } from 'node:path';
|
||||
import {
|
||||
CsoError,
|
||||
SnapshotManifest,
|
||||
@@ -77,6 +77,28 @@ export function historyMarker(note: string): string {
|
||||
/** Transformation recorded for a repository boundary Git listed as one entry: an untracked nested repository or a registered submodule gitlink. */
|
||||
export const NESTED_REPOSITORY =
|
||||
'excluded: nested Git repository; Git listed it as a single boundary entry and never descends into it, so its own source and history are not audited with this repository';
|
||||
/**
|
||||
* Transformation recorded for a symlink. Git tracks only its target string, so
|
||||
* that string is the whole input: it is reported verbatim and the link is never
|
||||
* followed. Where it points is classified lexically, without touching the
|
||||
* filesystem, so the classification cannot be raced or redirected. A target
|
||||
* that matches any secret pattern, as a whole or in any path segment (the
|
||||
* redactor misses key=value after a slash, and per-segment checks miss a URL),
|
||||
* fails closed: it is withheld and no path derived from it is shown.
|
||||
*/
|
||||
export function symlinkTransformation(path: string, target: string): string {
|
||||
const unix = target.replace(/\\/g, '/'),
|
||||
secret = redact(target) !== target || unix.split('/').some((part) => redact(part) !== part),
|
||||
normalized = posix.normalize(posix.join(posix.dirname(relativePath(path)), unix)),
|
||||
where = /^(?:[A-Za-z]:)?[\\/]/.test(target)
|
||||
? 'an absolute path, never resolved'
|
||||
: normalized === '..' || normalized.startsWith('../')
|
||||
? 'a relative path that escapes the repository, never resolved'
|
||||
: secret
|
||||
? 'a relative path inside the repository'
|
||||
: `resolves lexically to ${normalized === '.' ? 'the repository root' : JSON.stringify(normalized)} inside the repository`;
|
||||
return `excluded: symlink to ${secret ? 'a target withheld because it matches a secret pattern' : JSON.stringify(target)} (${where}); the link is recorded by its target string and never followed, and a target inside the repository is audited only under its own path`;
|
||||
}
|
||||
export function inAuditPaths(path: string, prefixes: readonly string[]): boolean {
|
||||
return prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
|
||||
}
|
||||
@@ -324,6 +346,39 @@ function directoryIdentities(root: string, path: string): DirectoryIdentity[] {
|
||||
}
|
||||
return identities;
|
||||
}
|
||||
type LinkIdentity = { dev: number; ino: number; mode: number; target: Buffer };
|
||||
/** Read a source symlink's own target string under identity checks; the link itself is never followed. */
|
||||
function readLinkStable(root: string, path: string): LinkIdentity {
|
||||
const ancestors = directoryIdentities(root, path),
|
||||
full = join(root, relativePath(path)),
|
||||
changed = () => new CsoError('SNAPSHOT_RACE', `Source symlink changed while reading: ${path}`),
|
||||
stat = () => {
|
||||
try {
|
||||
return fs.lstatSync(full);
|
||||
} catch {
|
||||
throw changed();
|
||||
}
|
||||
},
|
||||
named = stat();
|
||||
if (!named.isSymbolicLink()) throw changed();
|
||||
let target: Buffer;
|
||||
try {
|
||||
target = fs.readlinkSync(full, { encoding: 'buffer' });
|
||||
} catch {
|
||||
throw changed();
|
||||
}
|
||||
const current = stat();
|
||||
if (
|
||||
!current.isSymbolicLink() ||
|
||||
current.dev !== named.dev ||
|
||||
current.ino !== named.ino ||
|
||||
current.mode !== named.mode ||
|
||||
current.size !== named.size
|
||||
)
|
||||
throw changed();
|
||||
assertDirectoryIdentities(ancestors, path);
|
||||
return { dev: named.dev, ino: named.ino, mode: named.mode & 0o777, target };
|
||||
}
|
||||
function assertDirectoryIdentities(identities: DirectoryIdentity[], path: string): void {
|
||||
for (const expected of identities) {
|
||||
let current: fs.Stats;
|
||||
@@ -542,10 +597,15 @@ async function rejectSpecialFiles(
|
||||
repo: string,
|
||||
home: string,
|
||||
admission: ReturnType<typeof snapshotAdmission>,
|
||||
auditPaths?: readonly string[],
|
||||
): Promise<void> {
|
||||
// Git intentionally omits untracked FIFOs and devices from ls-files. Walk
|
||||
// pathnames without opening payloads, then ask Git which special names are
|
||||
// ignored so a nonignored FIFO cannot silently disappear from the snapshot.
|
||||
// Git intentionally omits untracked FIFOs, sockets and devices from
|
||||
// ls-files. Walk pathnames without opening payloads, then ask Git which
|
||||
// special names are ignored so a nonignored FIFO cannot silently disappear
|
||||
// from the snapshot. Symlinks are not special here: Git lists every tracked
|
||||
// or nonignored one, and capture records it by its target string without
|
||||
// following it. With --paths, only the audit scope and the directories
|
||||
// leading to it are walked, since nothing outside it is captured.
|
||||
admission.time();
|
||||
const ignoredRaw = await git(
|
||||
repo,
|
||||
@@ -570,6 +630,9 @@ async function rejectSpecialFiles(
|
||||
candidate = candidate.slice(0, slash);
|
||||
}
|
||||
};
|
||||
const inScope = (path: string) => !auditPaths || inAuditPaths(path, auditPaths),
|
||||
leadsIntoScope = (path: string) =>
|
||||
inScope(path) || auditPaths!.some((prefix) => prefix.startsWith(`${path}/`));
|
||||
const special: string[] = [];
|
||||
let visited = 0;
|
||||
const walk = (at: string, prefix = '') => {
|
||||
@@ -584,10 +647,10 @@ async function rejectSpecialFiles(
|
||||
const full = join(at, item.name),
|
||||
stat = fs.lstatSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
walk(full, path);
|
||||
if (leadsIntoScope(path)) walk(full, path);
|
||||
continue;
|
||||
}
|
||||
if (!stat.isFile()) special.push(path);
|
||||
if (!stat.isFile() && !stat.isSymbolicLink() && inScope(path)) special.push(path);
|
||||
}
|
||||
} finally {
|
||||
directory.closeSync();
|
||||
@@ -658,6 +721,7 @@ export async function capture(
|
||||
gitModes = new Map<string, string>(),
|
||||
sensitiveEvidence: any[] = [],
|
||||
boundaries = new Map<string, fs.Stats>(),
|
||||
links = new Map<string, LinkIdentity>(),
|
||||
absentPaths = new Set<string>();
|
||||
let total = 0;
|
||||
guard();
|
||||
@@ -673,7 +737,7 @@ export async function capture(
|
||||
if (unmatched !== undefined)
|
||||
throw new CsoError('INVALID_ARGUMENT', `--paths entry matches no source file: ${unmatched}`);
|
||||
const outsideAudit = (path: string) => auditPaths !== undefined && !inAuditPaths(path, auditPaths);
|
||||
await rejectSpecialFiles(repo, home, admission);
|
||||
await rejectSpecialFiles(repo, home, admission, auditPaths);
|
||||
guard();
|
||||
const manifest: SnapshotManifest = {
|
||||
version: 3,
|
||||
@@ -716,6 +780,33 @@ export async function capture(
|
||||
throw error;
|
||||
}
|
||||
const size = source.size;
|
||||
// Git stores a symlink as its target string, so that string is the
|
||||
// whole source. Record it and never follow the link, whatever it
|
||||
// points at: a file, a directory, a device, /etc, a loop or nothing.
|
||||
if (source.isSymbolicLink()) {
|
||||
const link = readLinkStable(repo, path),
|
||||
dependency = noReadPath(path);
|
||||
links.set(path, link);
|
||||
gitModes.set(path, '120000');
|
||||
gitHashes.set(
|
||||
path,
|
||||
createHash(objectFormat).update(`blob ${link.target.length}\0`).update(link.target).digest('hex'),
|
||||
);
|
||||
entries.push({
|
||||
path,
|
||||
pathId: snapshotPathId(repo, path),
|
||||
originalHash: dependency || outsideAudit(path) ? 'not-read' : sha256(link.target),
|
||||
bytes: link.target.length,
|
||||
mode: link.mode,
|
||||
transformation: dependency
|
||||
? `excluded: ${exclusion(path) ?? 'host dependency input'}`
|
||||
: outsideAudit(path)
|
||||
? OUTSIDE_AUDIT_PATHS
|
||||
: symlinkTransformation(path, link.target.toString()),
|
||||
});
|
||||
guard();
|
||||
continue;
|
||||
}
|
||||
// A directory in Git's inventory is a repository boundary, not source:
|
||||
// an untracked nested repository (listed with a trailing slash) or a
|
||||
// registered submodule's gitlink. Git reports it as one entry and never
|
||||
@@ -841,6 +932,19 @@ export async function capture(
|
||||
const assertEntriesStable = (message: string) => {
|
||||
for (const e of entries) {
|
||||
guard();
|
||||
const link = links.get(e.path);
|
||||
if (link) {
|
||||
const current = readLinkStable(repo, e.path);
|
||||
if (
|
||||
current.dev !== link.dev ||
|
||||
current.ino !== link.ino ||
|
||||
current.mode !== link.mode ||
|
||||
!current.target.equals(link.target)
|
||||
)
|
||||
throw new CsoError('SNAPSHOT_RACE', `${message}: ${e.path}`);
|
||||
guard();
|
||||
continue;
|
||||
}
|
||||
if (e.originalHash === 'not-read') {
|
||||
const boundary = boundaries.get(e.path);
|
||||
if (boundary) {
|
||||
@@ -1032,7 +1136,7 @@ export async function capture(
|
||||
// Finish with a complete source check. Nothing below this block reads the
|
||||
// audited repository, so a late nonignored file or restored deletion cannot
|
||||
// fall between the final inventory and manifest publication.
|
||||
await rejectSpecialFiles(repo, home, admission);
|
||||
await rejectSpecialFiles(repo, home, admission, auditPaths);
|
||||
guard();
|
||||
assertEntriesStable('Source changed before snapshot persistence');
|
||||
if (canonical(list) !== canonical(await paths(repo, home, headCommit, admission)))
|
||||
|
||||
Reference in new issue
Block a user