Program.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.IO.Pipes;
  6. using System.Numerics;
  7. using System.Runtime.InteropServices;
  8. using System.Reflection;
  9. using System.Security.AccessControl;
  10. using System.Security.Cryptography;
  11. using System.Security.Principal;
  12. using System.Text;
  13. using System.Threading;
  14. using Microsoft.Win32.SafeHandles;
  15. internal static class Program
  16. {
  17. private const string Protocol = "ZCODE_BROWSER_IMPORT_V1";
  18. private const string HelperVersion = "2";
  19. private const int PipeTimeoutMs = 60000;
  20. private const int BrokerLifetimeMs = 90000;
  21. private const int ControllerLifetimeMs = 75000;
  22. private const int MaxProtocolLineLength = 1024 * 1024;
  23. private const string ChromeCngProvider = "Microsoft Software Key Storage Provider";
  24. private const string ChromeCngKey = "Google Chromekey1";
  25. private static readonly byte[] Flag1Key = Hex(
  26. "B31C6E241AC846728DA9C1FAC4936651CFFB944D143AB816276BCC6DA0284787");
  27. private static readonly byte[] Flag2Key = Hex(
  28. "E98F37D7F4E1FA433D19304DC2258042090E2D1D7EEA7670D41F738D08729660");
  29. private static readonly byte[] Flag3Mask = Hex(
  30. "CCF8A1CEC56605B8517552BA1A2D061C03A29E90274FB2FCF59BA4B75C392390");
  31. private static Dictionary<string, string> serviceArguments;
  32. private static ServiceMainDelegate serviceMainDelegate;
  33. private static ServiceControlHandlerDelegate serviceControlHandlerDelegate;
  34. private static IntPtr serviceStatusHandle;
  35. private static readonly ManualResetEvent serviceStopEvent = new ManualResetEvent(false);
  36. private static NamedPipeServerStream activeServicePipe;
  37. private static int Main(string[] args)
  38. {
  39. try
  40. {
  41. if (HasArgument(args, "--version"))
  42. {
  43. string[] buildIdentity = GetBuildIdentity();
  44. Console.Out.WriteLine(
  45. "ZCODE_BROWSER_IMPORT_HELPER\t" + HelperVersion + "\t" + GetProcessArchitecture() +
  46. "\t" + buildIdentity[0] + "\t" + buildIdentity[1]);
  47. return 0;
  48. }
  49. if (HasArgument(args, "--broker"))
  50. {
  51. RunBroker(ParseArguments(args));
  52. return 0;
  53. }
  54. if (HasArgument(args, "--elevated"))
  55. {
  56. RunElevated(ParseArguments(args));
  57. return 0;
  58. }
  59. if (HasArgument(args, "--service"))
  60. {
  61. serviceArguments = ParseArguments(args);
  62. RunServiceDispatcher();
  63. return 0;
  64. }
  65. return 2;
  66. }
  67. catch
  68. {
  69. // 安全边界:异常只转换为稳定错误码,绝不把密钥、路径或系统异常文本写入输出。
  70. if (!HasArgument(args, "--service"))
  71. {
  72. WriteError("helper_failed");
  73. }
  74. return 1;
  75. }
  76. }
  77. private static void RunBroker(Dictionary<string, string> args)
  78. {
  79. int hostPid = ParsePositiveInt(RequireArgument(args, "--parent-pid"));
  80. using (ManualResetEvent completed = new ManualResetEvent(false))
  81. {
  82. Thread watchdog = new Thread(() => MonitorHostAndDeadline(hostPid, completed));
  83. watchdog.IsBackground = true;
  84. watchdog.Start();
  85. try { RunBrokerCore(); }
  86. finally
  87. {
  88. completed.Set();
  89. watchdog.Join(1000);
  90. }
  91. }
  92. }
  93. private static void RunBrokerCore()
  94. {
  95. string request;
  96. string pipeName;
  97. string token;
  98. NamedPipeServerStream pipe;
  99. try
  100. {
  101. request = ReadBoundedLine(Console.In);
  102. ValidateImportRequest(request);
  103. pipeName = "zcode-browser-import-broker-" + Guid.NewGuid().ToString("N");
  104. token = CreateToken();
  105. pipe = CreatePipeServer(pipeName, true);
  106. }
  107. catch
  108. {
  109. // Bugfix 原因:broker 初始化异常原先统一落到 helper_failed,无法区分输入/控制管道尚未建立的失败阶段。
  110. WriteError("broker_initialization_failed");
  111. return;
  112. }
  113. // 凭据切换式 UAC 会以另一个管理员 SID 启动 elevated controller;控制管道允许管理员,
  114. // broker 侧用启动后拿到的精确 PID 和随机 token 绑定本次实例,controller 再反向校验 broker 映像路径。
  115. using (pipe)
  116. {
  117. Process elevated;
  118. try
  119. {
  120. ProcessStartInfo startInfo = new ProcessStartInfo
  121. {
  122. FileName = GetSelfPath(),
  123. Arguments = "--elevated --pipe " + pipeName + " --token " + token +
  124. " --parent-pid " + Process.GetCurrentProcess().Id,
  125. UseShellExecute = true,
  126. Verb = "runas",
  127. WindowStyle = ProcessWindowStyle.Hidden,
  128. };
  129. elevated = Process.Start(startInfo);
  130. }
  131. catch (System.ComponentModel.Win32Exception error)
  132. {
  133. if (error.NativeErrorCode == 1223)
  134. {
  135. WriteError("elevation_cancelled");
  136. return;
  137. }
  138. WriteError("elevation_failed");
  139. return;
  140. }
  141. if (elevated == null)
  142. {
  143. WriteError("elevation_failed");
  144. return;
  145. }
  146. using (elevated)
  147. {
  148. try
  149. {
  150. if (!WaitForConnection(pipe, PipeTimeoutMs))
  151. {
  152. TryTerminate(elevated);
  153. WriteError("timeout");
  154. return;
  155. }
  156. // Bugfix 原因:标准用户通过 UAC 切换到其他管理员账号后,普通 broker 无权跨账号读取
  157. // 高完整性 controller 的映像路径;这里仍用 Process.Start 返回的精确 PID、管理员限定
  158. // pipe ACL 和一次性 token 绑定连接。controller 反向校验 broker 路径、SYSTEM 服务校验
  159. // broker 路径的安全边界保持不变。
  160. if (!VerifyPipeClient(pipe.SafePipeHandle, GetSelfPath(), elevated.Id, false))
  161. {
  162. TryTerminate(elevated);
  163. WriteError("peer_verification_failed");
  164. return;
  165. }
  166. }
  167. catch
  168. {
  169. TryTerminate(elevated);
  170. // Bugfix 原因:提权控制器在握手阶段断开时,最外层异常只会返回 helper_failed,丢失了失败阶段。
  171. WriteError("controller_handshake_failed");
  172. return;
  173. }
  174. try
  175. {
  176. using (StreamReader reader = CreateReader(pipe))
  177. using (StreamWriter writer = CreateWriter(pipe))
  178. {
  179. if (!FixedTimeEquals(ReadBoundedLine(reader), token))
  180. {
  181. WriteError("peer_verification_failed");
  182. return;
  183. }
  184. string ready = ReadBoundedLine(reader);
  185. string[] readyFields = ready.Split('\t');
  186. if (readyFields.Length == 3 && readyFields[0] == Protocol && readyFields[1] == "ERR")
  187. {
  188. Console.Out.WriteLine(ready);
  189. return;
  190. }
  191. if (readyFields.Length != 5 || readyFields[0] != Protocol || readyFields[1] != "READY")
  192. {
  193. WriteError("service_failed");
  194. return;
  195. }
  196. string systemPipeName = readyFields[2];
  197. string serviceToken = readyFields[3];
  198. int servicePid = ParsePositiveInt(readyFields[4]);
  199. string response;
  200. try
  201. {
  202. // 用户层 DPAPI 必须 impersonate 原始 broker,而不是 UAC 中可能另输的管理员账号。
  203. // 因此普通用户 broker 直接连接 SYSTEM service;elevated controller 只管理服务生命周期。
  204. using (NamedPipeClientStream servicePipe = ConnectPipeClient(systemPipeName, servicePid, false))
  205. using (StreamReader serviceReader = CreateReader(servicePipe))
  206. using (StreamWriter serviceWriter = CreateWriter(servicePipe))
  207. {
  208. serviceWriter.WriteLine(serviceToken);
  209. serviceWriter.WriteLine(request);
  210. response = ReadBoundedLine(serviceReader);
  211. }
  212. }
  213. catch
  214. {
  215. // Bugfix 原因:SYSTEM 服务管道连接或读取中断时不再退化成无阶段信息的 helper_failed。
  216. WriteError("service_channel_failed");
  217. return;
  218. }
  219. writer.WriteLine(Protocol + "\tDONE");
  220. string cleanup = ReadBoundedLine(reader);
  221. if (cleanup != Protocol + "\tCLEANED")
  222. {
  223. WriteError("service_cleanup_failed");
  224. return;
  225. }
  226. Console.Out.WriteLine(response);
  227. }
  228. }
  229. catch
  230. {
  231. WriteError("controller_handshake_failed");
  232. return;
  233. }
  234. try { elevated.WaitForExit(5000); }
  235. catch { }
  236. }
  237. }
  238. }
  239. private static void RunElevated(Dictionary<string, string> args)
  240. {
  241. if (!IsAdministrator())
  242. {
  243. return;
  244. }
  245. string brokerPipeName = RequireArgument(args, "--pipe");
  246. string brokerToken = RequireArgument(args, "--token");
  247. int parentPid = ParsePositiveInt(RequireArgument(args, "--parent-pid"));
  248. using (NamedPipeClientStream brokerPipe = ConnectPipeClient(brokerPipeName, parentPid))
  249. using (ManualResetEvent completed = new ManualResetEvent(false))
  250. {
  251. Thread watchdog = new Thread(
  252. () => MonitorBrokerAndDeadline(brokerPipe, parentPid, completed));
  253. watchdog.IsBackground = true;
  254. watchdog.Start();
  255. try
  256. {
  257. using (StreamReader brokerReader = CreateReader(brokerPipe))
  258. using (StreamWriter brokerWriter = CreateWriter(brokerPipe))
  259. {
  260. brokerWriter.WriteLine(brokerToken);
  261. RunTemporarySystemService(brokerReader, brokerWriter, parentPid);
  262. }
  263. }
  264. finally
  265. {
  266. completed.Set();
  267. watchdog.Join(1000);
  268. }
  269. }
  270. }
  271. private static void MonitorHostAndDeadline(int hostPid, ManualResetEvent completed)
  272. {
  273. IntPtr hostProcess = OpenProcess(ProcessSynchronize, false, hostPid);
  274. if (hostProcess == IntPtr.Zero) Environment.Exit(1);
  275. try
  276. {
  277. DateTime deadline = DateTime.UtcNow.AddMilliseconds(BrokerLifetimeMs);
  278. while (!completed.WaitOne(100))
  279. {
  280. uint wait = WaitForSingleObject(hostProcess, 0);
  281. if (wait == WaitObject0 || wait == WaitFailed || DateTime.UtcNow >= deadline)
  282. Environment.Exit(1);
  283. }
  284. }
  285. finally { CloseHandle(hostProcess); }
  286. }
  287. private static void MonitorBrokerAndDeadline(
  288. NamedPipeClientStream brokerPipe,
  289. int parentPid,
  290. ManualResetEvent completed)
  291. {
  292. IntPtr brokerProcess = OpenProcess(
  293. ProcessSynchronize | ProcessQueryLimitedInformation,
  294. false,
  295. parentPid);
  296. try
  297. {
  298. if (brokerProcess == IntPtr.Zero ||
  299. !VerifyProcessImagePathHandle(brokerProcess, GetSelfPath()))
  300. {
  301. brokerPipe.Dispose();
  302. return;
  303. }
  304. DateTime deadline = DateTime.UtcNow.AddMilliseconds(ControllerLifetimeMs);
  305. while (!completed.WaitOne(100))
  306. {
  307. uint wait = WaitForSingleObject(brokerProcess, 0);
  308. if (wait == WaitObject0 || wait == WaitFailed || DateTime.UtcNow >= deadline)
  309. {
  310. // Bugfix 原因:Electron 退出后 broker 可能仍卡在 SYSTEM 服务响应,不能再依赖 JS 定时器。
  311. // controller 自己关闭控制管道,强制 RunTemporarySystemService 进入 finally 停止/删除服务。
  312. brokerPipe.Dispose();
  313. return;
  314. }
  315. }
  316. }
  317. finally
  318. {
  319. if (brokerProcess != IntPtr.Zero) CloseHandle(brokerProcess);
  320. }
  321. }
  322. private static void RunTemporarySystemService(
  323. StreamReader brokerReader,
  324. StreamWriter brokerWriter,
  325. int brokerPid)
  326. {
  327. string serviceName = "ZCodeBrowserImport_" + Guid.NewGuid().ToString("N");
  328. string pipeName = "zcode-browser-import-system-" + Guid.NewGuid().ToString("N");
  329. string token = CreateToken();
  330. IntPtr scm = IntPtr.Zero;
  331. IntPtr service = IntPtr.Zero;
  332. bool serviceStarted = false;
  333. bool cleanupSucceeded = false;
  334. try
  335. {
  336. scm = OpenSCManager(null, null, ScManagerCreateService);
  337. if (scm == IntPtr.Zero) throw new InvalidOperationException();
  338. string commandLine = QuoteCommandLineArgument(GetSelfPath()) +
  339. " --service --pipe " + pipeName + " --token " + token +
  340. " --broker-pid " + brokerPid +
  341. " --service-name " + serviceName;
  342. service = CreateService(
  343. scm,
  344. serviceName,
  345. serviceName,
  346. ServiceAllAccess,
  347. ServiceWin32OwnProcess,
  348. ServiceDemandStart,
  349. ServiceErrorNormal,
  350. commandLine,
  351. null,
  352. IntPtr.Zero,
  353. null,
  354. null,
  355. null);
  356. if (service == IntPtr.Zero) throw new InvalidOperationException();
  357. if (!StartService(service, 0, null)) throw new InvalidOperationException();
  358. serviceStarted = true;
  359. int servicePid = WaitForServiceProcessId(service, PipeTimeoutMs);
  360. if (servicePid <= 0) throw new InvalidOperationException();
  361. brokerWriter.WriteLine(
  362. Protocol + "\tREADY\t" + pipeName + "\t" + token + "\t" + servicePid);
  363. if (ReadBoundedLine(brokerReader) != Protocol + "\tDONE")
  364. throw new InvalidDataException();
  365. }
  366. catch
  367. {
  368. if (!serviceStarted) brokerWriter.WriteLine(ErrorResponse("service_failed"));
  369. }
  370. finally
  371. {
  372. // Bugfix 原因:临时 LocalSystem 服务若只在成功路径删除,UAC 后的超时/管道异常会留下高权限常驻项。
  373. // 所有退出路径都先请求停止;无响应时只终止 SCM 返回且映像路径匹配的精确服务 PID,再删除并核验。
  374. cleanupSucceeded = CleanupTemporaryService(scm, service, serviceName);
  375. }
  376. if (serviceStarted)
  377. {
  378. brokerWriter.WriteLine(
  379. cleanupSucceeded ? Protocol + "\tCLEANED" : ErrorResponse("service_cleanup_failed"));
  380. }
  381. }
  382. private static int WaitForServiceProcessId(IntPtr service, int timeoutMs)
  383. {
  384. DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
  385. do
  386. {
  387. ServiceStatusProcess status;
  388. if (TryQueryServiceStatus(service, out status))
  389. {
  390. if (status.currentState == ServiceStopped) return -1;
  391. if (status.processId > 0) return status.processId;
  392. }
  393. Thread.Sleep(50);
  394. }
  395. while (DateTime.UtcNow < deadline);
  396. return -1;
  397. }
  398. private static bool CleanupTemporaryService(
  399. IntPtr scm,
  400. IntPtr service,
  401. string serviceName)
  402. {
  403. bool stopped = service == IntPtr.Zero;
  404. bool deleted = service == IntPtr.Zero;
  405. try
  406. {
  407. if (service != IntPtr.Zero)
  408. {
  409. ServiceStatus ignored = new ServiceStatus();
  410. if (!ControlService(service, ServiceControlStop, ref ignored))
  411. {
  412. int stopError = Marshal.GetLastWin32Error();
  413. if (stopError == ErrorServiceNotActive) stopped = true;
  414. }
  415. if (!stopped) stopped = WaitForServiceStopped(service, 5000);
  416. if (!stopped)
  417. {
  418. ServiceStatusProcess status;
  419. if (TryQueryServiceStatus(service, out status) && status.processId > 0)
  420. stopped = TerminateVerifiedServiceProcess(status.processId);
  421. }
  422. deleted = DeleteService(service);
  423. if (!deleted)
  424. {
  425. int deleteError = Marshal.GetLastWin32Error();
  426. deleted = deleteError == ErrorServiceMarkedForDelete ||
  427. deleteError == ErrorServiceDoesNotExist;
  428. }
  429. }
  430. }
  431. finally
  432. {
  433. if (service != IntPtr.Zero) CloseServiceHandle(service);
  434. if (scm != IntPtr.Zero) CloseServiceHandle(scm);
  435. }
  436. return stopped && deleted && WaitForServiceAbsent(serviceName, 5000);
  437. }
  438. private static bool WaitForServiceStopped(IntPtr service, int timeoutMs)
  439. {
  440. DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
  441. do
  442. {
  443. ServiceStatusProcess status;
  444. if (!TryQueryServiceStatus(service, out status)) return false;
  445. if (status.currentState == ServiceStopped) return true;
  446. Thread.Sleep(50);
  447. }
  448. while (DateTime.UtcNow < deadline);
  449. return false;
  450. }
  451. private static bool TryQueryServiceStatus(IntPtr service, out ServiceStatusProcess status)
  452. {
  453. status = new ServiceStatusProcess();
  454. int bytesNeeded;
  455. return QueryServiceStatusEx(
  456. service,
  457. ServiceStatusProcessInfo,
  458. ref status,
  459. Marshal.SizeOf(typeof(ServiceStatusProcess)),
  460. out bytesNeeded);
  461. }
  462. private static bool TerminateVerifiedServiceProcess(int processId)
  463. {
  464. IntPtr serviceProcess = OpenProcess(
  465. ProcessTerminate | ProcessSynchronize | ProcessQueryLimitedInformation,
  466. false,
  467. processId);
  468. if (serviceProcess == IntPtr.Zero) return false;
  469. try
  470. {
  471. return VerifyProcessImagePathHandle(serviceProcess, GetSelfPath()) &&
  472. TerminateProcess(serviceProcess, 1) &&
  473. WaitForSingleObject(serviceProcess, 5000) == WaitObject0;
  474. }
  475. finally { CloseHandle(serviceProcess); }
  476. }
  477. private static bool WaitForServiceAbsent(string serviceName, int timeoutMs)
  478. {
  479. DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
  480. do
  481. {
  482. IntPtr manager = OpenSCManager(null, null, ScManagerConnect);
  483. if (manager == IntPtr.Zero) return false;
  484. IntPtr candidate = IntPtr.Zero;
  485. try
  486. {
  487. candidate = OpenService(manager, serviceName, ServiceQueryStatus);
  488. if (candidate == IntPtr.Zero)
  489. {
  490. int error = Marshal.GetLastWin32Error();
  491. if (error == ErrorServiceDoesNotExist || error == ErrorServiceMarkedForDelete)
  492. return true;
  493. }
  494. }
  495. finally
  496. {
  497. if (candidate != IntPtr.Zero) CloseServiceHandle(candidate);
  498. CloseServiceHandle(manager);
  499. }
  500. Thread.Sleep(50);
  501. }
  502. while (DateTime.UtcNow < deadline);
  503. return false;
  504. }
  505. private static void RunServiceDispatcher()
  506. {
  507. serviceMainDelegate = ServiceMain;
  508. ServiceTableEntry[] table = new ServiceTableEntry[2];
  509. table[0] = new ServiceTableEntry
  510. {
  511. serviceName = RequireArgument(serviceArguments, "--service-name"),
  512. serviceMain = serviceMainDelegate,
  513. };
  514. table[1] = new ServiceTableEntry();
  515. if (!StartServiceCtrlDispatcher(table)) throw new InvalidOperationException();
  516. }
  517. private static void ServiceMain(int argc, IntPtr argv)
  518. {
  519. serviceControlHandlerDelegate = ServiceControlHandler;
  520. serviceStatusHandle = RegisterServiceCtrlHandler(
  521. RequireArgument(serviceArguments, "--service-name"), serviceControlHandlerDelegate);
  522. SetCurrentServiceStatus(ServiceRunning, Win32OwnProcessAccepted);
  523. try
  524. {
  525. RunServiceWorker(serviceArguments);
  526. }
  527. catch
  528. {
  529. // 服务异常只影响本次导入;最终状态和自删除仍必须执行。
  530. }
  531. finally
  532. {
  533. TryDeleteCurrentService(RequireArgument(serviceArguments, "--service-name"));
  534. SetCurrentServiceStatus(ServiceStopped, 0);
  535. }
  536. }
  537. private static void TryDeleteCurrentService(string serviceName)
  538. {
  539. IntPtr manager = IntPtr.Zero;
  540. IntPtr service = IntPtr.Zero;
  541. try
  542. {
  543. manager = OpenSCManager(null, null, ScManagerConnect);
  544. if (manager == IntPtr.Zero) return;
  545. service = OpenService(manager, serviceName, DeleteAccess);
  546. if (service != IntPtr.Zero) DeleteService(service);
  547. }
  548. catch { }
  549. finally
  550. {
  551. if (service != IntPtr.Zero) CloseServiceHandle(service);
  552. if (manager != IntPtr.Zero) CloseServiceHandle(manager);
  553. }
  554. }
  555. private static void RunServiceWorker(Dictionary<string, string> args)
  556. {
  557. if (!IsLocalSystem()) return;
  558. string pipeName = RequireArgument(args, "--pipe");
  559. string token = RequireArgument(args, "--token");
  560. int brokerPid = ParsePositiveInt(RequireArgument(serviceArguments, "--broker-pid"));
  561. // SYSTEM 服务只向原始普通用户 broker 暴露一次性 pipe;精确 PID/映像路径/token 仍是授权依据。
  562. using (NamedPipeServerStream pipe = CreatePipeServer(pipeName, false, true))
  563. {
  564. activeServicePipe = pipe;
  565. try
  566. {
  567. if (!WaitForConnection(pipe, PipeTimeoutMs) ||
  568. !VerifyPipeClient(pipe.SafePipeHandle, GetSelfPath(), brokerPid))
  569. {
  570. return;
  571. }
  572. using (StreamReader reader = CreateReader(pipe))
  573. using (StreamWriter writer = CreateWriter(pipe))
  574. {
  575. if (!FixedTimeEquals(ReadBoundedLine(reader), token)) return;
  576. string request = ReadBoundedLine(reader);
  577. byte[] masterKey = null;
  578. ImportRequest parsed = null;
  579. try
  580. {
  581. parsed = ParseImportRequest(request);
  582. masterKey = DecryptAppBoundKey(pipe.SafePipeHandle, parsed.EncryptedKey, parsed.ChromeExecutablePath);
  583. writer.WriteLine(Protocol + "\tOK\t" + Convert.ToBase64String(masterKey));
  584. }
  585. catch (ChromeValidationException)
  586. {
  587. writer.WriteLine(ErrorResponse("validation_failed"));
  588. }
  589. catch (UnsupportedKeyException)
  590. {
  591. writer.WriteLine(ErrorResponse("unsupported_key"));
  592. }
  593. catch (CngException)
  594. {
  595. writer.WriteLine(ErrorResponse("cng_failed"));
  596. }
  597. catch
  598. {
  599. writer.WriteLine(ErrorResponse("decryption_failed"));
  600. }
  601. finally
  602. {
  603. if (parsed != null) Zero(parsed.EncryptedKey);
  604. Zero(masterKey);
  605. }
  606. }
  607. }
  608. finally { activeServicePipe = null; }
  609. }
  610. }
  611. private static byte[] DecryptAppBoundKey(SafePipeHandle pipeHandle, byte[] encryptedKey, string chromeExecutablePath)
  612. {
  613. byte[] systemPlaintext = null;
  614. byte[] userPlaintext = null;
  615. byte[] content = null;
  616. try
  617. {
  618. systemPlaintext = DpapiUnprotect(encryptedKey);
  619. if (!ImpersonateNamedPipeClient(pipeHandle.DangerousGetHandle()))
  620. throw new InvalidOperationException();
  621. try
  622. {
  623. userPlaintext = DpapiUnprotect(systemPlaintext);
  624. }
  625. finally
  626. {
  627. RevertToSelf();
  628. }
  629. ParsedAppBoundBlob parsed = ParseAppBoundBlob(userPlaintext);
  630. try
  631. {
  632. content = parsed.Content;
  633. ValidateChromePath(parsed.ValidationData, chromeExecutablePath);
  634. return DeriveChromeMasterKey(content);
  635. }
  636. finally
  637. {
  638. Zero(parsed.ValidationData);
  639. }
  640. }
  641. finally
  642. {
  643. Zero(systemPlaintext);
  644. Zero(userPlaintext);
  645. Zero(content);
  646. }
  647. }
  648. private static ParsedAppBoundBlob ParseAppBoundBlob(byte[] data)
  649. {
  650. if (data == null || data.Length < 10) throw new InvalidDataException();
  651. int offset = 0;
  652. uint validationLength = ReadUInt32(data, ref offset);
  653. if (validationLength == 0 || validationLength > data.Length - offset - 4)
  654. throw new InvalidDataException();
  655. byte[] validation = CopyRange(data, ref offset, checked((int)validationLength));
  656. uint contentLength = ReadUInt32(data, ref offset);
  657. if (contentLength == 0 || contentLength != data.Length - offset)
  658. throw new InvalidDataException();
  659. byte[] content = CopyRange(data, ref offset, checked((int)contentLength));
  660. return new ParsedAppBoundBlob(validation, content);
  661. }
  662. private static void ValidateChromePath(byte[] validationData, string chromeExecutablePath)
  663. {
  664. if (validationData == null || validationData.Length < 2) throw new ChromeValidationException();
  665. int pathOffset;
  666. if (validationData[0] == 2) pathOffset = 1;
  667. else if (validationData[0] == 3 && validationData.Length >= 3) pathOffset = 2;
  668. else throw new ChromeValidationException();
  669. string protectedPath = Encoding.UTF8.GetString(
  670. validationData, pathOffset, validationData.Length - pathOffset);
  671. string expectedPath = TrimChromeValidationPath(chromeExecutablePath);
  672. string actualPath = NormalizeProgramFilesPath(protectedPath);
  673. if (!string.Equals(expectedPath, actualPath, StringComparison.OrdinalIgnoreCase))
  674. throw new ChromeValidationException();
  675. }
  676. private static string TrimChromeValidationPath(string executablePath)
  677. {
  678. string path = Path.GetFullPath(executablePath).TrimEnd(Path.DirectorySeparatorChar);
  679. path = Path.GetDirectoryName(path);
  680. while (!string.IsNullOrEmpty(path))
  681. {
  682. string name = Path.GetFileName(path);
  683. Version version;
  684. if (string.Equals(name, "Application", StringComparison.OrdinalIgnoreCase) ||
  685. string.Equals(name, "Temp", StringComparison.OrdinalIgnoreCase) ||
  686. Version.TryParse(name, out version))
  687. {
  688. path = Path.GetDirectoryName(path);
  689. continue;
  690. }
  691. break;
  692. }
  693. return NormalizeProgramFilesPath(path);
  694. }
  695. private static string NormalizeProgramFilesPath(string path)
  696. {
  697. if (string.IsNullOrWhiteSpace(path)) throw new ChromeValidationException();
  698. string normalized = Path.GetFullPath(path.Trim()).TrimEnd(Path.DirectorySeparatorChar);
  699. string programFilesX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
  700. string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  701. if (!string.IsNullOrEmpty(programFilesX86) && !string.IsNullOrEmpty(programFiles) &&
  702. normalized.StartsWith(programFilesX86 + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
  703. {
  704. normalized = programFiles + normalized.Substring(programFilesX86.Length);
  705. }
  706. return normalized;
  707. }
  708. private static byte[] DeriveChromeMasterKey(byte[] content)
  709. {
  710. if (content == null || content.Length < 1) throw new UnsupportedKeyException();
  711. byte flag = content[0];
  712. if ((flag == 1 || flag == 2) && content.Length == 61)
  713. {
  714. byte[] nonce = Slice(content, 1, 12);
  715. byte[] ciphertext = Slice(content, 13, 32);
  716. byte[] tag = Slice(content, 45, 16);
  717. try
  718. {
  719. return flag == 1
  720. ? AesGcmDecrypt(Flag1Key, nonce, ciphertext, tag)
  721. : ChaCha20Poly1305Decrypt(Flag2Key, nonce, ciphertext, tag);
  722. }
  723. finally
  724. {
  725. Zero(nonce);
  726. Zero(ciphertext);
  727. Zero(tag);
  728. }
  729. }
  730. if (flag == 3 && content.Length == 93)
  731. {
  732. byte[] encryptedAesKey = Slice(content, 1, 32);
  733. byte[] nonce = Slice(content, 33, 12);
  734. byte[] ciphertext = Slice(content, 45, 32);
  735. byte[] tag = Slice(content, 77, 16);
  736. byte[] aesKey = null;
  737. try
  738. {
  739. aesKey = DecryptChromeCngKey(encryptedAesKey);
  740. if (aesKey.Length != 32) throw new CngException();
  741. for (int i = 0; i < aesKey.Length; i++) aesKey[i] ^= Flag3Mask[i];
  742. return AesGcmDecrypt(aesKey, nonce, ciphertext, tag);
  743. }
  744. finally
  745. {
  746. Zero(encryptedAesKey);
  747. Zero(nonce);
  748. Zero(ciphertext);
  749. Zero(tag);
  750. Zero(aesKey);
  751. }
  752. }
  753. throw new UnsupportedKeyException();
  754. }
  755. private static byte[] DecryptChromeCngKey(byte[] encrypted)
  756. {
  757. IntPtr provider = IntPtr.Zero;
  758. IntPtr key = IntPtr.Zero;
  759. try
  760. {
  761. if (NCryptOpenStorageProvider(out provider, ChromeCngProvider, 0) != 0)
  762. throw new CngException();
  763. if (NCryptOpenKey(provider, out key, ChromeCngKey, 0, 0) != 0)
  764. throw new CngException();
  765. int outputLength;
  766. if (NCryptDecrypt(key, encrypted, encrypted.Length, IntPtr.Zero, null, 0, out outputLength, NCryptSilentFlag) != 0 ||
  767. outputLength <= 0 || outputLength > 1024)
  768. throw new CngException();
  769. byte[] output = new byte[outputLength];
  770. int written;
  771. if (NCryptDecrypt(key, encrypted, encrypted.Length, IntPtr.Zero, output, output.Length, out written, NCryptSilentFlag) != 0 ||
  772. written != output.Length)
  773. {
  774. Zero(output);
  775. throw new CngException();
  776. }
  777. return output;
  778. }
  779. finally
  780. {
  781. if (key != IntPtr.Zero) NCryptFreeObject(key);
  782. if (provider != IntPtr.Zero) NCryptFreeObject(provider);
  783. }
  784. }
  785. private static byte[] AesGcmDecrypt(byte[] key, byte[] nonce, byte[] ciphertext, byte[] tag)
  786. {
  787. IntPtr algorithm = IntPtr.Zero;
  788. IntPtr keyHandle = IntPtr.Zero;
  789. GCHandle nonceHandle = default(GCHandle);
  790. GCHandle tagHandle = default(GCHandle);
  791. try
  792. {
  793. CheckNtStatus(BCryptOpenAlgorithmProvider(out algorithm, "AES", null, 0));
  794. byte[] mode = Encoding.Unicode.GetBytes("ChainingModeGCM\0");
  795. CheckNtStatus(BCryptSetProperty(algorithm, "ChainingMode", mode, mode.Length, 0));
  796. int objectLength = GetBcryptIntProperty(algorithm, "ObjectLength");
  797. byte[] keyObject = new byte[objectLength];
  798. try
  799. {
  800. CheckNtStatus(BCryptGenerateSymmetricKey(
  801. algorithm, out keyHandle, keyObject, keyObject.Length, key, key.Length, 0));
  802. nonceHandle = GCHandle.Alloc(nonce, GCHandleType.Pinned);
  803. tagHandle = GCHandle.Alloc(tag, GCHandleType.Pinned);
  804. BcryptAuthenticatedCipherModeInfo authInfo = new BcryptAuthenticatedCipherModeInfo
  805. {
  806. cbSize = Marshal.SizeOf(typeof(BcryptAuthenticatedCipherModeInfo)),
  807. dwInfoVersion = 1,
  808. pbNonce = nonceHandle.AddrOfPinnedObject(),
  809. cbNonce = nonce.Length,
  810. pbTag = tagHandle.AddrOfPinnedObject(),
  811. cbTag = tag.Length,
  812. };
  813. byte[] plaintext = new byte[ciphertext.Length];
  814. int written;
  815. int status = BCryptDecrypt(
  816. keyHandle, ciphertext, ciphertext.Length, ref authInfo,
  817. null, 0, plaintext, plaintext.Length, out written, 0);
  818. if (status != 0 || written != plaintext.Length)
  819. {
  820. Zero(plaintext);
  821. CheckNtStatus(status);
  822. throw new CryptographicException();
  823. }
  824. return plaintext;
  825. }
  826. finally
  827. {
  828. Zero(keyObject);
  829. }
  830. }
  831. finally
  832. {
  833. if (tagHandle.IsAllocated) tagHandle.Free();
  834. if (nonceHandle.IsAllocated) nonceHandle.Free();
  835. if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
  836. if (algorithm != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithm, 0);
  837. }
  838. }
  839. private static byte[] ChaCha20Poly1305Decrypt(byte[] key, byte[] nonce, byte[] ciphertext, byte[] expectedTag)
  840. {
  841. byte[] firstBlock = ChaCha20Block(key, nonce, 0);
  842. byte[] oneTimeKey = Slice(firstBlock, 0, 32);
  843. byte[] macInput = BuildPoly1305Input(ciphertext);
  844. byte[] actualTag = null;
  845. try
  846. {
  847. actualTag = Poly1305(oneTimeKey, macInput);
  848. if (!FixedTimeEquals(actualTag, expectedTag)) throw new CryptographicException();
  849. byte[] plaintext = new byte[ciphertext.Length];
  850. int offset = 0;
  851. uint counter = 1;
  852. while (offset < ciphertext.Length)
  853. {
  854. byte[] block = ChaCha20Block(key, nonce, counter++);
  855. try
  856. {
  857. int take = Math.Min(64, ciphertext.Length - offset);
  858. for (int i = 0; i < take; i++) plaintext[offset + i] = (byte)(ciphertext[offset + i] ^ block[i]);
  859. offset += take;
  860. }
  861. finally { Zero(block); }
  862. }
  863. return plaintext;
  864. }
  865. finally
  866. {
  867. Zero(firstBlock);
  868. Zero(oneTimeKey);
  869. Zero(macInput);
  870. Zero(actualTag);
  871. }
  872. }
  873. private static byte[] ChaCha20Block(byte[] key, byte[] nonce, uint counter)
  874. {
  875. if (key.Length != 32 || nonce.Length != 12) throw new CryptographicException();
  876. uint[] state = new uint[16]
  877. {
  878. 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574,
  879. ReadUInt32(key, 0), ReadUInt32(key, 4), ReadUInt32(key, 8), ReadUInt32(key, 12),
  880. ReadUInt32(key, 16), ReadUInt32(key, 20), ReadUInt32(key, 24), ReadUInt32(key, 28),
  881. counter, ReadUInt32(nonce, 0), ReadUInt32(nonce, 4), ReadUInt32(nonce, 8),
  882. };
  883. uint[] working = (uint[])state.Clone();
  884. for (int i = 0; i < 10; i++)
  885. {
  886. QuarterRound(working, 0, 4, 8, 12); QuarterRound(working, 1, 5, 9, 13);
  887. QuarterRound(working, 2, 6, 10, 14); QuarterRound(working, 3, 7, 11, 15);
  888. QuarterRound(working, 0, 5, 10, 15); QuarterRound(working, 1, 6, 11, 12);
  889. QuarterRound(working, 2, 7, 8, 13); QuarterRound(working, 3, 4, 9, 14);
  890. }
  891. byte[] output = new byte[64];
  892. for (int i = 0; i < 16; i++) WriteUInt32(output, i * 4, unchecked(working[i] + state[i]));
  893. Array.Clear(state, 0, state.Length);
  894. Array.Clear(working, 0, working.Length);
  895. return output;
  896. }
  897. private static void QuarterRound(uint[] x, int a, int b, int c, int d)
  898. {
  899. x[a] = unchecked(x[a] + x[b]); x[d] = RotateLeft(x[d] ^ x[a], 16);
  900. x[c] = unchecked(x[c] + x[d]); x[b] = RotateLeft(x[b] ^ x[c], 12);
  901. x[a] = unchecked(x[a] + x[b]); x[d] = RotateLeft(x[d] ^ x[a], 8);
  902. x[c] = unchecked(x[c] + x[d]); x[b] = RotateLeft(x[b] ^ x[c], 7);
  903. }
  904. private static byte[] BuildPoly1305Input(byte[] ciphertext)
  905. {
  906. int paddedCiphertext = (ciphertext.Length + 15) & ~15;
  907. byte[] input = new byte[paddedCiphertext + 16];
  908. Buffer.BlockCopy(ciphertext, 0, input, 0, ciphertext.Length);
  909. WriteUInt64(input, paddedCiphertext + 8, (ulong)ciphertext.Length);
  910. return input;
  911. }
  912. private static byte[] Poly1305(byte[] key, byte[] data)
  913. {
  914. byte[] rBytes = Slice(key, 0, 16);
  915. rBytes[3] &= 15; rBytes[7] &= 15; rBytes[11] &= 15; rBytes[15] &= 15;
  916. rBytes[4] &= 252; rBytes[8] &= 252; rBytes[12] &= 252;
  917. BigInteger r = FromUnsignedLittleEndian(rBytes);
  918. BigInteger s = FromUnsignedLittleEndian(Slice(key, 16, 16));
  919. BigInteger p = (BigInteger.One << 130) - 5;
  920. BigInteger accumulator = BigInteger.Zero;
  921. for (int offset = 0; offset < data.Length; offset += 16)
  922. {
  923. int count = Math.Min(16, data.Length - offset);
  924. byte[] block = new byte[count + 1];
  925. Buffer.BlockCopy(data, offset, block, 0, count);
  926. block[count] = 1;
  927. accumulator = ((accumulator + FromUnsignedLittleEndian(block)) * r) % p;
  928. Zero(block);
  929. }
  930. BigInteger tagValue = (accumulator + s) & ((BigInteger.One << 128) - 1);
  931. byte[] encoded = tagValue.ToByteArray();
  932. byte[] tag = new byte[16];
  933. Buffer.BlockCopy(encoded, 0, tag, 0, Math.Min(encoded.Length, tag.Length));
  934. Zero(rBytes);
  935. Zero(encoded);
  936. return tag;
  937. }
  938. private static BigInteger FromUnsignedLittleEndian(byte[] value)
  939. {
  940. byte[] signed = new byte[value.Length + 1];
  941. Buffer.BlockCopy(value, 0, signed, 0, value.Length);
  942. BigInteger result = new BigInteger(signed);
  943. Zero(signed);
  944. return result;
  945. }
  946. private static byte[] DpapiUnprotect(byte[] encrypted)
  947. {
  948. GCHandle inputHandle = GCHandle.Alloc(encrypted, GCHandleType.Pinned);
  949. DataBlob input = new DataBlob { cbData = encrypted.Length, pbData = inputHandle.AddrOfPinnedObject() };
  950. DataBlob output = new DataBlob();
  951. try
  952. {
  953. if (!CryptUnprotectData(ref input, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref output))
  954. throw new CryptographicException();
  955. byte[] plaintext = new byte[output.cbData];
  956. Marshal.Copy(output.pbData, plaintext, 0, plaintext.Length);
  957. return plaintext;
  958. }
  959. finally
  960. {
  961. inputHandle.Free();
  962. if (output.pbData != IntPtr.Zero)
  963. {
  964. RtlSecureZeroMemory(output.pbData, new UIntPtr((uint)Math.Max(0, output.cbData)));
  965. LocalFree(output.pbData);
  966. }
  967. }
  968. }
  969. private static NamedPipeServerStream CreatePipeServer(
  970. string pipeName,
  971. bool allowAdministrators = false,
  972. bool allowAuthenticatedUsers = false)
  973. {
  974. PipeSecurity security = new PipeSecurity();
  975. security.SetAccessRuleProtection(true, false);
  976. SecurityIdentifier currentUser = WindowsIdentity.GetCurrent().User;
  977. if (currentUser == null) throw new InvalidOperationException();
  978. security.AddAccessRule(new PipeAccessRule(currentUser, PipeAccessRights.ReadWrite, AccessControlType.Allow));
  979. security.AddAccessRule(new PipeAccessRule(
  980. new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
  981. PipeAccessRights.FullControl,
  982. AccessControlType.Allow));
  983. if (allowAdministrators)
  984. {
  985. security.AddAccessRule(new PipeAccessRule(
  986. new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
  987. PipeAccessRights.ReadWrite,
  988. AccessControlType.Allow));
  989. }
  990. if (allowAuthenticatedUsers)
  991. {
  992. security.AddAccessRule(new PipeAccessRule(
  993. new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
  994. PipeAccessRights.ReadWrite,
  995. AccessControlType.Allow));
  996. }
  997. return new NamedPipeServerStream(
  998. pipeName,
  999. PipeDirection.InOut,
  1000. 1,
  1001. PipeTransmissionMode.Byte,
  1002. // Bugfix 原因:WaitForConnection 使用 Begin/End 异步等待实现硬超时;同步管道会在
  1003. // controller/service 接入前直接抛 InvalidOperationException,导致 Cookie 解密从未开始。
  1004. PipeOptions.Asynchronous,
  1005. 4096,
  1006. 4096,
  1007. security);
  1008. }
  1009. private static NamedPipeClientStream ConnectPipeClient(
  1010. string pipeName,
  1011. int? expectedServerPid,
  1012. bool verifyServerImagePath = true)
  1013. {
  1014. NamedPipeClientStream pipe = new NamedPipeClientStream(
  1015. ".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
  1016. pipe.Connect(PipeTimeoutMs);
  1017. pipe.ReadMode = PipeTransmissionMode.Byte;
  1018. uint serverPid;
  1019. if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out serverPid) ||
  1020. (expectedServerPid.HasValue && serverPid != expectedServerPid.Value) ||
  1021. (verifyServerImagePath && !VerifyProcessImagePath((int)serverPid, GetSelfPath())))
  1022. {
  1023. pipe.Dispose();
  1024. throw new InvalidOperationException();
  1025. }
  1026. return pipe;
  1027. }
  1028. private static bool WaitForConnection(NamedPipeServerStream pipe, int timeoutMs)
  1029. {
  1030. IAsyncResult wait = pipe.BeginWaitForConnection(null, null);
  1031. if (!wait.AsyncWaitHandle.WaitOne(timeoutMs)) return false;
  1032. pipe.EndWaitForConnection(wait);
  1033. return true;
  1034. }
  1035. private static bool VerifyPipeClient(
  1036. SafePipeHandle pipeHandle,
  1037. string expectedPath,
  1038. int? expectedPid = null,
  1039. bool verifyClientImagePath = true)
  1040. {
  1041. uint clientPid;
  1042. return GetNamedPipeClientProcessId(pipeHandle, out clientPid) &&
  1043. (!expectedPid.HasValue || clientPid == expectedPid.Value) &&
  1044. (!verifyClientImagePath || VerifyProcessImagePath((int)clientPid, expectedPath));
  1045. }
  1046. private static bool VerifyProcessImagePath(int processId, string expectedPath)
  1047. {
  1048. IntPtr process = OpenProcess(ProcessQueryLimitedInformation, false, processId);
  1049. if (process == IntPtr.Zero) return false;
  1050. try
  1051. {
  1052. return VerifyProcessImagePathHandle(process, expectedPath);
  1053. }
  1054. finally { CloseHandle(process); }
  1055. }
  1056. private static bool VerifyProcessImagePathHandle(IntPtr process, string expectedPath)
  1057. {
  1058. StringBuilder path = new StringBuilder(32768);
  1059. int length = path.Capacity;
  1060. return QueryFullProcessImageName(process, 0, path, ref length) &&
  1061. string.Equals(
  1062. Path.GetFullPath(path.ToString()),
  1063. Path.GetFullPath(expectedPath),
  1064. StringComparison.OrdinalIgnoreCase);
  1065. }
  1066. private static StreamReader CreateReader(Stream stream)
  1067. {
  1068. return new StreamReader(stream, new UTF8Encoding(false, true), false, 4096, true);
  1069. }
  1070. private static StreamWriter CreateWriter(Stream stream)
  1071. {
  1072. return new StreamWriter(stream, new UTF8Encoding(false), 4096, true) { AutoFlush = true, NewLine = "\n" };
  1073. }
  1074. private static string ReadBoundedLine(TextReader reader)
  1075. {
  1076. StringBuilder line = new StringBuilder();
  1077. while (line.Length <= MaxProtocolLineLength)
  1078. {
  1079. int value = reader.Read();
  1080. if (value == -1 || value == '\n') break;
  1081. if (value != '\r') line.Append((char)value);
  1082. }
  1083. if (line.Length == 0 || line.Length > MaxProtocolLineLength) throw new InvalidDataException();
  1084. return line.ToString();
  1085. }
  1086. private static void ValidateImportRequest(string request)
  1087. {
  1088. ImportRequest parsed = ParseImportRequest(request);
  1089. Zero(parsed.EncryptedKey);
  1090. }
  1091. private static ImportRequest ParseImportRequest(string request)
  1092. {
  1093. string[] parts = request.Split('\t');
  1094. if (parts.Length != 3 || parts[0] != Protocol) throw new InvalidDataException();
  1095. byte[] encryptedKey = Convert.FromBase64String(parts[1]);
  1096. string chromePath = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2]));
  1097. if (encryptedKey.Length < 32 || encryptedKey.Length > 65536 ||
  1098. string.IsNullOrWhiteSpace(chromePath) || chromePath.Length > 32768 ||
  1099. !string.Equals(Path.GetExtension(chromePath), ".exe", StringComparison.OrdinalIgnoreCase))
  1100. {
  1101. Zero(encryptedKey);
  1102. throw new InvalidDataException();
  1103. }
  1104. return new ImportRequest(encryptedKey, chromePath);
  1105. }
  1106. private static Dictionary<string, string> ParseArguments(string[] args)
  1107. {
  1108. Dictionary<string, string> parsed = new Dictionary<string, string>(StringComparer.Ordinal);
  1109. for (int i = 0; i < args.Length; i++)
  1110. {
  1111. if (!args[i].StartsWith("--", StringComparison.Ordinal)) continue;
  1112. if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
  1113. parsed[args[i]] = args[++i];
  1114. else parsed[args[i]] = string.Empty;
  1115. }
  1116. return parsed;
  1117. }
  1118. private static string RequireArgument(Dictionary<string, string> args, string key)
  1119. {
  1120. string value;
  1121. if (!args.TryGetValue(key, out value) || string.IsNullOrWhiteSpace(value))
  1122. throw new InvalidDataException();
  1123. return value;
  1124. }
  1125. private static int ParsePositiveInt(string value)
  1126. {
  1127. int parsed;
  1128. if (!int.TryParse(value, out parsed) || parsed <= 0) throw new InvalidDataException();
  1129. return parsed;
  1130. }
  1131. private static bool HasArgument(string[] args, string target)
  1132. {
  1133. foreach (string value in args) if (value == target) return true;
  1134. return false;
  1135. }
  1136. private static string GetSelfPath()
  1137. {
  1138. return Path.GetFullPath(Process.GetCurrentProcess().MainModule.FileName);
  1139. }
  1140. private static string CreateToken()
  1141. {
  1142. byte[] token = new byte[32];
  1143. using (RandomNumberGenerator random = RandomNumberGenerator.Create()) random.GetBytes(token);
  1144. string encoded = BitConverter.ToString(token).Replace("-", string.Empty);
  1145. Zero(token);
  1146. return encoded;
  1147. }
  1148. private static bool IsAdministrator()
  1149. {
  1150. WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
  1151. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  1152. }
  1153. private static bool IsLocalSystem()
  1154. {
  1155. SecurityIdentifier sid = WindowsIdentity.GetCurrent().User;
  1156. return sid != null && sid.IsWellKnown(WellKnownSidType.LocalSystemSid);
  1157. }
  1158. private static void WriteError(string code)
  1159. {
  1160. Console.Out.WriteLine(ErrorResponse(code));
  1161. }
  1162. private static string ErrorResponse(string code)
  1163. {
  1164. return Protocol + "\tERR\t" + code;
  1165. }
  1166. private static string QuoteCommandLineArgument(string value)
  1167. {
  1168. return "\"" + value.Replace("\"", "\\\"") + "\"";
  1169. }
  1170. private static bool FixedTimeEquals(string left, string right)
  1171. {
  1172. return FixedTimeEquals(Encoding.UTF8.GetBytes(left), Encoding.UTF8.GetBytes(right));
  1173. }
  1174. private static bool FixedTimeEquals(byte[] left, byte[] right)
  1175. {
  1176. int difference = left.Length ^ right.Length;
  1177. int length = Math.Max(left.Length, right.Length);
  1178. for (int i = 0; i < length; i++)
  1179. {
  1180. byte a = i < left.Length ? left[i] : (byte)0;
  1181. byte b = i < right.Length ? right[i] : (byte)0;
  1182. difference |= a ^ b;
  1183. }
  1184. return difference == 0;
  1185. }
  1186. private static void TryTerminate(Process process)
  1187. {
  1188. try { if (!process.HasExited) process.Kill(); } catch { }
  1189. }
  1190. private static byte[] Slice(byte[] value, int offset, int count)
  1191. {
  1192. byte[] result = new byte[count];
  1193. Buffer.BlockCopy(value, offset, result, 0, count);
  1194. return result;
  1195. }
  1196. private static byte[] CopyRange(byte[] value, ref int offset, int count)
  1197. {
  1198. if (count < 0 || offset < 0 || offset > value.Length - count) throw new InvalidDataException();
  1199. byte[] result = Slice(value, offset, count);
  1200. offset += count;
  1201. return result;
  1202. }
  1203. private static uint ReadUInt32(byte[] data, ref int offset)
  1204. {
  1205. if (offset > data.Length - 4) throw new InvalidDataException();
  1206. uint value = ReadUInt32(data, offset);
  1207. offset += 4;
  1208. return value;
  1209. }
  1210. private static uint ReadUInt32(byte[] data, int offset)
  1211. {
  1212. return (uint)(data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24));
  1213. }
  1214. private static void WriteUInt32(byte[] data, int offset, uint value)
  1215. {
  1216. data[offset] = (byte)value; data[offset + 1] = (byte)(value >> 8);
  1217. data[offset + 2] = (byte)(value >> 16); data[offset + 3] = (byte)(value >> 24);
  1218. }
  1219. private static void WriteUInt64(byte[] data, int offset, ulong value)
  1220. {
  1221. for (int i = 0; i < 8; i++) data[offset + i] = (byte)(value >> (i * 8));
  1222. }
  1223. private static uint RotateLeft(uint value, int count)
  1224. {
  1225. return (value << count) | (value >> (32 - count));
  1226. }
  1227. private static byte[] Hex(string value)
  1228. {
  1229. byte[] result = new byte[value.Length / 2];
  1230. for (int i = 0; i < result.Length; i++) result[i] = Convert.ToByte(value.Substring(i * 2, 2), 16);
  1231. return result;
  1232. }
  1233. private static void Zero(byte[] value)
  1234. {
  1235. if (value != null) Array.Clear(value, 0, value.Length);
  1236. }
  1237. private static int GetBcryptIntProperty(IntPtr handle, string property)
  1238. {
  1239. byte[] value = new byte[4];
  1240. int written;
  1241. CheckNtStatus(BCryptGetProperty(handle, property, value, value.Length, out written, 0));
  1242. if (written != 4) throw new CryptographicException();
  1243. return BitConverter.ToInt32(value, 0);
  1244. }
  1245. private static void CheckNtStatus(int status)
  1246. {
  1247. if (status != 0) throw new CryptographicException();
  1248. }
  1249. private static string GetProcessArchitecture()
  1250. {
  1251. ushort processMachine;
  1252. ushort nativeMachine;
  1253. if (IsWow64Process2(Process.GetCurrentProcess().Handle, out processMachine, out nativeMachine))
  1254. {
  1255. ushort machine = processMachine == ImageFileMachineUnknown ? nativeMachine : processMachine;
  1256. if (machine == ImageFileMachineAmd64) return "x64";
  1257. if (machine == ImageFileMachineArm64) return "arm64";
  1258. if (machine == ImageFileMachineI386) return "ia32";
  1259. }
  1260. return Environment.Is64BitProcess ? "x64" : "ia32";
  1261. }
  1262. private static string[] GetBuildIdentity()
  1263. {
  1264. AssemblyInformationalVersionAttribute attribute = (AssemblyInformationalVersionAttribute)
  1265. Attribute.GetCustomAttribute(
  1266. Assembly.GetExecutingAssembly(),
  1267. typeof(AssemblyInformationalVersionAttribute));
  1268. if (attribute == null) throw new InvalidDataException();
  1269. string[] fields = attribute.InformationalVersion.Split('|');
  1270. if (fields.Length != 2 || string.IsNullOrWhiteSpace(fields[0]) || string.IsNullOrWhiteSpace(fields[1]))
  1271. throw new InvalidDataException();
  1272. return fields;
  1273. }
  1274. private static void SetCurrentServiceStatus(int state, int acceptedControls)
  1275. {
  1276. if (serviceStatusHandle == IntPtr.Zero) return;
  1277. ServiceStatus status = new ServiceStatus
  1278. {
  1279. serviceType = ServiceWin32OwnProcess,
  1280. currentState = state,
  1281. controlsAccepted = acceptedControls,
  1282. };
  1283. SetServiceStatus(serviceStatusHandle, ref status);
  1284. }
  1285. private static void ServiceControlHandler(int control)
  1286. {
  1287. if (control != ServiceControlStop) return;
  1288. SetCurrentServiceStatus(ServiceStopPending, 0);
  1289. serviceStopEvent.Set();
  1290. NamedPipeServerStream pipe = activeServicePipe;
  1291. if (pipe != null)
  1292. {
  1293. try { pipe.Dispose(); } catch { }
  1294. }
  1295. }
  1296. private sealed class ImportRequest
  1297. {
  1298. internal ImportRequest(byte[] encryptedKey, string chromeExecutablePath)
  1299. {
  1300. EncryptedKey = encryptedKey;
  1301. ChromeExecutablePath = chromeExecutablePath;
  1302. }
  1303. internal byte[] EncryptedKey { get; private set; }
  1304. internal string ChromeExecutablePath { get; private set; }
  1305. }
  1306. private sealed class ParsedAppBoundBlob
  1307. {
  1308. internal ParsedAppBoundBlob(byte[] validationData, byte[] content)
  1309. {
  1310. ValidationData = validationData;
  1311. Content = content;
  1312. }
  1313. internal byte[] ValidationData { get; private set; }
  1314. internal byte[] Content { get; private set; }
  1315. }
  1316. private sealed class ChromeValidationException : Exception { }
  1317. private sealed class UnsupportedKeyException : Exception { }
  1318. private sealed class CngException : Exception { }
  1319. [StructLayout(LayoutKind.Sequential)]
  1320. private struct DataBlob { internal int cbData; internal IntPtr pbData; }
  1321. [StructLayout(LayoutKind.Sequential)]
  1322. private struct BcryptAuthenticatedCipherModeInfo
  1323. {
  1324. internal int cbSize; internal int dwInfoVersion;
  1325. internal IntPtr pbNonce; internal int cbNonce;
  1326. internal IntPtr pbAuthData; internal int cbAuthData;
  1327. internal IntPtr pbTag; internal int cbTag;
  1328. internal IntPtr pbMacContext; internal int cbMacContext;
  1329. internal int cbAAD; internal long cbData; internal int dwFlags;
  1330. }
  1331. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1332. private struct ServiceTableEntry
  1333. {
  1334. [MarshalAs(UnmanagedType.LPWStr)] internal string serviceName;
  1335. internal ServiceMainDelegate serviceMain;
  1336. }
  1337. [StructLayout(LayoutKind.Sequential)]
  1338. private struct ServiceStatus
  1339. {
  1340. internal int serviceType; internal int currentState; internal int controlsAccepted;
  1341. internal int win32ExitCode; internal int serviceSpecificExitCode;
  1342. internal int checkPoint; internal int waitHint;
  1343. }
  1344. [StructLayout(LayoutKind.Sequential)]
  1345. private struct ServiceStatusProcess
  1346. {
  1347. internal int serviceType; internal int currentState; internal int controlsAccepted;
  1348. internal int win32ExitCode; internal int serviceSpecificExitCode;
  1349. internal int checkPoint; internal int waitHint;
  1350. internal int processId; internal int serviceFlags;
  1351. }
  1352. private delegate void ServiceMainDelegate(int argc, IntPtr argv);
  1353. private delegate void ServiceControlHandlerDelegate(int control);
  1354. private const int ScManagerCreateService = 0x0002;
  1355. private const int ScManagerConnect = 0x0001;
  1356. private const int DeleteAccess = 0x00010000;
  1357. private const int ServiceQueryStatus = 0x0004;
  1358. private const int ServiceAllAccess = 0xF01FF;
  1359. private const int ServiceWin32OwnProcess = 0x00000010;
  1360. private const int ServiceDemandStart = 0x00000003;
  1361. private const int ServiceErrorNormal = 0x00000001;
  1362. private const int ServiceControlStop = 0x00000001;
  1363. private const int ServiceStopped = 0x00000001;
  1364. private const int ServiceStopPending = 0x00000003;
  1365. private const int ServiceRunning = 0x00000004;
  1366. private const int Win32OwnProcessAccepted = 0x00000001;
  1367. private const int ServiceStatusProcessInfo = 0;
  1368. private const int ProcessTerminate = 0x0001;
  1369. private const int ProcessSynchronize = 0x00100000;
  1370. private const int ProcessQueryLimitedInformation = 0x1000;
  1371. private const uint WaitObject0 = 0x00000000;
  1372. private const uint WaitFailed = 0xFFFFFFFF;
  1373. private const int ErrorServiceDoesNotExist = 1060;
  1374. private const int ErrorServiceNotActive = 1062;
  1375. private const int ErrorServiceMarkedForDelete = 1072;
  1376. private const int NCryptSilentFlag = 0x00000040;
  1377. private const ushort ImageFileMachineUnknown = 0x0000;
  1378. private const ushort ImageFileMachineI386 = 0x014c;
  1379. private const ushort ImageFileMachineAmd64 = 0x8664;
  1380. private const ushort ImageFileMachineArm64 = 0xAA64;
  1381. [DllImport("crypt32.dll", SetLastError = true)]
  1382. private static extern bool CryptUnprotectData(ref DataBlob input, IntPtr description, IntPtr entropy,
  1383. IntPtr reserved, IntPtr prompt, int flags, ref DataBlob output);
  1384. [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory);
  1385. [DllImport("kernel32.dll", EntryPoint = "RtlSecureZeroMemory")]
  1386. private static extern IntPtr RtlSecureZeroMemory(IntPtr destination, UIntPtr length);
  1387. [DllImport("advapi32.dll", SetLastError = true)] private static extern bool ImpersonateNamedPipeClient(IntPtr pipe);
  1388. [DllImport("advapi32.dll", SetLastError = true)] private static extern bool RevertToSelf();
  1389. [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)]
  1390. private static extern int NCryptOpenStorageProvider(out IntPtr provider, string providerName, int flags);
  1391. [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)]
  1392. private static extern int NCryptOpenKey(IntPtr provider, out IntPtr key, string keyName, int legacyKeySpec, int flags);
  1393. [DllImport("ncrypt.dll")]
  1394. private static extern int NCryptDecrypt(IntPtr key, byte[] input, int inputLength, IntPtr paddingInfo,
  1395. byte[] output, int outputLength, out int resultLength, int flags);
  1396. [DllImport("ncrypt.dll")] private static extern int NCryptFreeObject(IntPtr handle);
  1397. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
  1398. private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithm, string algorithmId, string implementation, int flags);
  1399. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
  1400. private static extern int BCryptSetProperty(IntPtr handle, string property, byte[] input, int inputLength, int flags);
  1401. [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
  1402. private static extern int BCryptGetProperty(IntPtr handle, string property, byte[] output, int outputLength, out int result, int flags);
  1403. [DllImport("bcrypt.dll")]
  1404. private static extern int BCryptGenerateSymmetricKey(IntPtr algorithm, out IntPtr key, byte[] keyObject,
  1405. int keyObjectLength, byte[] secret, int secretLength, int flags);
  1406. [DllImport("bcrypt.dll")]
  1407. private static extern int BCryptDecrypt(IntPtr key, byte[] input, int inputLength,
  1408. ref BcryptAuthenticatedCipherModeInfo paddingInfo, byte[] iv, int ivLength,
  1409. byte[] output, int outputLength, out int resultLength, int flags);
  1410. [DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr key);
  1411. [DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithm, int flags);
  1412. [DllImport("kernel32.dll", SetLastError = true)]
  1413. private static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint clientProcessId);
  1414. [DllImport("kernel32.dll", SetLastError = true)]
  1415. private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint serverProcessId);
  1416. [DllImport("kernel32.dll", SetLastError = true)]
  1417. private static extern IntPtr OpenProcess(int access, bool inheritHandle, int processId);
  1418. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1419. private static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder path, ref int size);
  1420. [DllImport("kernel32.dll", SetLastError = true)]
  1421. private static extern bool TerminateProcess(IntPtr process, int exitCode);
  1422. [DllImport("kernel32.dll", SetLastError = true)]
  1423. private static extern uint WaitForSingleObject(IntPtr handle, int milliseconds);
  1424. [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
  1425. [DllImport("kernel32.dll", SetLastError = true)]
  1426. private static extern bool IsWow64Process2(IntPtr process, out ushort processMachine, out ushort nativeMachine);
  1427. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1428. private static extern IntPtr OpenSCManager(string machineName, string databaseName, int desiredAccess);
  1429. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1430. private static extern IntPtr OpenService(IntPtr manager, string serviceName, int desiredAccess);
  1431. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1432. private static extern IntPtr CreateService(IntPtr manager, string serviceName, string displayName,
  1433. int desiredAccess, int serviceType, int startType, int errorControl, string binaryPath,
  1434. string loadOrderGroup, IntPtr tagId, string dependencies, string account, string password);
  1435. [DllImport("advapi32.dll", SetLastError = true)]
  1436. private static extern bool StartService(IntPtr service, int argumentCount, string[] arguments);
  1437. [DllImport("advapi32.dll", SetLastError = true)] private static extern bool DeleteService(IntPtr service);
  1438. [DllImport("advapi32.dll", SetLastError = true)] private static extern bool CloseServiceHandle(IntPtr handle);
  1439. [DllImport("advapi32.dll", SetLastError = true)]
  1440. private static extern bool ControlService(IntPtr service, int control, ref ServiceStatus status);
  1441. [DllImport("advapi32.dll", SetLastError = true)]
  1442. private static extern bool QueryServiceStatusEx(IntPtr service, int infoLevel,
  1443. ref ServiceStatusProcess status, int bufferSize, out int bytesNeeded);
  1444. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1445. private static extern bool StartServiceCtrlDispatcher([In] ServiceTableEntry[] table);
  1446. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  1447. private static extern IntPtr RegisterServiceCtrlHandler(string serviceName, ServiceControlHandlerDelegate handler);
  1448. [DllImport("advapi32.dll", SetLastError = true)]
  1449. private static extern bool SetServiceStatus(IntPtr statusHandle, ref ServiceStatus status);
  1450. }