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',
|
||||
|
||||
Reference in new issue
Block a user