4
0

remote_control.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #!/usr/bin/env python3
  2. """Independent standard-library client for the opt-in LYNX Remote Control API.
  3. Defaults to read-only status. An edit requires an explicitly saved project
  4. snapshot and a JSON Patch file; writes are sent once and are never retried.
  5. """
  6. import argparse
  7. import base64
  8. import hashlib
  9. import hmac
  10. import json
  11. import os
  12. from pathlib import Path
  13. import secrets
  14. import socket
  15. import stat
  16. import sys
  17. PROTOCOL = "lynx-control/1"
  18. MAX_FRAME = 1024 * 1024
  19. MAX_DOCUMENT = 64 * 1024 * 1024
  20. def require(condition, message):
  21. if not condition:
  22. raise RuntimeError(message)
  23. def default_discovery():
  24. if os.environ.get("LYNX_CONTROL_DISCOVERY"):
  25. return Path(os.environ["LYNX_CONTROL_DISCOVERY"])
  26. if os.environ.get("LYNX_PROFILE_DIR"):
  27. return Path(os.environ["LYNX_PROFILE_DIR"]) / "LYNX/control/connection.json"
  28. if os.name == "nt":
  29. require(bool(os.environ.get("APPDATA")), "Set --discovery when APPDATA is unavailable")
  30. folder = Path(os.environ["APPDATA"]) / "LYNX"
  31. elif sys.platform == "darwin":
  32. folder = Path.home() / "Library/Application Support/LYNX"
  33. else:
  34. config = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
  35. if not config.is_absolute():
  36. config = Path.home() / ".config"
  37. folder = config / "LYNX"
  38. return folder / "control/connection.json"
  39. def windows_private_bytes(path):
  40. """Open the leaf without following a reparse point; inspect that same handle's ACL."""
  41. import ctypes as c
  42. from ctypes import wintypes as w
  43. kernel = c.WinDLL("kernel32", use_last_error=True)
  44. security = c.WinDLL("advapi32", use_last_error=True)
  45. kernel.CreateFileW.argtypes = [w.LPCWSTR, w.DWORD, w.DWORD, c.c_void_p, w.DWORD, w.DWORD, w.HANDLE]
  46. kernel.CreateFileW.restype = w.HANDLE
  47. kernel.CloseHandle.argtypes = [w.HANDLE]
  48. kernel.GetCurrentProcess.restype = w.HANDLE
  49. kernel.LocalFree.argtypes = [c.c_void_p]
  50. kernel.GetFileInformationByHandleEx.argtypes = [w.HANDLE, c.c_int, c.c_void_p, w.DWORD]
  51. kernel.ReadFile.argtypes = [w.HANDLE, c.c_void_p, w.DWORD, c.POINTER(w.DWORD), c.c_void_p]
  52. security.OpenProcessToken.argtypes = [w.HANDLE, w.DWORD, c.POINTER(w.HANDLE)]
  53. security.GetTokenInformation.argtypes = [w.HANDLE, c.c_int, c.c_void_p, w.DWORD, c.POINTER(w.DWORD)]
  54. security.GetSecurityInfo.argtypes = [w.HANDLE, c.c_int, w.DWORD, c.POINTER(c.c_void_p),
  55. c.c_void_p, c.POINTER(c.c_void_p), c.c_void_p, c.POINTER(c.c_void_p)]
  56. security.EqualSid.argtypes = [c.c_void_p, c.c_void_p]
  57. security.GetAclInformation.argtypes = [c.c_void_p, c.c_void_p, w.DWORD, c.c_int]
  58. security.GetAce.argtypes = [c.c_void_p, w.DWORD, c.POINTER(c.c_void_p)]
  59. security.ConvertSidToStringSidW.argtypes = [c.c_void_p, c.POINTER(w.LPWSTR)]
  60. handle = kernel.CreateFileW(str(path), 0x80000000 | 0x00020000, 7, None, 3, 0x00200000, None)
  61. require(handle != w.HANDLE(-1).value, "Cannot open the private discovery file")
  62. descriptor = c.c_void_p()
  63. process_token = w.HANDLE()
  64. try:
  65. attrs = (w.DWORD * 2)()
  66. require(kernel.GetFileInformationByHandleEx(handle, 9, attrs, c.sizeof(attrs)), "Cannot inspect discovery attributes")
  67. require(not attrs[0] & (0x400 | 0x10), "Discovery must be a regular file without a reparse point")
  68. owner, acl = c.c_void_p(), c.c_void_p()
  69. require(security.GetSecurityInfo(handle, 1, 0x5, c.byref(owner), None, c.byref(acl), None, c.byref(descriptor)) == 0,
  70. "Cannot inspect discovery ownership and DACL")
  71. require(acl.value, "Discovery must have an explicit private DACL")
  72. require(security.OpenProcessToken(kernel.GetCurrentProcess(), 8, c.byref(process_token)), "Cannot inspect current user")
  73. needed = w.DWORD()
  74. security.GetTokenInformation(process_token, 1, None, 0, c.byref(needed))
  75. token = c.create_string_buffer(needed.value)
  76. require(security.GetTokenInformation(process_token, 1, token, needed, c.byref(needed)), "Cannot inspect current user SID")
  77. current_sid = c.cast(token, c.POINTER(c.c_void_p))[0]
  78. require(security.EqualSid(owner, current_sid), "Discovery must belong to the current user")
  79. info = (w.DWORD * 3)()
  80. require(security.GetAclInformation(acl, info, c.sizeof(info), 2), "Cannot inspect discovery DACL entries")
  81. for index in range(info[0]):
  82. ace = c.c_void_p()
  83. require(security.GetAce(acl, index, c.byref(ace)), "Cannot inspect a discovery DACL entry")
  84. header = c.cast(ace, c.POINTER(c.c_ubyte))
  85. if header[1] & 0x08: # inherit-only ACE does not grant access to this file
  86. continue
  87. require(header[0] in (0, 1), "Unsupported discovery DACL entry")
  88. if header[0] == 1: # deny ACE grants nobody access
  89. continue
  90. sid = c.c_void_p(ace.value + 8)
  91. if security.EqualSid(sid, current_sid):
  92. continue
  93. readable = w.LPWSTR()
  94. require(security.ConvertSidToStringSidW(sid, c.byref(readable)), "Cannot inspect discovery DACL SID")
  95. try:
  96. require(readable.value == "S-1-5-18", "Discovery grants access to another user or group")
  97. finally:
  98. kernel.LocalFree(c.cast(readable, c.c_void_p))
  99. data = c.create_string_buffer(16385)
  100. count = w.DWORD()
  101. require(kernel.ReadFile(handle, data, len(data), c.byref(count), None), "Cannot read discovery")
  102. require(count.value <= 16384, "Discovery exceeds 16 KiB")
  103. return data.raw[:count.value]
  104. finally:
  105. if process_token:
  106. kernel.CloseHandle(process_token)
  107. if descriptor:
  108. kernel.LocalFree(descriptor)
  109. kernel.CloseHandle(handle)
  110. def private_bytes(path):
  111. require(path.is_absolute(), "Discovery path must be absolute")
  112. if os.name == "nt":
  113. return windows_private_bytes(path)
  114. fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
  115. try:
  116. info = os.fstat(fd)
  117. require(stat.S_ISREG(info.st_mode) and info.st_uid == os.geteuid() and not info.st_mode & 0o077,
  118. "Discovery must be a regular file owned by this user with mode 0600")
  119. require(info.st_size <= 16384, "Discovery exceeds 16 KiB")
  120. data = os.read(fd, 16385)
  121. require(len(data) <= 16384, "Discovery exceeds 16 KiB")
  122. return data
  123. finally:
  124. os.close(fd)
  125. def lower_hex(value, size):
  126. return isinstance(value, str) and len(value) == size and all(c in "0123456789abcdef" for c in value)
  127. def bounded_json(data, limit, depth):
  128. require(len(data) <= limit, "Server frame exceeds its size bound")
  129. level, quoted, escaped = 0, False, False
  130. for byte in data:
  131. if quoted:
  132. if escaped:
  133. escaped = False
  134. elif byte == 92:
  135. escaped = True
  136. elif byte == 34:
  137. quoted = False
  138. elif byte == 34:
  139. quoted = True
  140. elif byte in (91, 123):
  141. level += 1
  142. require(level <= depth, "Server frame exceeds its nesting bound")
  143. elif byte in (93, 125):
  144. level -= 1
  145. require(level >= 0, "Server frame nesting is invalid")
  146. return json.loads(data)
  147. class Client:
  148. def __init__(self, discovery):
  149. record = json.loads(private_bytes(discovery))
  150. require(isinstance(record, dict), "Discovery must be an object")
  151. require(record.get("protocol") == PROTOCOL and record.get("host") == "127.0.0.1", "Incompatible discovery protocol or address")
  152. require(type(record.get("port")) is int and 0 < record["port"] <= 65535, "Invalid discovery port")
  153. require(type(record.get("pid")) is int and record["pid"] > 0, "Invalid discovery PID")
  154. require(lower_hex(record.get("token"), 64), "Invalid discovery credential format")
  155. self.record = record
  156. def call(self, operation, args=None, *, write=False):
  157. token = self.record["token"]
  158. nonce = secrets.token_hex(16)
  159. def proof(role, server):
  160. message = f"{PROTOCOL}\n{role}\n{nonce}\n{server}".encode("ascii")
  161. return hmac.new(token.encode("ascii"), message, hashlib.sha256).hexdigest()
  162. def send(connection, value, limit):
  163. data = json.dumps(value, separators=(",", ":"), allow_nan=False).encode("utf-8")
  164. require(len(data) <= limit, "Request exceeds its size bound")
  165. connection.sendall(data + b"\n")
  166. def frame(stream, limit, depth):
  167. data = stream.readline(limit + 2)
  168. require(data.endswith(b"\n"), "Missing or oversized server frame")
  169. value = bounded_json(data[:-1], limit, depth)
  170. require(isinstance(value, dict), "Server frame must be an object")
  171. return value
  172. with socket.create_connection(("127.0.0.1", self.record["port"]), timeout=2) as connection:
  173. connection.settimeout(2)
  174. with connection.makefile("rb") as stream:
  175. send(connection, {"type": "hello", "protocol": PROTOCOL, "nonce": nonce}, 1024)
  176. challenge = frame(stream, 1024, 8)
  177. server = challenge.get("nonce")
  178. require(challenge.get("type") == "challenge" and challenge.get("protocol") == PROTOCOL
  179. and lower_hex(server, 32), "Invalid server challenge")
  180. require(isinstance(challenge.get("proof"), str)
  181. and hmac.compare_digest(challenge["proof"], proof("server", server)),
  182. "Server proof failed; no client proof or operation was sent")
  183. send(connection, {"type": "auth", "proof": proof("client", server)}, 1024)
  184. ready = frame(stream, 1024, 8)
  185. require(ready.get("type") == "ready" and ready.get("protocol") == PROTOCOL, "Client authentication refused")
  186. connection.settimeout(70)
  187. try:
  188. send(connection, {"op": operation, "args": args or {}}, MAX_FRAME)
  189. response = frame(stream, MAX_FRAME, 64)
  190. except (OSError, ValueError, RuntimeError) as error:
  191. if write:
  192. raise RuntimeError("The write outcome may be unknown. Inspect the project before any retry.") from error
  193. raise
  194. if response.get("ok") is not True:
  195. message = str(response.get("error", "Operation failed")).replace(token, "[redacted]")
  196. if response.get("uncertain") is True:
  197. message += " Inspect the project; do not repeat this write blindly."
  198. raise RuntimeError(message)
  199. return response["result"]
  200. def read_project(self):
  201. request, chunks, expected = {}, [], None
  202. while True:
  203. page = self.call("project.read", request)
  204. identity = {key: page[key] for key in ("snapshotId", "documentHash", "projectId", "controlEpoch", "revision", "totalBytes")}
  205. require(expected is None or identity == expected, "Project pages changed snapshot identity")
  206. expected = identity
  207. require(page.get("encoding") == "base64" and page.get("offset") == sum(map(len, chunks)), "Invalid project page offset/encoding")
  208. require(type(page["totalBytes"]) is int and 0 <= page["totalBytes"] <= MAX_DOCUMENT, "Invalid project size")
  209. chunk = base64.b64decode(page["data"], validate=True)
  210. require(len(chunk) <= 65536, "Oversized project page")
  211. chunks.append(chunk)
  212. size = sum(map(len, chunks))
  213. require(size <= page["totalBytes"], "Project pages exceed declared document size")
  214. if "nextOffset" not in page:
  215. require(size == page["totalBytes"], "Incomplete project document")
  216. break
  217. require(chunk and page["nextOffset"] == size, "Project page made no progress")
  218. request = {"snapshotId": page["snapshotId"], "expectedDocumentHash": page["documentHash"], "offset": size}
  219. document = b"".join(chunks)
  220. require(hashlib.sha256(document).hexdigest() == expected["documentHash"], "Project document hash differs")
  221. bounded_json(document, MAX_DOCUMENT, 64)
  222. return document, expected
  223. def write_new(path, data):
  224. fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
  225. with os.fdopen(fd, "wb") as output:
  226. output.write(data)
  227. def main():
  228. parser = argparse.ArgumentParser(description=__doc__)
  229. parser.add_argument("--discovery", type=Path)
  230. commands = parser.add_subparsers(dest="command")
  231. commands.add_parser("status")
  232. commands.add_parser("describe")
  233. commands.add_parser("stop")
  234. changes = commands.add_parser("changes")
  235. changes.add_argument("--from-revision", type=int, required=True)
  236. read = commands.add_parser("read")
  237. read.add_argument("--output", type=Path, required=True)
  238. read.add_argument("--metadata", type=Path, required=True)
  239. edit = commands.add_parser("edit")
  240. edit.add_argument("--snapshot", type=Path, required=True)
  241. edit.add_argument("--patch", type=Path, required=True)
  242. options = parser.parse_args()
  243. client = Client(options.discovery or default_discovery())
  244. if options.command == "read":
  245. document, metadata = client.read_project()
  246. require(not options.output.exists() and not options.metadata.exists(), "Choose new output and metadata file names")
  247. write_new(options.output, document)
  248. write_new(options.metadata, (json.dumps(metadata, indent=2) + "\n").encode())
  249. print("Saved a complete project snapshot and its edit fence.")
  250. return
  251. if options.command == "edit":
  252. metadata = json.loads(options.snapshot.read_bytes())
  253. patch_data = options.patch.read_bytes()
  254. patch = bounded_json(patch_data, MAX_FRAME - 4096, 64)
  255. require(isinstance(patch, list) and 1 <= len(patch) <= 128, "Patch must contain 1..128 operations")
  256. result = client.call("project.edit", {
  257. "snapshotId": metadata["snapshotId"], "expectedDocumentHash": metadata["documentHash"], "patch": patch,
  258. "expectedProjectId": metadata["projectId"], "expectedEpoch": metadata["controlEpoch"],
  259. "expectedRevision": metadata["revision"],
  260. }, write=True)
  261. elif options.command == "describe":
  262. result = client.call("api.describe")
  263. elif options.command == "changes":
  264. result = client.call("changes", {"fromRevision": options.from_revision})
  265. elif options.command == "stop":
  266. result = client.call("transport.stop", write=True)
  267. else:
  268. result = client.call("status")
  269. print(json.dumps(result, indent=2))
  270. if __name__ == "__main__":
  271. try:
  272. main()
  273. except (OSError, ValueError, KeyError, RuntimeError) as error:
  274. print(str(error), file=sys.stderr)
  275. sys.exit(1)