File size: 17,594 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | /**
* Tree-sitter AST analysis utilities for bash command security validation.
*
* These functions extract security-relevant information from tree-sitter
* parse trees, providing more accurate analysis than regex/shell-quote
* parsing. Each function takes a root node and command string, and returns
* structured data that can be used by security validators.
*
* The native NAPI parser returns plain JS objects β no cleanup needed.
*/
type TreeSitterNode = {
type: string
text: string
startIndex: number
endIndex: number
children: TreeSitterNode[]
childCount: number
}
export type QuoteContext = {
/** Command text with single-quoted content removed (double-quoted content preserved) */
withDoubleQuotes: string
/** Command text with all quoted content removed */
fullyUnquoted: string
/** Like fullyUnquoted but preserves quote characters (', ") */
unquotedKeepQuoteChars: string
}
export type CompoundStructure = {
/** Whether the command has compound operators (&&, ||, ;) at the top level */
hasCompoundOperators: boolean
/** Whether the command has pipelines */
hasPipeline: boolean
/** Whether the command has subshells */
hasSubshell: boolean
/** Whether the command has command groups ({...}) */
hasCommandGroup: boolean
/** Top-level compound operator types found */
operators: string[]
/** Individual command segments split by compound operators */
segments: string[]
}
export type DangerousPatterns = {
/** Has $() or backtick command substitution (outside quotes that would make it safe) */
hasCommandSubstitution: boolean
/** Has <() or >() process substitution */
hasProcessSubstitution: boolean
/** Has ${...} parameter expansion */
hasParameterExpansion: boolean
/** Has heredoc */
hasHeredoc: boolean
/** Has comment */
hasComment: boolean
}
export type TreeSitterAnalysis = {
quoteContext: QuoteContext
compoundStructure: CompoundStructure
/** Whether actual operator nodes (;, &&, ||) exist β if false, \; is just a word argument */
hasActualOperatorNodes: boolean
dangerousPatterns: DangerousPatterns
}
type QuoteSpans = {
raw: Array<[number, number]> // raw_string (single-quoted)
ansiC: Array<[number, number]> // ansi_c_string ($'...')
double: Array<[number, number]> // string (double-quoted)
heredoc: Array<[number, number]> // quoted heredoc_redirect
}
/**
* Single-pass collection of all quote-related spans.
* Previously this was 5 separate tree walks (one per type-set plus
* allQuoteTypes plus heredoc); fusing cuts tree-traversal ~5x.
*
* Replicates the per-type walk semantics: each original walk stopped at
* its own type. So the raw_string walk would recurse THROUGH a string
* node (not its type) to reach nested raw_string inside $(...), but the
* string walk would stop at the outer string. We track `inDouble` to
* collect the *outermost* string span per path, while still descending
* into $()/${} bodies to pick up inner raw_string/ansi_c_string.
*
* raw_string / ansi_c_string / quoted-heredoc bodies are literal text
* in bash (no expansion), so no nested quote nodes exist β return early.
*/
function collectQuoteSpans(
node: TreeSitterNode,
out: QuoteSpans,
inDouble: boolean,
): void {
switch (node.type) {
case 'raw_string':
out.raw.push([node.startIndex, node.endIndex])
return // literal body, no nested quotes possible
case 'ansi_c_string':
out.ansiC.push([node.startIndex, node.endIndex])
return // literal body
case 'string':
// Only collect the outermost string (matches old per-type walk
// which stops at first match). Recurse regardless β a nested
// $(cmd 'x') inside "..." has a real inner raw_string.
if (!inDouble) out.double.push([node.startIndex, node.endIndex])
for (const child of node.children) {
if (child) collectQuoteSpans(child, out, true)
}
return
case 'heredoc_redirect': {
// Quoted heredocs (<<'EOF', <<"EOF", <<\EOF): literal body.
// Unquoted (<<EOF) expands $()/${} β the body can contain
// $(cmd 'x') whose inner '...' IS a real raw_string node.
// Detection: heredoc_start text starts with '/"/\\
// Matches sync path's extractHeredocs({ quotedOnly: true }).
let isQuoted = false
for (const child of node.children) {
if (child && child.type === 'heredoc_start') {
const first = child.text[0]
isQuoted = first === "'" || first === '"' || first === '\\'
break
}
}
if (isQuoted) {
out.heredoc.push([node.startIndex, node.endIndex])
return // literal body, no nested quote nodes
}
// Unquoted: recurse into heredoc_body β command_substitution β
// inner quote nodes. The original per-type walks did NOT stop at
// heredoc_redirect (not in their type sets), so they recursed here.
break
}
}
for (const child of node.children) {
if (child) collectQuoteSpans(child, out, inDouble)
}
}
/**
* Builds a Set of all character positions covered by the given spans.
*/
function buildPositionSet(spans: Array<[number, number]>): Set<number> {
const set = new Set<number>()
for (const [start, end] of spans) {
for (let i = start; i < end; i++) {
set.add(i)
}
}
return set
}
/**
* Drops spans that are fully contained within another span, keeping only the
* outermost. Nested quotes (e.g., `"$(echo 'hi')"`) yield overlapping spans
* β the inner raw_string is found by recursing into the outer string node.
* Processing overlapping spans corrupts indices since removing/replacing the
* outer span shifts the inner span's start/end into stale positions.
*/
function dropContainedSpans<T extends readonly [number, number, ...unknown[]]>(
spans: T[],
): T[] {
return spans.filter(
(s, i) =>
!spans.some(
(other, j) =>
j !== i &&
other[0] <= s[0] &&
other[1] >= s[1] &&
(other[0] < s[0] || other[1] > s[1]),
),
)
}
/**
* Removes spans from a string, returning the string with those character
* ranges removed.
*/
function removeSpans(command: string, spans: Array<[number, number]>): string {
if (spans.length === 0) return command
// Drop inner spans that are fully contained in an outer one, then sort by
// start index descending so we can splice without offset shifts.
const sorted = dropContainedSpans(spans).sort((a, b) => b[0] - a[0])
let result = command
for (const [start, end] of sorted) {
result = result.slice(0, start) + result.slice(end)
}
return result
}
/**
* Replaces spans with just the quote delimiters (preserving ' and " characters).
*/
function replaceSpansKeepQuotes(
command: string,
spans: Array<[number, number, string, string]>,
): string {
if (spans.length === 0) return command
const sorted = dropContainedSpans(spans).sort((a, b) => b[0] - a[0])
let result = command
for (const [start, end, open, close] of sorted) {
// Replace content but keep the quote delimiters
result = result.slice(0, start) + open + close + result.slice(end)
}
return result
}
/**
* Extract quote context from the tree-sitter AST.
* Replaces the manual character-by-character extractQuotedContent() function.
*
* Tree-sitter node types:
* - raw_string: single-quoted ('...')
* - string: double-quoted ("...")
* - ansi_c_string: ANSI-C quoting ($'...') β span includes the leading $
* - heredoc_redirect: QUOTED heredocs only (<<'EOF', <<"EOF", <<\EOF) β
* the full redirect span (<<, delimiters, body, newlines) is stripped
* since the body is literal text in bash (no expansion). UNQUOTED
* heredocs (<<EOF) are left in place since bash expands $(...)/${...}
* inside them, and validators need to see those patterns. Matches the
* sync path's extractHeredocs({ quotedOnly: true }).
*/
export function extractQuoteContext(
rootNode: unknown,
command: string,
): QuoteContext {
// Single walk collects all quote span types at once.
const spans: QuoteSpans = { raw: [], ansiC: [], double: [], heredoc: [] }
collectQuoteSpans(rootNode as TreeSitterNode, spans, false)
const singleQuoteSpans = spans.raw
const ansiCSpans = spans.ansiC
const doubleQuoteSpans = spans.double
const quotedHeredocSpans = spans.heredoc
const allQuoteSpans = [
...singleQuoteSpans,
...ansiCSpans,
...doubleQuoteSpans,
...quotedHeredocSpans,
]
// Build a set of positions that should be excluded for each output variant.
// For withDoubleQuotes: remove single-quoted spans entirely, plus the
// opening/closing `"` delimiters of double-quoted spans (but keep the
// content between them). This matches the regex extractQuotedContent()
// semantics where `"` toggles quote state but content is still emitted.
const singleQuoteSet = buildPositionSet([
...singleQuoteSpans,
...ansiCSpans,
...quotedHeredocSpans,
])
const doubleQuoteDelimSet = new Set<number>()
for (const [start, end] of doubleQuoteSpans) {
doubleQuoteDelimSet.add(start) // opening "
doubleQuoteDelimSet.add(end - 1) // closing "
}
let withDoubleQuotes = ''
for (let i = 0; i < command.length; i++) {
if (singleQuoteSet.has(i)) continue
if (doubleQuoteDelimSet.has(i)) continue
withDoubleQuotes += command[i]
}
// fullyUnquoted: remove all quoted content
const fullyUnquoted = removeSpans(command, allQuoteSpans)
// unquotedKeepQuoteChars: remove content but keep delimiter chars
const spansWithQuoteChars: Array<[number, number, string, string]> = []
for (const [start, end] of singleQuoteSpans) {
spansWithQuoteChars.push([start, end, "'", "'"])
}
for (const [start, end] of ansiCSpans) {
// ansi_c_string spans include the leading $; preserve it so this
// matches the regex path, which treats $ as unquoted preceding '.
spansWithQuoteChars.push([start, end, "$'", "'"])
}
for (const [start, end] of doubleQuoteSpans) {
spansWithQuoteChars.push([start, end, '"', '"'])
}
for (const [start, end] of quotedHeredocSpans) {
// Heredoc redirect spans have no inline quote delimiters β strip entirely.
spansWithQuoteChars.push([start, end, '', ''])
}
const unquotedKeepQuoteChars = replaceSpansKeepQuotes(
command,
spansWithQuoteChars,
)
return { withDoubleQuotes, fullyUnquoted, unquotedKeepQuoteChars }
}
/**
* Extract compound command structure from the AST.
* Replaces isUnsafeCompoundCommand() and splitCommand() for tree-sitter path.
*/
export function extractCompoundStructure(
rootNode: unknown,
command: string,
): CompoundStructure {
const n = rootNode as TreeSitterNode
const operators: string[] = []
const segments: string[] = []
let hasSubshell = false
let hasCommandGroup = false
let hasPipeline = false
// Walk top-level children of the program node
function walkTopLevel(node: TreeSitterNode): void {
for (const child of node.children) {
if (!child) continue
if (child.type === 'list') {
// list nodes contain && and || operators
for (const listChild of child.children) {
if (!listChild) continue
if (listChild.type === '&&' || listChild.type === '||') {
operators.push(listChild.type)
} else if (
listChild.type === 'list' ||
listChild.type === 'redirected_statement'
) {
// Nested list, or redirected_statement wrapping a list/pipeline β
// recurse so inner operators/pipelines are detected. For
// `cmd1 && cmd2 2>/dev/null && cmd3`, the redirected_statement
// wraps `list(cmd1 && cmd2)` β the inner `&&` would be missed
// without recursion.
walkTopLevel({ ...node, children: [listChild] } as TreeSitterNode)
} else if (listChild.type === 'pipeline') {
hasPipeline = true
segments.push(listChild.text)
} else if (listChild.type === 'subshell') {
hasSubshell = true
segments.push(listChild.text)
} else if (listChild.type === 'compound_statement') {
hasCommandGroup = true
segments.push(listChild.text)
} else {
segments.push(listChild.text)
}
}
} else if (child.type === ';') {
operators.push(';')
} else if (child.type === 'pipeline') {
hasPipeline = true
segments.push(child.text)
} else if (child.type === 'subshell') {
hasSubshell = true
segments.push(child.text)
} else if (child.type === 'compound_statement') {
hasCommandGroup = true
segments.push(child.text)
} else if (
child.type === 'command' ||
child.type === 'declaration_command' ||
child.type === 'variable_assignment'
) {
segments.push(child.text)
} else if (child.type === 'redirected_statement') {
// `cd ~/src && find path 2>/dev/null` β tree-sitter wraps the ENTIRE
// compound in a redirected_statement: program β redirected_statement β
// (list β cmd1, &&, cmd2) + file_redirect. Same for `cmd1 | cmd2 > out`
// (wraps pipeline) and `(cmd) > out` (wraps subshell). Recurse to
// detect the inner structure; skip file_redirect children (redirects
// don't affect compound/pipeline classification).
let foundInner = false
for (const inner of child.children) {
if (!inner || inner.type === 'file_redirect') continue
foundInner = true
walkTopLevel({ ...child, children: [inner] } as TreeSitterNode)
}
if (!foundInner) {
// Standalone redirect with no body (shouldn't happen, but fail-safe)
segments.push(child.text)
}
} else if (child.type === 'negated_command') {
// `! cmd` β recurse into the inner command so its structure is
// classified (pipeline/subshell/etc.), but also record the full
// negated text as a segment so segments.length stays meaningful.
segments.push(child.text)
walkTopLevel(child)
} else if (
child.type === 'if_statement' ||
child.type === 'while_statement' ||
child.type === 'for_statement' ||
child.type === 'case_statement' ||
child.type === 'function_definition'
) {
// Control-flow constructs: the construct itself is one segment,
// but recurse so inner pipelines/subshells/operators are detected.
segments.push(child.text)
walkTopLevel(child)
}
}
}
walkTopLevel(n)
// If no segments found, the whole command is one segment
if (segments.length === 0) {
segments.push(command)
}
return {
hasCompoundOperators: operators.length > 0,
hasPipeline,
hasSubshell,
hasCommandGroup,
operators,
segments,
}
}
/**
* Check whether the AST contains actual operator nodes (;, &&, ||).
*
* This is the key function for eliminating the `find -exec \;` false positive.
* Tree-sitter parses `\;` as part of a `word` node (an argument to find),
* NOT as a `;` operator. So if no actual `;` operator nodes exist in the AST,
* there are no compound operators and hasBackslashEscapedOperator() can be skipped.
*/
export function hasActualOperatorNodes(rootNode: unknown): boolean {
const n = rootNode as TreeSitterNode
function walk(node: TreeSitterNode): boolean {
// Check for operator types that indicate compound commands
if (node.type === ';' || node.type === '&&' || node.type === '||') {
// Verify this is a child of a list or program, not inside a command
return true
}
if (node.type === 'list') {
// A list node means there are compound operators
return true
}
for (const child of node.children) {
if (child && walk(child)) return true
}
return false
}
return walk(n)
}
/**
* Extract dangerous pattern information from the AST.
*/
export function extractDangerousPatterns(rootNode: unknown): DangerousPatterns {
const n = rootNode as TreeSitterNode
let hasCommandSubstitution = false
let hasProcessSubstitution = false
let hasParameterExpansion = false
let hasHeredoc = false
let hasComment = false
function walk(node: TreeSitterNode): void {
switch (node.type) {
case 'command_substitution':
hasCommandSubstitution = true
break
case 'process_substitution':
hasProcessSubstitution = true
break
case 'expansion':
hasParameterExpansion = true
break
case 'heredoc_redirect':
hasHeredoc = true
break
case 'comment':
hasComment = true
break
}
for (const child of node.children) {
if (child) walk(child)
}
}
walk(n)
return {
hasCommandSubstitution,
hasProcessSubstitution,
hasParameterExpansion,
hasHeredoc,
hasComment,
}
}
/**
* Perform complete tree-sitter analysis of a command.
* Extracts all security-relevant data from the AST in one pass.
* This data must be extracted before tree.delete() is called.
*/
export function analyzeCommand(
rootNode: unknown,
command: string,
): TreeSitterAnalysis {
return {
quoteContext: extractQuoteContext(rootNode, command),
compoundStructure: extractCompoundStructure(rootNode, command),
hasActualOperatorNodes: hasActualOperatorNodes(rootNode),
dangerousPatterns: extractDangerousPatterns(rootNode),
}
}
|