fix(hooks): close command-safety bypasses and credential helper output loss
The command-safety hook only checked the first word of each segment, so destructive commands inside if/for/while blocks, subshells, braces, PowerShell script blocks, or behind wrapper options (xargs -0, sudo -E, timeout 30) ran unchecked. A comment with an apostrophe, an escaped quote, or a line continuation also hid the following command. Skip shell keywords, split on braces, drop comments, honor backslash escapes, join continued lines, and check every suffix after a wrapper. CLI mode also strips the byte order mark that Windows PowerShell 5.1 adds to piped stdin, which let every command pass there. with-credential.ps1 returned the child's exit code from a function, so the child's stdout was captured and the exit code became 0. Run the child as a statement and exit with its code. add-credentials now refreshes the installed helper on every run so fixes reach existing machines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f5d8f6f11b
commit
63a36d90e0
5 files changed
+77
-19
No files matched your search
@@ -29,8 +29,8 @@ if ($ValueFromStdin) {
|
||||
$bin = Join-Path $HomePath '.my-ai-configuration/bin'
|
||||
New-Item -ItemType Directory -Path $bin -Force | Out-Null
|
||||
foreach ($source in @('with-credential.ps1', 'with-credential.sh')) {
|
||||
$destination = Join-Path $bin $source
|
||||
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination }
|
||||
# Always refresh so fixes to the helper reach machines that already have it.
|
||||
Copy-Item -LiteralPath (Join-Path $root "scripts/lib/$source") -Destination (Join-Path $bin $source) -Force
|
||||
}
|
||||
foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
|
||||
Set-ManagedCredential $target $Key $Value
|
||||
|
||||
@@ -111,8 +111,8 @@ function Invoke-WithManagedCredential {
|
||||
$value = Get-ManagedCredential $Client $Key
|
||||
try {
|
||||
[Environment]::SetEnvironmentVariable($Key, $value, 'Process')
|
||||
# Output goes straight to the caller; returning a value here would capture the child's stdout.
|
||||
& $FilePath @ArgumentList
|
||||
return $LASTEXITCODE
|
||||
} finally {
|
||||
[Environment]::SetEnvironmentVariable($Key, $prior, 'Process')
|
||||
$value = $null
|
||||
@@ -121,5 +121,6 @@ function Invoke-WithManagedCredential {
|
||||
|
||||
if ($FilePath) {
|
||||
if (-not $Client -or -not $Key) { throw 'Client and key are required.' }
|
||||
exit (Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList)
|
||||
Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
@@ -41,6 +41,31 @@ class HookTests(unittest.TestCase):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
|
||||
def test_blocks_commands_hidden_in_control_flow_and_wrapper_options(self):
|
||||
for command in ('if [ -d build ]; then rm -rf build; fi', 'for d in a b; do rm -rf "$d"; done',
|
||||
'while true; do git reset --hard; done', '(rm -rf x)', '{ git reset --hard; }', '! rm -rf x',
|
||||
'find . -print0 | xargs -0 rm -rf', 'sudo -E rm -rf /x', 'env -i git reset --hard',
|
||||
'timeout 30 rm -rf x', 'nice -n 5 rm -rf x', 'rm -rf ${dir}', 'echo ${#arr[@]}; rm -rf x',
|
||||
"sudo -u bob bash -c 'rm -rf x'"):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
for command in ('Get-ChildItem bin -Recurse | ForEach-Object { Remove-Item $_ -Recurse -Force }',
|
||||
'gci bin | % { ri $_ -Recurse }', 'foreach ($d in $dirs) { Remove-Item $d -Recurse }'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command, 'PowerShell')
|
||||
|
||||
def test_blocks_commands_after_comments_escapes_and_line_continuations(self):
|
||||
for command in ("echo hi # don't touch\nrm -rf build", 'echo "\\""; git reset --hard', "echo 'a\\'; rm -rf x",
|
||||
'rm \\\n -rf build', 'git reset \\\n --hard'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
self.assertBlocked('Remove-Item build `\n -Recurse -Force', 'PowerShell')
|
||||
|
||||
def test_allows_comments_and_hashes_that_are_not_commands(self):
|
||||
for command in ('ls # rm -rf x', 'git commit -m "fix #12; rm -rf is bad"', 'echo a#b', 'echo "\\"rm -rf x\\""'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
|
||||
def test_blocks_destructive_powershell_variants(self):
|
||||
for command in ('Remove-Item build -Recurse -Force', 'Remove-Item -Path build -Rec', 'rm -r build', 'ri build -recurse',
|
||||
'Get-ChildItem x | Remove-Item -Recurse', 'git reset --hard', 'cmd /c "rd /s /q build"',
|
||||
|
||||
@@ -63,6 +63,9 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
home = Path(directory)
|
||||
key = f'MY_TEST_TOKEN_{uuid.uuid4().hex}'
|
||||
stored = False
|
||||
stale = home / '.my-ai-configuration/bin/with-credential.ps1'
|
||||
stale.parent.mkdir(parents=True)
|
||||
stale.write_text('# outdated helper\n', encoding='utf-8')
|
||||
try:
|
||||
result = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||
@@ -73,15 +76,18 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
stored = True
|
||||
helper = home / '.my-ai-configuration/bin/with-credential.ps1'
|
||||
self.assertTrue(helper.is_file())
|
||||
self.assertEqual((ROOT / 'scripts/lib/with-credential.ps1').read_bytes(), helper.read_bytes(),
|
||||
'add-credentials must replace an outdated helper')
|
||||
self.assertTrue((home / '.my-ai-configuration/bin/with-credential.sh').is_file())
|
||||
child = f"if ([Environment]::GetEnvironmentVariable('{key}', 'Process')) {{ exit 0 }}; exit 1"
|
||||
child = (f"if ([Environment]::GetEnvironmentVariable('{key}', 'Process')) "
|
||||
"{ Write-Output 'child-output'; exit 3 }; exit 1")
|
||||
injected = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper),
|
||||
'-Client', 'Codex', '-Key', key, '-FilePath', powershell,
|
||||
'-NoProfile', '-Command', child,
|
||||
], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, injected.returncode, injected.stderr)
|
||||
self.assertEqual(3, injected.returncode, injected.stderr)
|
||||
self.assertIn('child-output', injected.stdout)
|
||||
finally:
|
||||
cleanup = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
|
||||
@@ -16,7 +16,10 @@ import re
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
WRAPPERS = {'sudo', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs'}
|
||||
WRAPPERS = {'sudo', 'doas', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs', 'timeout', 'nice'}
|
||||
# Shell keywords that can precede a command in the same segment.
|
||||
KEYWORDS = {'if', 'then', 'else', 'elif', 'do', 'while', 'until', '!'}
|
||||
LINE_CONTINUATION = re.compile(r'[\\`]\r?\n')
|
||||
POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'}
|
||||
POWERSHELL_HOSTS = {'pwsh', 'powershell'}
|
||||
POWERSHELL_REMOVE = {'remove-item', 'ri'}
|
||||
@@ -28,9 +31,15 @@ MAX_DEPTH = 3
|
||||
|
||||
|
||||
def split_segments(command):
|
||||
"""Split on ;, &, |, &&, || and newlines that are outside quotes."""
|
||||
segments, current, quote = [], [], None
|
||||
for character in command:
|
||||
"""Split on ;, &, |, &&, ||, newlines, and braces outside quotes; drop # comments; join continued lines."""
|
||||
command = LINE_CONTINUATION.sub(' ', command)
|
||||
segments, current, quote, index = [], [], None, 0
|
||||
while index < len(command):
|
||||
character = command[index]
|
||||
if character == '\\' and quote != "'" and index + 1 < len(command):
|
||||
current.append(command[index:index + 2])
|
||||
index += 2
|
||||
continue
|
||||
if quote:
|
||||
current.append(character)
|
||||
if character == quote:
|
||||
@@ -38,11 +47,16 @@ def split_segments(command):
|
||||
elif character in '\'"':
|
||||
quote = character
|
||||
current.append(character)
|
||||
elif character in ';&|\n':
|
||||
elif character == '#' and (index == 0 or command[index - 1].isspace()):
|
||||
newline = command.find('\n', index)
|
||||
index = len(command) if newline < 0 else newline
|
||||
continue
|
||||
elif character in ';&|\n{}':
|
||||
segments.append(''.join(current))
|
||||
current = []
|
||||
else:
|
||||
current.append(character)
|
||||
index += 1
|
||||
segments.append(''.join(current))
|
||||
return [segment.strip() for segment in segments if segment.strip()]
|
||||
|
||||
@@ -60,14 +74,16 @@ def program_name(token):
|
||||
|
||||
|
||||
def strip_wrappers(tokens):
|
||||
index = 0
|
||||
while index < len(tokens):
|
||||
token = tokens[index]
|
||||
if program_name(token) in WRAPPERS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', token):
|
||||
index += 1
|
||||
"""Drop leading keywords, subshell parentheses, and variable assignments; stop at the first program or wrapper."""
|
||||
tokens = list(tokens)
|
||||
while tokens:
|
||||
first = tokens[0].lstrip('(')
|
||||
if not first or first in KEYWORDS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', first):
|
||||
tokens.pop(0)
|
||||
continue
|
||||
tokens[0] = first
|
||||
break
|
||||
return tokens[index:]
|
||||
return tokens
|
||||
|
||||
|
||||
def short_flags(tokens):
|
||||
@@ -97,6 +113,13 @@ def check_tokens(tokens, shell=None):
|
||||
if not tokens:
|
||||
return None
|
||||
program = program_name(tokens[0])
|
||||
if program in WRAPPERS:
|
||||
# Wrapper options and values (xargs -0, sudo -u bob, timeout 30) come before the wrapped command.
|
||||
for start in range(1, len(tokens)):
|
||||
reason = check_tokens(tokens[start:], shell)
|
||||
if reason:
|
||||
return reason
|
||||
return None
|
||||
arguments = tokens[1:]
|
||||
lowered = [argument.lower() for argument in arguments]
|
||||
if program == 'rm' and shell != 'powershell':
|
||||
@@ -127,6 +150,8 @@ def nested_command(tokens):
|
||||
if not tokens:
|
||||
return None
|
||||
program = program_name(tokens[0])
|
||||
if program in WRAPPERS:
|
||||
return next((found for start in range(1, len(tokens)) if (found := nested_command(tokens[start:]))), None)
|
||||
if program == 'eval':
|
||||
return ' '.join(tokens[1:]), 'bash'
|
||||
for index, token in enumerate(tokens[1:], start=1):
|
||||
@@ -214,7 +239,8 @@ def main():
|
||||
args = parser.parse_args()
|
||||
if args.hook:
|
||||
return run_hook(sys.stdin.buffer.read())
|
||||
command = sys.stdin.read() if args.command == '-' else args.command
|
||||
# Windows PowerShell 5.1 prefixes piped stdin with a UTF-8 byte order mark.
|
||||
command = sys.stdin.buffer.read().decode('utf-8-sig', errors='replace') if args.command == '-' else args.command
|
||||
return run_check(command, args.workspace)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user