| 1 |
"""Run a command on Windows with symbolic-link creation denied, and report why it is or is not denied. |
| 2 |
|
| 3 |
Windows grants symlink creation through two independent paths, so closing one proves nothing. A process holding |
| 4 |
SeCreateSymbolicLinkPrivilege may always create them; separately, Developer Mode lets an unprivileged process create |
| 5 |
them through SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE. The CI job clears the Developer Mode registry value, and |
| 6 |
this script removes the privilege from its own token. |
| 7 |
|
| 8 |
SE_PRIVILEGE_REMOVED is documented as irreversible, with checks for a removed privilege returning |
| 9 |
STATUS_PRIVILEGE_NOT_HELD, which is the guarantee this relies on. The documentation does not say whether a child |
| 10 |
inherits the removal or whether clearing Developer Mode needs a reboot, so this reports what it observes rather |
| 11 |
than assuming. Read those lines in the job log before trusting the job. |
| 12 |
|
| 13 |
Usage: python deny_symlink.py <command> [args...] |
| 14 |
""" |
| 15 |
|
| 16 |
from __future__ import annotations |
| 17 |
|
| 18 |
import ctypes |
| 19 |
import subprocess # ruff:ignore[suspicious-subprocess-import] # launching the suite is this script's whole job |
| 20 |
import sys |
| 21 |
import tempfile |
| 22 |
from ctypes import wintypes |
| 23 |
from pathlib import Path |
| 24 |
from typing import Final |
| 25 |
|
| 26 |
_TOKEN_ADJUST_PRIVILEGES: Final[int] = 0x0020 |
| 27 |
_TOKEN_QUERY: Final[int] = 0x0008 |
| 28 |
_SE_PRIVILEGE_REMOVED: Final[int] = 0x0004 |
| 29 |
_ERROR_NOT_ALL_ASSIGNED: Final[int] = 1300 |
| 30 |
_PRIVILEGE: Final[str] = "SeCreateSymbolicLinkPrivilege" |
| 31 |
|
| 32 |
|
| 33 |
class _Luid(ctypes.Structure): |
| 34 |
_fields_ = (("low_part", wintypes.DWORD), ("high_part", wintypes.LONG)) |
| 35 |
|
| 36 |
|
| 37 |
class _LuidAndAttributes(ctypes.Structure): |
| 38 |
_fields_ = (("luid", _Luid), ("attributes", wintypes.DWORD)) |
| 39 |
|
| 40 |
|
| 41 |
class _TokenPrivileges(ctypes.Structure): |
| 42 |
_fields_ = (("privilege_count", wintypes.DWORD), ("privileges", _LuidAndAttributes * 1)) |
| 43 |
|
| 44 |
|
| 45 |
def main() -> int: |
| 46 |
if sys.platform != "win32": |
| 47 |
print("deny_symlink only applies to Windows") |
| 48 |
return 1 |
| 49 |
|
| 50 |
print(f"developer mode: {_developer_mode()}") |
| 51 |
print(f"{_PRIVILEGE} before: {_privilege_state()}") |
| 52 |
print(f"symlink before: {_can_symlink()}") |
| 53 |
|
| 54 |
print(f"removal reported: {_remove_privilege()}") |
| 55 |
print(f"{_PRIVILEGE} after: {_privilege_state()}") |
| 56 |
print(f"symlink after (this process): {_can_symlink()}") |
| 57 |
|
| 58 |
child = subprocess.run( |
| 59 |
[sys.executable, "-c", _CHILD_PROBE], |
| 60 |
capture_output=True, |
| 61 |
text=True, |
| 62 |
check=False, |
| 63 |
) |
| 64 |
print(f"symlink after (child process): {child.stdout.strip() or child.stderr.strip()}") |
| 65 |
|
| 66 |
return subprocess.run(sys.argv[1:], check=False).returncode |
| 67 |
|
| 68 |
|
| 69 |
def _developer_mode() -> str: |
| 70 |
# ty needs the platform narrowed to see the Windows-only members from any host. |
| 71 |
assert sys.platform == "win32" |
| 72 |
import winreg # ruff:ignore[import-outside-top-level] Windows-only, and this module already refuses to run elsewhere |
| 73 |
|
| 74 |
try: |
| 75 |
with winreg.OpenKey( |
| 76 |
winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" |
| 77 |
) as key: |
| 78 |
return str(winreg.QueryValueEx(key, "AllowDevelopmentWithoutDevLicense")[0]) |
| 79 |
except OSError as error: |
| 80 |
return f"unreadable ({error})" |
| 81 |
|
| 82 |
|
| 83 |
def _privilege_state() -> str: |
| 84 |
result = subprocess.run( |
| 85 |
["whoami", "/priv"], # ruff:ignore[start-process-with-partial-path] resolved from PATH on every Windows image |
| 86 |
capture_output=True, |
| 87 |
text=True, |
| 88 |
check=False, |
| 89 |
) |
| 90 |
for line in result.stdout.splitlines(): |
| 91 |
if _PRIVILEGE in line: |
| 92 |
return line.strip() |
| 93 |
return "absent from the token" |
| 94 |
|
| 95 |
|
| 96 |
def _remove_privilege() -> str: |
| 97 |
# ty needs the platform narrowed to see the Windows-only members from any host. |
| 98 |
assert sys.platform == "win32" |
| 99 |
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True) |
| 100 |
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) |
| 101 |
# Declare the signatures: GetCurrentProcess returns the pseudo-handle (HANDLE)-1, and ctypes' default c_int restype |
| 102 |
# truncates it on 64-bit, so OpenProcessToken is handed a bad handle and fails with ERROR_INVALID_HANDLE. |
| 103 |
kernel32.GetCurrentProcess.argtypes = () |
| 104 |
kernel32.GetCurrentProcess.restype = wintypes.HANDLE |
| 105 |
advapi32.OpenProcessToken.argtypes = (wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)) |
| 106 |
advapi32.OpenProcessToken.restype = wintypes.BOOL |
| 107 |
advapi32.LookupPrivilegeValueW.argtypes = (wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(_Luid)) |
| 108 |
advapi32.LookupPrivilegeValueW.restype = wintypes.BOOL |
| 109 |
advapi32.AdjustTokenPrivileges.argtypes = ( |
| 110 |
wintypes.HANDLE, |
| 111 |
wintypes.BOOL, |
| 112 |
ctypes.POINTER(_TokenPrivileges), |
| 113 |
wintypes.DWORD, |
| 114 |
ctypes.c_void_p, |
| 115 |
ctypes.c_void_p, |
| 116 |
) |
| 117 |
advapi32.AdjustTokenPrivileges.restype = wintypes.BOOL |
| 118 |
|
| 119 |
token = wintypes.HANDLE() |
| 120 |
if not advapi32.OpenProcessToken( |
| 121 |
kernel32.GetCurrentProcess(), _TOKEN_ADJUST_PRIVILEGES | _TOKEN_QUERY, ctypes.byref(token) |
| 122 |
): |
| 123 |
return f"OpenProcessToken failed with {ctypes.get_last_error()}" |
| 124 |
|
| 125 |
luid = _Luid() |
| 126 |
if not advapi32.LookupPrivilegeValueW(None, _PRIVILEGE, ctypes.byref(luid)): |
| 127 |
return f"LookupPrivilegeValue failed with {ctypes.get_last_error()}" |
| 128 |
|
| 129 |
privileges = _TokenPrivileges(1, (_LuidAndAttributes * 1)(_LuidAndAttributes(luid, _SE_PRIVILEGE_REMOVED))) |
| 130 |
if not advapi32.AdjustTokenPrivileges(token, False, ctypes.byref(privileges), 0, None, None): # ruff:ignore[boolean-positional-value-in-call] |
| 131 |
return f"AdjustTokenPrivileges failed with {ctypes.get_last_error()}" |
| 132 |
# The call reports success even when the token never held the privilege, so read the code it leaves behind. |
| 133 |
if (code := ctypes.get_last_error()) == _ERROR_NOT_ALL_ASSIGNED: |
| 134 |
return "the token did not hold the privilege" |
| 135 |
return "removed" if code == 0 else f"unexpected code {code}" |
| 136 |
|
| 137 |
|
| 138 |
_CHILD_PROBE: Final[str] = """ |
| 139 |
import pathlib, tempfile |
| 140 |
|
| 141 |
with tempfile.TemporaryDirectory() as directory: |
| 142 |
target = pathlib.Path(directory, "target") |
| 143 |
target.touch() |
| 144 |
try: |
| 145 |
pathlib.Path(directory, "link").symlink_to(target) |
| 146 |
except OSError as error: |
| 147 |
print(f"False (WinError {error.winerror})") |
| 148 |
else: |
| 149 |
print("True") |
| 150 |
""" |
| 151 |
|
| 152 |
|
| 153 |
def _can_symlink() -> str: |
| 154 |
# ty needs the platform narrowed to see the Windows-only members from any host. |
| 155 |
assert sys.platform == "win32" |
| 156 |
with tempfile.TemporaryDirectory() as directory: |
| 157 |
target = Path(directory, "target") |
| 158 |
target.touch() |
| 159 |
try: |
| 160 |
Path(directory, "link").symlink_to(target) |
| 161 |
except OSError as error: |
| 162 |
return f"False (WinError {error.winerror})" |
| 163 |
return "True" |
| 164 |
|
| 165 |
|
| 166 |
if __name__ == "__main__": |
| 167 |
raise SystemExit(main()) |