Repository navigation
fix(SG-006): read the pipeline shapes from #193 the way the shell does #207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2251,23 +2251,51 @@ def _run_decoded_matches(text: str) -> list[str]: | |
|
|
||
|
|
||
| def _looks_like_file(token: str) -> bool: | ||
| """Whether an argument names a file (`report.sh`, `./run`) rather than being a plain word. | ||
| """Whether an argument has the shape of a path (`report.sh`, `./run`, `bin/run`). | ||
|
|
||
| A skill is prose as well as shell, so `curl ... | bash to install` must still be flagged: | ||
| only an argument with a dot or a slash is taken as a script file that replaces stdin. | ||
| Trailing sentence punctuation is left out first, so a word like `install.` is prose | ||
| rather than a file with an extension. | ||
| """ | ||
| token = token.rstrip(".,:;!?") | ||
| return "." in token or "/" in token | ||
|
|
||
|
|
||
| def _is_script_operand(token: str, following: list[str]) -> bool: | ||
| """Whether a shell or Python operand names a script file rather than being prose. | ||
|
|
||
| A path always is one. A bare word with no extension is one when it is the last word, or | ||
| when the next word is clearly part of the command (an option, a redirection or a path, | ||
| as in `bash summarize report.csv`). A bare word followed by another bare word is read as | ||
| prose, so `curl ... | bash to install` is still flagged. | ||
| """ | ||
| if _looks_like_file(token): | ||
| return True | ||
| if not following: | ||
| return True | ||
| nxt = following[0] | ||
| return nxt.startswith("-") or re.match(r"\d*[<>]", nxt) is not None or _looks_like_file(nxt) | ||
|
|
||
|
|
||
| def _command_index(tokens: list[str]) -> int: | ||
| """The index of the command word, skipping a leading `sudo` and its options.""" | ||
| i = 0 | ||
| if tokens and tokens[0].lower() == "sudo": | ||
| i = 1 | ||
| while i < len(tokens) and tokens[i].startswith("-"): | ||
| i += 2 if tokens[i] in _SUDO_OPTIONS_WITH_ARGUMENT else 1 | ||
| return i | ||
|
|
||
|
|
||
| def _read_stage(segment: str) -> tuple[list[str], str]: | ||
| """Split a pipeline stage into words, reading quotes and escapes as a shell does. | ||
|
|
||
| Returns the words and the source text they were read from. The words end where the command | ||
| ends: at a `#` comment, or at a closing backtick or parenthesis that was opened before this | ||
| stage, as in "`curl ... | bash` to run" or "(curl ... | bash)". Quoted text, and a `$(...)` | ||
| opened inside the stage, stay in their word, so `bash --rcfile "$(printf x)" script.sh` | ||
| keeps its script file. An unquoted backslash escapes the next character, so `\\bash` (the | ||
| way to skip an alias) is the word `bash`. | ||
| keeps its script file, as does the unquoted `$(echo ./local.rc)` in | ||
| `bash --rcfile $(echo ./local.rc)`. An unquoted backslash escapes the next character, so | ||
| `\\bash` (the way to skip an alias) is the word `bash`. | ||
| """ | ||
| segment = segment.lstrip("({[` \t") | ||
| words: list[str] = [] | ||
|
|
@@ -2290,7 +2318,9 @@ def _read_stage(segment: str) -> tuple[list[str], str]: | |
| quote = ch | ||
| word.append(ch) | ||
| elif ch.isspace(): | ||
| if word: | ||
| if depth: | ||
| word.append(ch) # a space inside a $(...) or <(...) stays in the word | ||
| elif word: | ||
| words.append("".join(word)) | ||
| word = [] | ||
| elif ch == "\\" and i < n: | ||
|
|
@@ -2333,7 +2363,7 @@ def _shell_reads_stdin(arguments: list[str]) -> bool: | |
| if not token.startswith("--") and token.startswith("-") and "n" in token[1:]: | ||
| return False # -n reads the script and runs nothing | ||
| if not token.startswith("-"): | ||
| return not _looks_like_file(token) | ||
| return not _is_script_operand(token, arguments[j:]) | ||
| if token in ("--help", "--version"): | ||
| return False | ||
| if token.startswith("--"): | ||
|
|
@@ -2355,11 +2385,7 @@ def _shell_reads_stdin(arguments: list[str]) -> bool: | |
| def _reads_script_from_stdin(segment: str) -> bool: | ||
| """Whether this pipeline stage runs what it is fed as a script.""" | ||
| tokens, _ = _read_stage(segment) | ||
| i = 0 | ||
| if tokens and tokens[0].lower() == "sudo": | ||
| i = 1 | ||
| while i < len(tokens) and tokens[i].startswith("-"): | ||
| i += 2 if tokens[i] in _SUDO_OPTIONS_WITH_ARGUMENT else 1 | ||
| i = _command_index(tokens) | ||
| if i >= len(tokens): | ||
| return False | ||
| name = tokens[i].rsplit("/", 1)[-1].lower() | ||
|
|
@@ -2378,7 +2404,7 @@ def _reads_script_from_stdin(segment: str) -> bool: | |
| if token in ("--help", "--version"): | ||
| return False | ||
| if not token.startswith("-"): | ||
| return not _looks_like_file(token) | ||
| return not _is_script_operand(token, tokens[j:]) | ||
| if token.startswith("--"): | ||
| continue | ||
| for index, flag in enumerate(token[1:], start=1): | ||
|
|
@@ -2392,6 +2418,39 @@ def _reads_script_from_stdin(segment: str) -> bool: | |
| return True | ||
|
|
||
|
|
||
| # Commands whose output never carries their input: a count or a checksum of it, or text | ||
| # of their own. A shell after one of them is not running the download. Every other stage | ||
| # is taken to pass the download on, changed or not (`gunzip`, `sed`, `base64 -d`), so the | ||
| # finding stays. | ||
| _STAGES_THAT_REPLACE_INPUT = frozenset( | ||
| { | ||
| "wc", | ||
| "cksum", | ||
| "sum", | ||
| "md5sum", | ||
| "sha1sum", | ||
| "sha224sum", | ||
| "sha256sum", | ||
| "sha384sum", | ||
| "sha512sum", | ||
| "b2sum", | ||
| "echo", | ||
| "printf", | ||
| "true", | ||
| "false", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _stage_replaces_download(segment: str) -> bool: | ||
| """Whether a pipeline stage swaps the download for output of its own, as `wc -l` does.""" | ||
| tokens, _ = _read_stage(segment) | ||
| i = _command_index(tokens) | ||
| if i >= len(tokens): | ||
| return False | ||
| return tokens[i].rsplit("/", 1)[-1].lower() in _STAGES_THAT_REPLACE_INPUT | ||
|
|
||
|
|
||
| def _split_commands(line: str) -> list[list[tuple[str, str]]]: | ||
| """Cut a line into commands and their pipeline stages, reading quotes as a shell does. | ||
|
|
||
|
|
@@ -2483,6 +2542,70 @@ def _split_commands(line: str) -> list[list[tuple[str, str]]]: | |
| return commands | ||
|
|
||
|
|
||
| def _redirects_stdout_away(stage: str) -> bool: | ||
| """Whether this command sends its standard output to a file instead of the pipe. | ||
|
|
||
| Follows the stage's redirections from left to right: `>`, `>>`, `>|`, `&>` and `N>` | ||
| point a file descriptor at a file, while `N>&M` copies where M currently points. | ||
| Standard output (fd 1) starts at the pipe, so a later redirection can point it back | ||
| at the pipe, as in `3>&1 1>/dev/null 1>&3`. | ||
| """ | ||
| targets = {"1": "pipe"} | ||
| i, n = 0, len(stage) | ||
| quote = "" | ||
| while i < n: | ||
| ch = stage[i] | ||
| if quote: | ||
| if ch == "\\" and quote == '"': | ||
| i += 2 | ||
| continue | ||
| if ch == quote: | ||
| quote = "" | ||
| i += 1 | ||
| continue | ||
| if ch in "'\"": | ||
| quote = ch | ||
| i += 1 | ||
| continue | ||
| if ch == "\\": | ||
| i += 2 | ||
| continue | ||
| if ch != ">": | ||
| i += 1 | ||
| continue | ||
| start = i | ||
| while start > 0 and stage[start - 1].isdigit(): | ||
| start -= 1 | ||
| if start < i and (start == 0 or stage[start - 1].isspace()): | ||
| fd = stage[start:i] | ||
| else: | ||
| fd = "1" | ||
| both = start == i and i > 0 and stage[i - 1] == "&" | ||
| j = i + 1 | ||
| if j < n and stage[j] in ">|": | ||
| j += 1 | ||
| while j < n and stage[j].isspace(): | ||
| j += 1 | ||
| if j < n and stage[j] == "&": | ||
| d = j + 1 | ||
| while d < n and stage[d].isdigit(): | ||
| d += 1 | ||
| if d > j + 1: | ||
| target = targets.get(stage[j + 1 : d], "other") | ||
| else: | ||
| target = "file" # `>&file`, or a closed descriptor for `>&-` | ||
| targets[fd] = target | ||
| if both: | ||
| targets["2"] = target | ||
| i = d | ||
| continue | ||
| targets[fd] = "file" | ||
| if both: | ||
| targets["2"] = "file" | ||
| i = j | ||
| return targets.get("1", "other") != "pipe" | ||
|
|
||
|
|
||
| def _is_download(stage: str, outside_quotes: str) -> bool: | ||
| """Whether a pipeline stage runs curl or wget, rather than printing the word.""" | ||
| if not _FETCHER.search(stage): | ||
|
|
@@ -2496,7 +2619,11 @@ def _is_download(stage: str, outside_quotes: str) -> bool: | |
| # `cat curl-install.sh | bash` runs a local file whose name only contains the word. | ||
| words = stage.split() | ||
| at = next((n for n, word in enumerate(words) if _is_fetcher_word(word)), None) | ||
| return at is not None and not _curl_writes_to_file(words[at], words[at + 1 :]) | ||
| return ( | ||
| at is not None | ||
| and not _curl_writes_to_file(words[at], words[at + 1 :]) | ||
| and not _redirects_stdout_away(stage) | ||
| ) | ||
|
|
||
|
|
||
| def _curl_writes_to_file(fetcher: str, arguments: list[str]) -> bool: | ||
|
|
@@ -2536,27 +2663,91 @@ def _pipe_to_interpreter_matches(text: str) -> list[str]: | |
| if "|" not in line or not _FETCHER.search(line): | ||
| continue | ||
| for stages in _split_commands(line): | ||
| first = next( | ||
| (n for n, (stage, seen) in enumerate(stages) if _is_download(stage, seen)), None | ||
| ) | ||
| if first is None: | ||
| continue | ||
| # The snippet starts at the download command, not at the words before it. | ||
| download = stages[first][0] | ||
| fetcher = _FETCHER.search(download) | ||
| download = download[fetcher.start() :] if fetcher else download | ||
| for end in range(first + 1, len(stages)): | ||
| if _reads_script_from_stdin(stages[end][0]): | ||
| active = None | ||
| for end, (stage, seen) in enumerate(stages): | ||
| if active is not None and _reads_script_from_stdin(stage): | ||
| # The snippet starts at the download command, not at the words before it. | ||
| download = stages[active][0] | ||
| fetcher = _FETCHER.search(download) | ||
| download = download[fetcher.start() :] if fetcher else download | ||
| # The snippet is cut from the line as written, spacing around each | included, | ||
| # so the scanner can find it in the text and report its line. | ||
| rest = [_read_stage(s)[1] for s, _ in stages[first + 1 : end + 1]] | ||
| rest = [_read_stage(s)[1] for s, _ in stages[active + 1 : end + 1]] | ||
| start = line.find(download.strip()) | ||
| stop = line.find(rest[-1], start) + len(rest[-1]) if start >= 0 else -1 | ||
| if start >= 0 and stop > start: | ||
| matches.append(line[start:stop][:200]) | ||
| else: | ||
| matches.append(" | ".join(p.strip() for p in [download, *rest])[:200]) | ||
| break | ||
| if active is not None and _stage_replaces_download(stage): | ||
| active = None # this stage replaces what the download sent on | ||
| elif active is None and _is_download(stage, seen): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check for a new download in the replacing stage. At
Use an independent download check after clearing
|
||
| active = end | ||
| return matches | ||
|
|
||
|
|
||
| # A download fed to a shell or sourced through a redirection rather than a pipe: | ||
| # `bash -s stable < <(curl ...)`, `bash <<< "$(curl ...)"` and `. <(curl ...)`. | ||
| _HERE_STRING_FETCH = re.compile(r"<<<\s*[\"']?(?:\$\(|`)\s*(?:curl|wget)(?![\w-])", re.IGNORECASE) | ||
| _SEPARATE_PROCESS_FETCH = re.compile(r"<\s*<\(\s*(?:curl|wget)(?![\w-])", re.IGNORECASE) | ||
| _DIRECT_PROCESS_FETCH = re.compile(r"<\(\s*(?:curl|wget)(?![\w-])", re.IGNORECASE) | ||
| _REDIRECTION_TOKEN = re.compile(r"^\d*(?:&>>|&>|<<<|<<-?|<>|<&|>>|>\||>&|>|<(?!\())") | ||
|
|
||
|
|
||
| def _strip_redirections(arguments: list[str]) -> list[str]: | ||
| """Remove redirection operators and their targets from a command's arguments.""" | ||
| kept: list[str] = [] | ||
| skip_target = False | ||
| for token in arguments: | ||
| if skip_target: | ||
| skip_target = False | ||
| continue | ||
| match = _REDIRECTION_TOKEN.match(token) | ||
| if match: | ||
| skip_target = match.end() == len(token) | ||
| continue | ||
| kept.append(token) | ||
| return kept | ||
|
|
||
|
|
||
| def _source_reads_stdin(arguments: list[str]) -> bool: | ||
| """Whether `.`/`source` names the download rather than a script file.""" | ||
| for token in _strip_redirections(arguments): | ||
| if token == "--" or token.startswith("-"): | ||
| continue | ||
| return token.startswith("<(") | ||
| return True | ||
|
|
||
|
|
||
| def _redirection_to_interpreter_matches(text: str) -> list[str]: | ||
| """Find a download run through a here-string, process substitution or `source`.""" | ||
| matches: list[str] = [] | ||
| text = _LINE_CONTINUATION.sub(" ", text) | ||
| for line in text.splitlines(): | ||
| if "<" not in line or not _FETCHER.search(line): | ||
| continue | ||
| for stages in _split_commands(line): | ||
| for stage, outside_quotes in stages: | ||
| tokens, shown = _read_stage(stage) | ||
| i = _command_index(tokens) | ||
| if i >= len(tokens): | ||
| continue | ||
| name = tokens[i].rsplit("/", 1)[-1].lower() | ||
| if name in _SHELLS: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stop flagging redirected downloads that the shell does not execute. The shell branch at
Both inputs should not be flagged. Check the execution mode and the script operand before the redirection match returns a finding. Do not reuse The Add near-miss tests for
|
||
| found = _HERE_STRING_FETCH.search(outside_quotes) or ( | ||
| _SEPARATE_PROCESS_FETCH.search(outside_quotes) | ||
| ) | ||
| if found and not _shell_reads_stdin(_strip_redirections(tokens[i + 1 :])): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check the final stdin source before removing redirections. At
Track the effective stdin source before accepting the match. With the redirections reversed, keep the finding. As per coding guidelines, “A rule earns its place by being precise.”
|
||
| found = None | ||
| elif name in ("source", "."): | ||
| found = _DIRECT_PROCESS_FETCH.search(outside_quotes) | ||
| if found and not _source_reads_stdin(tokens[i + 1 :]): | ||
| found = None | ||
| else: | ||
| found = None | ||
| if found: | ||
| matches.append(shown[:200]) | ||
| return matches | ||
|
|
||
|
|
||
|
|
@@ -2569,6 +2760,7 @@ def _check_rug_pull(text: str) -> list[str]: | |
| [m.group(0) for m in _RUG_PULL_RE.finditer(text)] | ||
| + _run_decoded_matches(text) | ||
| + _pipe_to_interpreter_matches(text) | ||
| + _redirection_to_interpreter_matches(text) | ||
| ) | ||
|
|
||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.