Repository navigation
Expand file tree
/
Copy pathinstance.py
More file actions
240 lines (208 loc) · 11.2 KB
/
Copy pathinstance.py
File metadata and controls
240 lines (208 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""One wall per Windows user: later launches hand their files to the running wall over a named pipe."""
import ctypes
import json
import logging
import os
import queue
import time
from ctypes import wintypes
from multiprocessing.connection import Client
from multiprocessing.connection import Listener
from multiprocessing.connection import PipeListener
import _winapi
import config as C
log = logging.getLogger("tesserawall")
_k32, _adv = ctypes.WinDLL("kernel32", use_last_error=True), ctypes.WinDLL("advapi32", use_last_error=True)
_k32.OpenProcess.restype = wintypes.HANDLE
_k32.GetCurrentProcess.restype = wintypes.HANDLE
_k32.GetCurrentThread.restype = wintypes.HANDLE
_k32.CloseHandle.argtypes = [wintypes.HANDLE]
_k32.LocalFree.argtypes = [ctypes.c_void_p]
_k32.GetNamedPipeServerProcessId.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)]
_adv.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
_adv.OpenThreadToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.BOOL, ctypes.POINTER(wintypes.HANDLE)]
_adv.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD)]
_adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)]
_adv.ImpersonateNamedPipeClient.argtypes = [wintypes.HANDLE]
TOKEN_QUERY, PROCESS_QUERY_LIMITED_INFORMATION, TOKEN_USER = 0x0008, 0x1000, 1
PIPE_REJECT_REMOTE_CLIENTS, _PIPE_BUFSIZE = 0x8, 8192
def _token_sid(token) -> str | None:
"""The user SID of an access token, as text (S-1-5-21-...)."""
size = wintypes.DWORD()
_adv.GetTokenInformation(token, TOKEN_USER, None, 0, ctypes.byref(size))
if not size.value:
return None
buf = ctypes.create_string_buffer(size.value)
if not _adv.GetTokenInformation(token, TOKEN_USER, buf, size, ctypes.byref(size)):
return None
psid = ctypes.c_void_p.from_buffer(buf).value # TOKEN_USER starts with SID_AND_ATTRIBUTES.Sid
text = wintypes.LPWSTR()
if not _adv.ConvertSidToStringSidW(psid, ctypes.byref(text)):
return None
try:
return text.value
finally:
_k32.LocalFree(text)
def process_sid(pid: int | None = None) -> str | None:
"""The user a process runs as (this one if pid is None); None if Windows won't say, as for another
user's process."""
if pid is None:
proc = _k32.GetCurrentProcess()
else:
proc = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if not proc:
return None
token = wintypes.HANDLE()
try:
if not _adv.OpenProcessToken(proc, TOKEN_QUERY, ctypes.byref(token)):
return None
try:
return _token_sid(token)
finally:
_k32.CloseHandle(token)
finally:
if pid is not None:
_k32.CloseHandle(proc)
def pipe_server_sid(handle) -> str | None:
"""The user running the server end of a connected pipe."""
pid = wintypes.ULONG()
if not _k32.GetNamedPipeServerProcessId(handle, ctypes.byref(pid)):
return None
return process_sid(pid.value)
def pipe_client_sid(handle) -> str | None:
"""The user on the client end of a pipe, by impersonating it (it must have written first). Unlike the
client's process id, this also holds for a client on another PC."""
if not _adv.ImpersonateNamedPipeClient(handle):
return None
token = wintypes.HANDLE()
try:
if not _adv.OpenThreadToken(_k32.GetCurrentThread(), TOKEN_QUERY, True, ctypes.byref(token)):
return None
try:
return _token_sid(token)
finally:
_k32.CloseHandle(token)
finally:
_adv.RevertToSelf()
def _control_pipe() -> str:
"""One wall per Windows user and sign-in session, named by the user's SID: unique, unlike user names
(john.doe and john_doe once mapped to the same pipe), and the same for every launch of this user."""
session = wintypes.DWORD()
if not _k32.ProcessIdToSessionId(os.getpid(), ctypes.byref(session)):
session.value = 0
who = MY_SID or "".join(ch if ch.isalnum() else "_" for ch in (os.environ.get("USERNAME") or "user"))
return r"\\.\pipe\tesserawall-control-" + f"{who}-{session.value}"
class _SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p),
("bInheritHandle", wintypes.BOOL)]
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.ULONG)]
_k32.CreateNamedPipeW.restype = wintypes.HANDLE
_k32.CreateNamedPipeW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
ctypes.POINTER(_SecurityAttributes)]
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
class OwnerOnlyPipeListener(PipeListener):
"""multiprocessing's pipe listener, but each pipe instance is created with a DACL that lets only this
user connect, and refuses clients on other computers. With the default DACL any local account could
connect (for reading) and hold the listener (security audit T5); the checks in claim_control_pipe and
listen() stay as a second line. Clients are still multiprocessing's own Client: same message pipe."""
def _new_handle(self, first=False):
if not getattr(self, "_sa", None):
sd = ctypes.c_void_p()
# D:P = a protected DACL (nothing inherited); GA = full access, for this user's SID only.
if not _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(f"D:P(A;;GA;;;{MY_SID})", 1,
ctypes.byref(sd), None):
raise ctypes.WinError(ctypes.get_last_error())
self._sd = sd # kept for the life of the listener
self._sa = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), sd, False)
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
if first:
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
mode = (_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | _winapi.PIPE_WAIT
| PIPE_REJECT_REMOTE_CLIENTS)
handle = _k32.CreateNamedPipeW(self._address, flags, mode, _winapi.PIPE_UNLIMITED_INSTANCES,
_PIPE_BUFSIZE, _PIPE_BUFSIZE, _winapi.NMPWAIT_WAIT_FOREVER,
ctypes.byref(self._sa))
if handle == INVALID_HANDLE_VALUE or not handle:
raise ctypes.WinError(ctypes.get_last_error())
return handle
def new_listener():
"""The control pipe's listener: owner-only when this user's SID is known, else multiprocessing's own."""
if MY_SID:
return OwnerOnlyPipeListener(CONTROL_PIPE)
return Listener(CONTROL_PIPE, family="AF_PIPE")
MY_SID = process_sid()
CONTROL_PIPE = _control_pipe()
# Another user's program holds our pipe name: this launch runs a wall of its own, taking no hand-overs.
ALONE = object()
# Gathering a multi-file right-click (see gather_batch), in seconds after this launch became the wall.
BATCH_MIN, BATCH_QUIET, BATCH_MAX = 0.5, 0.35, 3.0
LISTEN_WAIT = 2.0 # seconds a connected launch has to send its paths
def claim_control_pipe(paths: list):
"""Become the one running tesserawall, or hand `paths` to the one that is. Returns the control-pipe
listener if this process is now the wall, None if the paths were handed over, or ALONE if a program
of another user holds the pipe name (this process is then a wall that takes no hand-overs).
Explorer starts one process per selected file (right-click verb, Send To, drop on a shortcut),
all at the same moment, so this must be race-free. It is because creating the listener is the
claim: Python creates the pipe's first instance with FILE_FLAG_FIRST_PIPE_INSTANCE, so exactly
one process succeeds and the rest get "access denied" and retry as clients. The claim is made
before any window opens, so the winner can accept connections within milliseconds."""
deadline = time.monotonic() + 15
while True:
try: # an empty list just detects a running wall
with Client(CONTROL_PIPE, family="AF_PIPE") as c:
owner = pipe_server_sid(c.fileno())
if MY_SID and owner != MY_SID: # someone else made the pipe first: send them nothing
log.warning("control pipe is held by another user (%s); this wall runs on its own", owner)
return ALONE
c.send_bytes(json.dumps(paths).encode("utf-8")) # JSON, never pickle (see listen())
return None
except OSError:
pass
try:
return new_listener()
except OSError: # another launch claimed it between our two attempts: send to it instead
if time.monotonic() > deadline:
raise
time.sleep(0.05)
def gather_batch(incoming: queue.Queue, claimed_at: float) -> list:
"""Collect files that sibling launches hand over just after this one became the wall.
Right-click on several files starts one process per file at the same moment; the others arrive
here in a random order within a fraction of a second. Waits until nothing has arrived for
BATCH_QUIET seconds (at least BATCH_MIN after the claim, at most BATCH_MAX)."""
got, last = [], claimed_at
while True:
try:
got.append(incoming.get(timeout=0.03))
last = time.monotonic()
continue
except queue.Empty:
pass
now = time.monotonic()
if now - claimed_at >= BATCH_MAX or (now - claimed_at >= BATCH_MIN and now - last >= BATCH_QUIET):
return got
def listen(listener: Listener, incoming: queue.Queue):
"""Receive paths from later launches (Send To / shortcut drop while a wall is running)."""
while True:
try:
with listener.accept() as conn:
if not conn.poll(LISTEN_WAIT): # a client that connects and never writes must not stall us
log.warning("listener: a client sent nothing; dropped")
continue
# Raw bytes holding a JSON list of paths. Never conn.recv(): that unpickles, and a
# pickle from another local program could run code inside the wall.
data = conn.recv_bytes(1 << 20)
sender = pipe_client_sid(conn.fileno())
if MY_SID and sender != MY_SID: # only this user's own launches may add videos
log.warning("listener: ignored a hand-over from another user (%s)", sender)
continue
paths = json.loads(data.decode("utf-8"))
if isinstance(paths, list):
for p in paths[:C.MAX_VIDEOS * 4]:
if isinstance(p, str):
incoming.put(p)
except Exception as e: # a broken client must not kill the listener
log.error("listener: %s", e)
time.sleep(0.5) # an error that repeats (a closed pipe) must not spin a core and flood the log