test_prod2u_p4_activate_verification_toolchain.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """Windows activation-script guards for the local verification toolchain."""
  2. from __future__ import annotations
  3. import json
  4. import base64
  5. import re
  6. import shutil
  7. import os
  8. import subprocess
  9. import tempfile
  10. import unittest
  11. from pathlib import Path
  12. ROOT = Path(__file__).resolve().parents[2]
  13. ACTIVATION_SCRIPT = ROOT / "tools" / "activate_verification_toolchain.ps1"
  14. AGENT_INSTRUCTIONS = ROOT / "AGENTS.md"
  15. POWERSHELL = shutil.which("powershell.exe")
  16. CMD = shutil.which("cmd.exe")
  17. CMD_SHIM = ROOT / "tools" / "toolchain_shims" / "verilator.cmd"
  18. def ps_literal(path: Path) -> str:
  19. return "'" + str(path).replace("'", "''") + "'"
  20. def run_powershell(command: str) -> subprocess.CompletedProcess[str]:
  21. if POWERSHELL is None:
  22. raise unittest.SkipTest("Windows PowerShell is unavailable")
  23. return subprocess.run(
  24. [POWERSHELL, "-NoProfile", "-NonInteractive", "-Command", command],
  25. cwd=ROOT,
  26. text=True,
  27. capture_output=True,
  28. check=False,
  29. timeout=60,
  30. )
  31. def last_json_line(stdout: str) -> dict[str, object]:
  32. for line in reversed(stdout.splitlines()):
  33. if line.strip().startswith("{"):
  34. return json.loads(line)
  35. raise AssertionError(f"PowerShell output did not contain JSON:\n{stdout}")
  36. class ActivateVerificationToolchainTests(unittest.TestCase):
  37. def test_repository_instructions_require_a_native_verilator_entrypoint(self) -> None:
  38. instructions = AGENT_INSTRUCTIONS.read_text(encoding="utf-8")
  39. self.assertIn("tools/activate_verification_toolchain.ps1", instructions)
  40. self.assertIn("resolver", instructions)
  41. self.assertIn("Verilator", instructions)
  42. self.assertIn("PATH", instructions)
  43. def test_verilator_command_is_bound_to_native_windows_binary(self) -> None:
  44. source = ACTIVATION_SCRIPT.read_text(encoding="utf-8")
  45. self.assertIn('"verilator_bin.exe"', source)
  46. self.assertIn('"verilator.exe"', source)
  47. self.assertIn("$env:VERILATOR = $VerilatorNative", source)
  48. self.assertRegex(
  49. source,
  50. re.compile(
  51. r"Set-Alias\s+-Name\s+verilator\s+-Value\s+\$VerilatorNative"
  52. r"\s+-Scope\s+Global\s+-Force",
  53. re.IGNORECASE,
  54. ),
  55. )
  56. def test_repeated_activation_runs_native_verilator_without_file_association(self) -> None:
  57. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  58. toolchain = Path(temporary) / "suite"
  59. native = toolchain / "bin" / "verilator_bin.exe"
  60. native.parent.mkdir(parents=True)
  61. command = f"""
  62. $source = @'
  63. using System;
  64. public static class FakeVerilator {{
  65. public static int Main(string[] args) {{
  66. Console.WriteLine("Fake Verilator 1.0");
  67. return 0;
  68. }}
  69. }}
  70. '@
  71. Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  72. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  73. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  74. $resolved = Get-Command verilator -ErrorAction Stop
  75. verilator --version
  76. $versionExit = $LASTEXITCODE
  77. [pscustomobject]@{{
  78. command_type = [string]$resolved.CommandType
  79. definition = [string]$resolved.Definition
  80. env_verilator = [string]$env:VERILATOR
  81. version_exit = $versionExit
  82. }} | ConvertTo-Json -Compress
  83. """
  84. completed = run_powershell(command)
  85. self.assertEqual(completed.returncode, 0, completed.stderr)
  86. payload = last_json_line(completed.stdout)
  87. self.assertEqual(payload["command_type"], "Alias")
  88. self.assertEqual(Path(str(payload["definition"])).resolve(), native.resolve())
  89. self.assertEqual(Path(str(payload["env_verilator"])).resolve(), native.resolve())
  90. self.assertEqual(payload["version_exit"], 0)
  91. self.assertIn("Fake Verilator 1.0", completed.stdout)
  92. def test_child_powershell_never_resolves_extensionless_verilator_wrapper(self) -> None:
  93. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  94. toolchain = Path(temporary) / "suite"
  95. native = toolchain / "bin" / "verilator_bin.exe"
  96. wrapper = toolchain / "bin" / "verilator"
  97. child_script = Path(temporary) / "child-verilator-check.ps1"
  98. native.parent.mkdir(parents=True)
  99. wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii")
  100. child_script.write_text(
  101. """$ErrorActionPreference = "Stop"
  102. $resolved = Get-Command verilator -ErrorAction Stop
  103. if ([System.IO.Path]::GetFullPath($resolved.Definition) -eq
  104. [System.IO.Path]::GetFullPath($env:EXPECTED_UNSAFE_VERILATOR)) {
  105. Write-Error "child PowerShell resolved the extensionless Verilator wrapper"
  106. exit 91
  107. }
  108. verilator --version
  109. exit $LASTEXITCODE
  110. """,
  111. encoding="utf-8-sig",
  112. )
  113. command = f"""
  114. $ErrorActionPreference = "Stop"
  115. $source = @'
  116. using System;
  117. public static class FakeVerilator {{
  118. public static int Main(string[] args) {{
  119. Console.WriteLine("Fake Verilator 1.0");
  120. return 0;
  121. }}
  122. }}
  123. '@
  124. Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  125. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  126. $env:EXPECTED_UNSAFE_VERILATOR = {ps_literal(wrapper)}
  127. & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
  128. exit $LASTEXITCODE
  129. """
  130. completed = run_powershell(command)
  131. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  132. self.assertIn("Fake Verilator 1.0", completed.stdout)
  133. def test_child_powershell_preserves_verilator_metacharacters_and_exit_code(self) -> None:
  134. arguments = [
  135. "--lint-only",
  136. r"C:\space dir\file.v",
  137. "D=100%",
  138. "bang!name",
  139. "caret^name",
  140. "paren(name)",
  141. "amp&name",
  142. ]
  143. expected = [
  144. base64.b64encode(argument.encode("utf-8")).decode("ascii")
  145. for argument in arguments
  146. ]
  147. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  148. toolchain = Path(temporary) / "suite"
  149. native = toolchain / "bin" / "verilator_bin.exe"
  150. native.parent.mkdir(parents=True)
  151. child_script = Path(temporary) / "child-verilator-argv.ps1"
  152. child_script.write_text(
  153. r"""verilator '--lint-only' 'C:\space dir\file.v' 'D=100%' 'bang!name' 'caret^name' 'paren(name)' 'amp&name'
  154. exit $LASTEXITCODE
  155. """,
  156. encoding="utf-8-sig",
  157. )
  158. command = f"""
  159. $ErrorActionPreference = "Stop"
  160. $source = @'
  161. using System;
  162. using System.Text;
  163. public static class FakeVerilator {{
  164. public static int Main(string[] args) {{
  165. foreach (string argument in args) {{
  166. Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(argument)));
  167. }}
  168. return 37;
  169. }}
  170. }}
  171. '@
  172. Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  173. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  174. & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
  175. exit $LASTEXITCODE
  176. """
  177. completed = run_powershell(command)
  178. self.assertEqual(completed.returncode, 37, completed.stdout + completed.stderr)
  179. observed = [line.strip() for line in completed.stdout.splitlines() if line.strip() in expected]
  180. self.assertEqual(observed, expected)
  181. def test_child_powershell_rejects_verilator_target_outside_toolchain_root(self) -> None:
  182. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  183. root = Path(temporary)
  184. toolchain = root / "suite"
  185. native = toolchain / "bin" / "verilator_bin.exe"
  186. attacker = root / "attacker" / "verilator_bin.exe"
  187. native.parent.mkdir(parents=True)
  188. attacker.parent.mkdir(parents=True)
  189. child_script = root / "child-verilator-target.ps1"
  190. child_script.write_text(
  191. """$env:VERILATOR = $env:UNTRUSTED_VERILATOR
  192. verilator --version
  193. exit $LASTEXITCODE
  194. """,
  195. encoding="utf-8-sig",
  196. )
  197. command = f"""
  198. $ErrorActionPreference = "Stop"
  199. $safeSource = @'
  200. using System;
  201. public static class SafeVerilator {{
  202. public static int Main(string[] args) {{ return 0; }}
  203. }}
  204. '@
  205. $attackerSource = @'
  206. using System;
  207. public static class AttackerVerilator {{
  208. public static int Main(string[] args) {{
  209. Console.WriteLine("UNTRUSTED_VERILATOR_EXECUTED");
  210. return 0;
  211. }}
  212. }}
  213. '@
  214. Add-Type -TypeDefinition $safeSource -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  215. Add-Type -TypeDefinition $attackerSource -OutputAssembly {ps_literal(attacker)} -OutputType ConsoleApplication
  216. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  217. $env:UNTRUSTED_VERILATOR = {ps_literal(attacker)}
  218. & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
  219. exit $LASTEXITCODE
  220. """
  221. completed = run_powershell(command)
  222. self.assertNotEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  223. self.assertNotIn("UNTRUSTED_VERILATOR_EXECUTED", completed.stdout)
  224. def test_extensionless_only_toolchain_fails_before_path_or_command_exposure(self) -> None:
  225. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  226. toolchain = Path(temporary) / "suite"
  227. wrapper = toolchain / "bin" / "verilator"
  228. wrapper.parent.mkdir(parents=True)
  229. wrapper.write_text("extensionless Perl wrapper", encoding="ascii")
  230. command = f"""
  231. $system32 = Join-Path $env:SystemRoot "System32"
  232. $env:PATH = "$system32;$env:SystemRoot"
  233. Remove-Item Env:VERILATOR -ErrorAction SilentlyContinue
  234. $beforePath = $env:PATH
  235. $caught = $null
  236. try {{
  237. & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
  238. }} catch {{
  239. $caught = $_.Exception.Message
  240. }}
  241. $resolved = Get-Command verilator -ErrorAction SilentlyContinue
  242. [pscustomobject]@{{
  243. caught = [string]$caught
  244. path_unchanged = ($env:PATH -ceq $beforePath)
  245. command_found = ($null -ne $resolved)
  246. env_verilator = [string]$env:VERILATOR
  247. }} | ConvertTo-Json -Compress
  248. """
  249. completed = run_powershell(command)
  250. self.assertEqual(completed.returncode, 0, completed.stderr)
  251. payload = last_json_line(completed.stdout)
  252. self.assertIn("native Verilator", str(payload["caught"]))
  253. self.assertTrue(payload["path_unchanged"])
  254. self.assertFalse(payload["command_found"])
  255. self.assertEqual(payload["env_verilator"], "")
  256. def test_cmd_verilator_shim_is_fail_closed_and_never_forwards_arguments(self) -> None:
  257. source = CMD_SHIM.read_text(encoding="ascii")
  258. self.assertNotIn("%*", source)
  259. if CMD is None:
  260. raise unittest.SkipTest("cmd.exe is unavailable")
  261. env = os.environ.copy()
  262. env["PATH"] = os.pathsep.join((str(CMD_SHIM.parent), env.get("PATH", "")))
  263. completed = subprocess.run(
  264. [CMD, "/d", "/s", "/c", "verilator --version"],
  265. cwd=ROOT,
  266. env=env,
  267. text=True,
  268. capture_output=True,
  269. check=False,
  270. timeout=30,
  271. )
  272. self.assertEqual(completed.returncode, 126, completed.stdout + completed.stderr)
  273. self.assertIn("supported only from PowerShell", completed.stderr)
  274. if __name__ == "__main__":
  275. unittest.main()