返回 CodeWhale
windows.rs
根目录 / crates / engine / src / extension_host / windows.rs
1 //! Native-only Windows launch boundary. LPAC with only the `registryRead`
2 //! capability (Winsock cannot initialize without it) supplies
3 //! filesystem/network denial; the existing Job supplies lifetime and memory.
4 //! A fresh profile never inherits ACLs from a retired host. Profiles/assets
5 //! created here are disposed by their exact owner after the process ends;
6 //! crash leftovers are not guessed at or swept. Windows may also provide its
7 //! private AppContainer scratch/registry, separate from Core-owned state.
8
9 use std::collections::BTreeMap;
10 use std::ffi::{OsStr, OsString};
11 use std::fs::{self, File};
12 use std::io::{self, Read};
13 use std::mem::{size_of, zeroed};
14 use std::os::windows::ffi::OsStrExt;
15 use std::os::windows::fs::OpenOptionsExt;
16 use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
17 use std::path::{Path, PathBuf};
18 use std::ptr::{null, null_mut};
19 use std::sync::{Arc, Mutex};
20 use std::time::Duration;
21
22 use windows_sys::Win32::Foundation::{
23 ERROR_PIPE_CONNECTED, GetLastError, INVALID_HANDLE_VALUE, LocalFree, WAIT_ABANDONED,
24 WAIT_OBJECT_0, WAIT_TIMEOUT,
25 };
26 use windows_sys::Win32::Security::Authorization::{GRANT_ACCESS, REVOKE_ACCESS};
27 use windows_sys::Win32::Security::Isolation::{
28 CreateAppContainerProfile, DeleteAppContainerProfile,
29 };
30 use windows_sys::Win32::Security::{
31 ACL, CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, EqualSid, FreeSid, GetTokenInformation,
32 OBJECT_INHERIT_ACE, PSID, SECURITY_ATTRIBUTES, SECURITY_CAPABILITIES, SID_AND_ATTRIBUTES,
33 TOKEN_APPCONTAINER_INFORMATION, TOKEN_GROUPS, TOKEN_QUERY, TOKEN_STATISTICS,
34 TokenAppContainerSid, TokenCapabilities, TokenIsAppContainer,
35 TokenIsLessPrivilegedAppContainer, TokenStatistics,
36 };
37 use windows_sys::Win32::Storage::FileSystem::{
38 CreateFileW, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_OVERLAPPED,
39 FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_READ_ATTRIBUTES,
40 OPEN_EXISTING, PIPE_ACCESS_INBOUND, PIPE_ACCESS_OUTBOUND, READ_CONTROL, WRITE_DAC,
41 };
42 use windows_sys::Win32::System::Pipes::{ConnectNamedPipe, CreateNamedPipeW, PIPE_WAIT};
43 use windows_sys::Win32::System::Threading::{
44 CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateMutexW, CreateProcessW,
45 DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, GetCurrentProcess,
46 GetExitCodeProcess, InitializeProcThreadAttributeList, OpenProcessToken,
47 PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY,
48 PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
49 PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, PROCESS_INFORMATION, ReleaseMutex, ResumeThread,
50 STARTF_USESTDHANDLES, STARTUPINFOEXW, UpdateProcThreadAttribute, WaitForSingleObject,
51 };
52 use windows_sys::Win32::System::WindowsProgramming::PROCESS_CREATION_CHILD_PROCESS_OVERRIDE;
53
54 use codewhale_dependencies::{HostRuntime, HostRuntimeKind};
55 use codewhale_runtime::process_tree::ProcessTree;
56 use codewhale_util::files::WindowsDirectory;
57
58 const PROBE_SOURCE: &str = include_str!("../../extension-host/src/windows-sandbox-probe.mjs");
59 const PROBE_DEADLINE: Duration = Duration::from_secs(15);
60 // Windows SDK winnt.h; the documented LPAC startup attribute opts out of the
61 // ambient ALL APPLICATION PACKAGES group. Not a fabricated token status.
62 const PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT: u32 = 0x1;
63 const MAX_GRANT_ENTRIES: usize = 65_536;
64 const MAX_GRANT_SCOPES: usize = 1024;
65 /// Empty Bun config in the granted runtime-copy directory (see sandbox_args).
66 const EMPTY_BUN_CONFIG: &str = "empty-bunfig.toml";
67 const ACL_EDIT_WAIT_MS: u32 = 30_000;
68
69 // A kernel mutex covers admission and retirement in every Core process in
70 // this Windows logon/session. A process-local mutex cannot protect the shared
71 // host home's read/merge/write DACL transactions from another Core process.
72 struct AclEditGuard {
73 mutex: OwnedHandle,
74 // Windows mutex ownership belongs to the acquiring thread.
75 _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
76 }
77
78 impl AclEditGuard {
79 fn acquire() -> io::Result<Self> {
80 let mut token = null_mut();
81 // SAFETY: the process pseudo-handle is valid and token is an out pointer.
82 if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
83 return Err(io::Error::last_os_error());
84 }
85 let token = unsafe { OwnedHandle::from_raw_handle(token) };
86 let mut statistics = TOKEN_STATISTICS::default();
87 let mut read = 0;
88 // SAFETY: the aligned SDK struct and size match this fixed token query.
89 if unsafe {
90 GetTokenInformation(
91 token.as_raw_handle(),
92 TokenStatistics,
93 (&mut statistics as *mut TOKEN_STATISTICS).cast(),
94 size_of::<TOKEN_STATISTICS>() as u32,
95 &mut read,
96 )
97 } == 0
98 {
99 return Err(io::Error::last_os_error());
100 }
101 if read != size_of::<TOKEN_STATISTICS>() as u32 {
102 return Err(io::Error::other("invalid ACL lock logon identity"));
103 }
104 let logon = statistics.AuthenticationId;
105 let name = wide(OsStr::new(&format!(
106 r"Local\Codewhale.Native.AclEdits.{:08x}{:08x}",
107 logon.HighPart, logon.LowPart,
108 )))?;
109 // Default creator DACL, non-inheritable handle: never add a Native
110 // profile or AppContainer-group grant to Core's synchronization.
111 let mutex = unsafe { CreateMutexW(null(), 0, name.as_ptr()) };
112 if mutex.is_null() {
113 return Err(io::Error::last_os_error());
114 }
115 let mutex = unsafe { OwnedHandle::from_raw_handle(mutex) };
116 match unsafe { WaitForSingleObject(mutex.as_raw_handle(), ACL_EDIT_WAIT_MS) } {
117 // Abandonment also acquires ownership. No cached transaction state
118 // is trusted: callers pin each object and reread/validate its actual
119 // kernel DACL before editing, including after a prior owner crashed.
120 WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Self {
121 mutex,
122 _thread_bound: std::marker::PhantomData,
123 }),
124 WAIT_TIMEOUT => Err(io::Error::new(
125 io::ErrorKind::TimedOut,
126 "Native ACL edit lock timed out",
127 )),
128 _ => Err(io::Error::last_os_error()),
129 }
130 }
131 }
132
133 impl Drop for AclEditGuard {
134 fn drop(&mut self) {
135 // SAFETY: this thread acquired the mutex and the handle is still owned.
136 if unsafe { ReleaseMutex(self.mutex.as_raw_handle()) } == 0 {
137 tracing::warn!(
138 "Native ACL edit lock release failed: {}",
139 io::Error::last_os_error()
140 );
141 }
142 }
143 }
144
145 #[derive(Clone)]
146 pub struct NativeSandbox {
147 profile: Arc<Profile>,
148 _assets: Arc<tempfile::TempDir>,
149 pub program: PathBuf,
150 data: PathBuf,
151 }
152
153 impl std::fmt::Debug for NativeSandbox {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 f.debug_struct("NativeSandbox")
156 .field("program", &self.program)
157 .finish_non_exhaustive()
158 }
159 }
160
161 struct Profile {
162 name: Vec<u16>,
163 sid: PSID,
164 grants: Mutex<BTreeMap<PathBuf, GrantScope>>,
165 cleanup_runtime: Option<tokio::runtime::Handle>,
166 }
167 struct GrantScope {
168 identity: (u32, u64),
169 kind: GrantKind,
170 }
171 /// What one recorded ACE covers, so retirement edits exactly that object.
172 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
173 enum GrantKind {
174 /// One regular file.
175 File,
176 /// One directory's own entry list: no inheritance, no children.
177 Directory,
178 /// A directory and everything below it (inherited and explicit ACEs).
179 Tree,
180 }
181 // A retained exact profile SID, never a parsed/guessed orphan identity.
182 struct RetiredProfile {
183 name: Vec<u16>,
184 sid: PSID,
185 grants: BTreeMap<PathBuf, GrantScope>,
186 }
187 // SAFETY: retired state is exclusively owned; the SID is freed only after the
188 // existing runtime's blocking cleanup worker has finished its exact grants.
189 unsafe impl Send for RetiredProfile {}
190 // SAFETY: SID/name are immutable after successful creation. Win32 consumes
191 // borrowed SID memory synchronously; only the final Arc drop frees it.
192 unsafe impl Send for Profile {}
193 unsafe impl Sync for Profile {}
194
195 impl Profile {
196 fn create() -> io::Result<Self> {
197 let name = wide(OsStr::new(&format!(
198 "Codewhale.Native.{}",
199 uuid::Uuid::new_v4()
200 )))?;
201 let mut sid = null_mut();
202 // SAFETY: nul-terminated owned strings and an initialized out pointer.
203 let result = unsafe {
204 CreateAppContainerProfile(
205 name.as_ptr(),
206 name.as_ptr(),
207 name.as_ptr(),
208 null(),
209 0,
210 &mut sid,
211 )
212 };
213 if result < 0 {
214 return Err(io::Error::other(format!(
215 "CreateAppContainerProfile HRESULT {result:#x}"
216 )));
217 }
218 if sid.is_null() {
219 // No existing/user profile is adopted or removed on a collision.
220 unsafe {
221 DeleteAppContainerProfile(name.as_ptr());
222 }
223 return Err(io::Error::other("AppContainer profile has no SID"));
224 }
225 Ok(Self {
226 name,
227 sid,
228 grants: Mutex::new(BTreeMap::new()),
229 cleanup_runtime: tokio::runtime::Handle::try_current().ok(),
230 })
231 }
232 }
233
234 impl Profile {
235 fn remember(&self, path: &Path, file: &File, kind: GrantKind) -> io::Result<()> {
236 let value = codewhale_util::path_identity::windows_file_identity(file)?;
237 let mut grants = self
238 .grants
239 .lock()
240 .map_err(|_| io::Error::other("profile grant accounting poisoned"))?;
241 if let Some(old) = grants.get(path) {
242 if old.identity != (value.volume, value.index) || old.kind != kind {
243 return Err(io::Error::other(
244 "recorded profile grant identity changed; refusing overwrite",
245 ));
246 }
247 return Ok(());
248 }
249 if grants.len() == MAX_GRANT_SCOPES {
250 return Err(io::Error::other("profile exceeds 1024 exact grant scopes"));
251 }
252 grants.insert(
253 path.to_path_buf(),
254 GrantScope {
255 identity: (value.volume, value.index),
256 kind,
257 },
258 );
259 Ok(())
260 }
261 }
262 impl Drop for Profile {
263 fn drop(&mut self) {
264 let grants = std::mem::take(
265 self.grants
266 .get_mut()
267 .unwrap_or_else(|error| error.into_inner()),
268 );
269 let retired = RetiredProfile {
270 name: std::mem::take(&mut self.name),
271 sid: self.sid,
272 grants,
273 };
274 // Same existing Tokio scheduler; no new runtime/authority. The worker
275 // owns the SID until retirement completes, even during cancellation.
276 if let Some(runtime) = self.cleanup_runtime.take() {
277 runtime.spawn_blocking(move || retired.dispose());
278 } else {
279 // Synchronous platform callers have no runtime; work remains
280 // bounded to the exact recorded roots, never a profile sweep.
281 retired.dispose();
282 }
283 }
284 }
285 impl RetiredProfile {
286 fn dispose(self) {
287 drop(self);
288 }
289 }
290 // Drop also retires a task cancelled before its blocking worker starts. Once
291 // started, spawn_blocking cannot abandon this exclusively owned cleanup.
292 impl Drop for RetiredProfile {
293 fn drop(&mut self) {
294 for (path, scope) in &self.grants {
295 if let Err(error) = retire_scope(path, scope, self.sid) {
296 tracing::warn!(path = %path.display(), "Native exact-profile ACL retirement failed: {error}");
297 }
298 }
299 // The OS profile and SID stay alive until exact grant retirement ends.
300 // Crash remnants or refused/replaced roots are not guessed at/swept.
301 unsafe {
302 let result = DeleteAppContainerProfile(self.name.as_ptr());
303 if result < 0 {
304 tracing::warn!("Native AppContainer profile disposal failed ({result:#x})");
305 }
306 FreeSid(self.sid);
307 }
308 }
309 }
310
311 fn retire_scope(root: &Path, scope: &GrantScope, sid: PSID) -> io::Result<()> {
312 let _serial = AclEditGuard::acquire()?;
313 if !root.try_exists()? {
314 return Ok(());
315 }
316 let directory = scope.kind != GrantKind::File;
317 let root_pin = if directory {
318 WindowsDirectory::open_acl(root)?
319 } else {
320 WindowsDirectory::open(
321 root.parent()
322 .ok_or_else(|| io::Error::other("grant has no parent"))?,
323 )?
324 };
325 let root_file;
326 let file = if directory {
327 root_pin.acl_handle()?
328 } else {
329 root_file = acl_file_with_share(root, 1 | 2 | 4)?;
330 &root_file
331 };
332 let value = codewhale_util::path_identity::windows_file_identity(file)?;
333 if (value.volume, value.index) != scope.identity {
334 return Err(io::Error::other(
335 "recorded grant object was replaced; refusing cleanup",
336 ));
337 }
338 // Remove the parent's inheritable grant before walking, so newly created
339 // children cannot inherit this retired SID. The kernel write never
340 // propagates; every child is independently fenced and updated.
341 edit_acl(file, sid, 0, 0, REVOKE_ACCESS)?;
342 if scope.kind != GrantKind::Tree {
343 return Ok(());
344 }
345 let mut pending = Vec::new();
346 let mut count = 1;
347 enqueue_pinned_children(root, &root_pin, &mut pending, count)?;
348 let mut failure = None;
349 while let Some((path, parent_pin)) = pending.pop() {
350 count += 1;
351 if count > MAX_GRANT_ENTRIES {
352 return Err(io::Error::other(
353 "profile retirement exceeds 65536 entries in a recorded root",
354 ));
355 }
356 let mut work = || -> io::Result<()> {
357 let metadata = fs::symlink_metadata(&path)?;
358 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
359 return Err(io::Error::other(
360 "profile retirement refuses links/reparse points",
361 ));
362 }
363 if metadata.is_dir() {
364 let directory = parent_pin.open_acl_child(
365 path.file_name()
366 .ok_or_else(|| io::Error::other("grant has no filename"))?,
367 )?;
368 edit_acl(directory.acl_handle()?, sid, 0, 0, REVOKE_ACCESS)?;
369 enqueue_pinned_children(&path, &directory, &mut pending, count)
370 } else if metadata.is_file() {
371 if parent_pin.child_path(
372 path.file_name()
373 .ok_or_else(|| io::Error::other("grant has no filename"))?,
374 )? != path
375 {
376 return Err(io::Error::other("grant left its pinned parent"));
377 }
378 // Retiring this exact SID may overlap a new host's data
379 // writes. The handle edits this exact object while the pinned
380 // parent chain fences its path, so allow those legitimate
381 // writers/renames; never restore an old whole ACL.
382 let file = acl_file_with_share(&path, 1 | 2 | 4)?;
383 edit_acl(&file, sid, 0, 0, REVOKE_ACCESS)?;
384 Ok(())
385 } else {
386 Err(io::Error::other(
387 "profile retirement refuses a nonregular entry",
388 ))
389 }
390 };
391 match work() {
392 Ok(()) => {}
393 Err(error) => {
394 failure = Some(error);
395 }
396 }
397 }
398 match failure {
399 Some(error) => Err(error),
400 None => Ok(()),
401 }
402 }
403 fn enqueue_children(path: &Path, pending: &mut Vec<PathBuf>, visited: usize) -> io::Result<()> {
404 for entry in fs::read_dir(path)? {
405 // Bound materialized pending entries, not only already visited paths.
406 if visited + pending.len() >= MAX_GRANT_ENTRIES {
407 return Err(io::Error::other(
408 "profile directory traversal exceeds 65536 entries",
409 ));
410 }
411 pending.push(entry?.path());
412 }
413 Ok(())
414 }
415 fn enqueue_pinned_children(
416 path: &Path,
417 pin: &WindowsDirectory,
418 pending: &mut Vec<(PathBuf, WindowsDirectory)>,
419 visited: usize,
420 ) -> io::Result<()> {
421 let mut children = Vec::new();
422 // Reuse the exact admission/retirement bound, including already pending
423 // entries. Each child keeps its actual direct parent pinned until visited.
424 enqueue_children(path, &mut children, visited + pending.len())?;
425 pending.extend(children.into_iter().map(|child| (child, pin.clone())));
426 Ok(())
427 }
428 /// Name the admission step in an error, so a refusal says where it stopped.
429 fn in_step<T>(step: &str, result: io::Result<T>) -> io::Result<T> {
430 result.map_err(|error| io::Error::new(error.kind(), format!("{step}: {error}")))
431 }
432 fn acl_file(path: &Path) -> io::Result<File> {
433 acl_file_with_share(path, 1)
434 }
435 fn acl_file_with_share(path: &Path, share: u32) -> io::Result<File> {
436 let file = fs::OpenOptions::new()
437 .access_mode(READ_CONTROL | WRITE_DAC | FILE_READ_ATTRIBUTES)
438 .share_mode(share)
439 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
440 .open(path)?;
441 let metadata = file.metadata()?;
442 if !metadata.is_file()
443 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
444 || codewhale_util::path_identity::windows_file_identity(&file)?.links != 1
445 {
446 return Err(io::Error::other(
447 "profile ACL operation refuses a linked/nonregular file",
448 ));
449 }
450 Ok(file)
451 }
452
453 impl NativeSandbox {
454 /// Blocking, invoked by the existing manager's bounded launch worker.
455 pub fn prepare(
456 runtime: &HostRuntime,
457 bundle: &Path,
458 home: &Path,
459 data: &Path,
460 memory_cap: u64,
461 ) -> Result<Self, String> {
462 let work = || -> io::Result<Self> {
463 let profile = Arc::new(Profile::create()?);
464 let parent = home.join("extension-host").join("native-launch");
465 fs::create_dir_all(&parent)?;
466 let _parent = in_step("pin launch parent", WindowsDirectory::open(&parent))?;
467 let assets = Arc::new(
468 tempfile::Builder::new()
469 .prefix("host-")
470 .tempdir_in(&parent)?,
471 );
472 let program = assets.path().join("runtime.exe");
473 fs::write(assets.path().join(EMPTY_BUN_CONFIG), b"")?;
474 // The selected runtime is copied, never granted access in an
475 // installation/user directory. Pin its opened bytes while copying.
476 let original = runtime.path.canonicalize()?;
477 let source_pin = in_step(
478 "pin runtime directory",
479 WindowsDirectory::open(
480 original
481 .parent()
482 .ok_or_else(|| io::Error::other("runtime has no parent"))?,
483 ),
484 )?;
485 let mut source = in_step(
486 "open runtime",
487 codewhale_util::bundle_file::open_bundle_file(&original),
488 )?;
489 if source.metadata()?.len() > 512 * 1024 * 1024 {
490 return Err(io::Error::other(
491 "selected runtime exceeds 512 MiB launch limit",
492 ));
493 }
494 let mut target = fs::OpenOptions::new()
495 .write(true)
496 .create_new(true)
497 .open(&program)?;
498 io::copy(&mut source, &mut target)?;
499 target.sync_all()?;
500 drop(target);
501 drop(source_pin);
502 let sandbox = Self {
503 profile,
504 _assets: assets,
505 program,
506 data: data.to_path_buf(),
507 };
508 in_step(
509 "grant runtime copy",
510 sandbox.grant_tree(sandbox._assets.path(), false),
511 )?;
512 // Exact canonical bundle file only: never recursively grant its
513 // parent, which also contains the Builtin's private data.
514 in_step(
515 "grant host bundle",
516 sandbox.grant_file(bundle, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, true),
517 )?;
518 // Bun's resolver lists the directory holding its entry file and
519 // refuses the entry when it cannot ("Module not found"); it treats
520 // unreadable ancestors as opaque. List that one directory only:
521 // no inheritance, so its other files (embedded builtin modules,
522 // notices) stay denied, and the Builtin's data beside it too.
523 // Node loads the entry by path and needs no listing.
524 if runtime.kind == HostRuntimeKind::Bun && !runtime.compiled {
525 in_step(
526 "list host bundle directory",
527 sandbox.grant_directory(
528 bundle
529 .parent()
530 .ok_or_else(|| io::Error::other("host bundle has no parent"))?,
531 ),
532 )?;
533 }
534 fs::create_dir_all(data.join("tmp"))?;
535 in_step("grant data directory", sandbox.grant_tree(data, true))?;
536 in_step("isolation probe", sandbox.probe(runtime, memory_cap))?;
537 Ok(sandbox)
538 };
539 work().map_err(|error| format!("Windows Native isolation could not be verified: {error}"))
540 }
541
542 /// Only call after the existing Rust Native receipt/hash check. The root
543 /// is a reviewed staged snapshot, never the mutable source or a link.
544 pub fn admit_root(&self, root: &Path) -> Result<(), String> {
545 self.grant_tree(root, false)
546 .map_err(|error| format!("cannot admit reviewed Windows bundle: {error}"))
547 }
548
549 pub fn grant_data_dir(&self, dir: &Path) -> Result<(), String> {
550 self.grant_tree(dir, true)
551 .map_err(|error| format!("cannot grant cohort data directory: {error}"))
552 }
553
554 fn grant_tree(&self, root: &Path, writable: bool) -> io::Result<()> {
555 let _serial = AclEditGuard::acquire()?;
556 let root_pin = WindowsDirectory::open_acl(root)?;
557 self.profile
558 .remember(root, root_pin.acl_handle()?, GrantKind::Tree)?;
559 let access = FILE_GENERIC_READ
560 | FILE_GENERIC_EXECUTE
561 | if writable {
562 FILE_GENERIC_WRITE | windows_sys::Win32::Storage::FileSystem::DELETE
563 } else {
564 0
565 };
566 set_acl(
567 root_pin.acl_handle()?,
568 self.profile.sid,
569 access,
570 OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
571 )?;
572 let mut pending = Vec::new();
573 let mut count = 1;
574 enqueue_pinned_children(root, &root_pin, &mut pending, count)?;
575 while let Some((path, parent_pin)) = pending.pop() {
576 count += 1;
577 if count > MAX_GRANT_ENTRIES {
578 return Err(io::Error::other("sandbox grant tree exceeds 65536 entries"));
579 }
580 let metadata = fs::symlink_metadata(&path)?;
581 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
582 return Err(io::Error::other(
583 "sandbox grant refuses a link/reparse point",
584 ));
585 }
586 if metadata.is_dir() {
587 let pin = parent_pin.open_acl_child(
588 path.file_name()
589 .ok_or_else(|| io::Error::other("grant has no filename"))?,
590 )?;
591 set_acl(
592 pin.acl_handle()?,
593 self.profile.sid,
594 access,
595 OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
596 )?;
597 enqueue_pinned_children(&path, &pin, &mut pending, count)?;
598 } else if metadata.is_file() {
599 self.grant_pinned_file(&parent_pin, &path, access, false)?;
600 } else {
601 return Err(io::Error::other(
602 "sandbox grant refuses a non-regular entry",
603 ));
604 }
605 }
606 Ok(())
607 }
608
609 /// Read/list/traverse on exactly one directory object. Not inherited:
610 /// each child keeps only the grants it is given explicitly.
611 fn grant_directory(&self, directory: &Path) -> io::Result<()> {
612 let _serial = AclEditGuard::acquire()?;
613 let pin = WindowsDirectory::open_acl(directory)?;
614 self.profile
615 .remember(directory, pin.acl_handle()?, GrantKind::Directory)?;
616 set_acl(
617 pin.acl_handle()?,
618 self.profile.sid,
619 FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
620 0,
621 )
622 }
623
624 fn grant_file(&self, path: &Path, access: u32, remember: bool) -> io::Result<()> {
625 let _serial = AclEditGuard::acquire()?;
626 let pin = WindowsDirectory::open(
627 path.parent()
628 .ok_or_else(|| io::Error::other("file has no parent"))?,
629 )?;
630 self.grant_pinned_file(&pin, path, access, remember)
631 }
632
633 // The owning grant entrypoint holds AclEditGuard. Tree files reuse the parent
634 // chain rather than reopen pinned directory objects. The
635 // child_path comparison is only a lexical invariant; the protection is the
636 // held no-write/no-delete parent chain plus acl_file's no-follow,
637 // regular, single-link checks.
638 fn grant_pinned_file(
639 &self,
640 parent_pin: &WindowsDirectory,
641 path: &Path,
642 access: u32,
643 remember: bool,
644 ) -> io::Result<()> {
645 if parent_pin.child_path(
646 path.file_name()
647 .ok_or_else(|| io::Error::other("file has no filename"))?,
648 )? != path
649 {
650 return Err(io::Error::other("grant left its pinned parent"));
651 }
652 let file = acl_file(path)?;
653 if remember {
654 self.profile.remember(path, &file, GrantKind::File)?;
655 }
656 set_acl(&file, self.profile.sid, access, 0)
657 }
658
659 fn probe(&self, runtime: &HostRuntime, memory_cap: u64) -> io::Result<()> {
660 let outside = tempfile::tempdir()?;
661 let mut reads = Vec::new();
662 for name in [
663 "codex-auth.json",
664 "dsh-credentials.yaml",
665 "builtin-private-state.json",
666 ] {
667 let path = outside.path().join(name);
668 fs::write(&path, b"non-secret-denial-control")?;
669 reads.push(path);
670 }
671 let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
672 listener.set_nonblocking(true)?;
673 let overrides = [
674 (
675 "CODEWHALE_WINDOWS_PROBE_INSIDE".to_string(),
676 self.data
677 .join(format!(".probe-{}", uuid::Uuid::new_v4()))
678 .to_string_lossy()
679 .into_owned(),
680 ),
681 (
682 "CODEWHALE_WINDOWS_PROBE_OUTSIDE".to_string(),
683 outside
684 .path()
685 .join("forbidden-write")
686 .to_string_lossy()
687 .into_owned(),
688 ),
689 (
690 "CODEWHALE_WINDOWS_PROBE_READS".to_string(),
691 serde_json::to_string(&reads)?,
692 ),
693 (
694 "CODEWHALE_WINDOWS_PROBE_PORT".to_string(),
695 listener.local_addr()?.port().to_string(),
696 ),
697 ];
698 let runtime_env = super::supervisor::runtime_env(runtime.kind);
699 let mut args = super::supervisor::runtime_args(runtime);
700 if runtime.compiled {
701 args.extend(["--tier=plugin".into(), "--windows-sandbox-probe".into()]);
702 } else {
703 args.extend([
704 "--input-type=module".into(),
705 "-e".into(),
706 format!("{PROBE_SOURCE}\nconsole.log(JSON.stringify(await windowsSandboxProbe()))"),
707 ]);
708 }
709 // Serialize the same sandbox-safe argv used to launch the parent.
710 let args = sandbox_args(&args, self._assets.path());
711 let child_args = (
712 "CODEWHALE_WINDOWS_PROBE_CHILD_ARGS".to_string(),
713 serde_json::to_string(&args)?,
714 );
715 let env = codewhale_runtime::child_env::sanitized_plugin_mcp_env_from(
716 std::env::vars_os(),
717 runtime_env
718 .iter()
719 .chain(&overrides)
720 .chain(std::iter::once(&child_args))
721 .map(|(k, v)| (k.as_str(), v.as_str())),
722 );
723 let mut probe = self.spawn_inner(&args, &env, memory_cap, false)?;
724 // Close input immediately. Fixed output is under 512 bytes; a runtime
725 // substitution that floods a pipe cannot evade the wait deadline.
726 drop(probe.stdin);
727 let status = match probe.child.wait_timeout(PROBE_DEADLINE) {
728 Ok(status) => status,
729 Err(error) => {
730 let _ = probe.child.tree.kill();
731 let _ = probe.child.wait_timeout(Duration::from_secs(2));
732 return Err(error);
733 }
734 };
735 let mut stdout = Vec::new();
736 File::from(probe.stdout)
737 .take(4097)
738 .read_to_end(&mut stdout)?;
739 let mut stderr = Vec::new();
740 File::from(probe.stderr)
741 .take(4097)
742 .read_to_end(&mut stderr)?;
743 if !status.success() || stdout.len() > 4096 {
744 return Err(io::Error::other(format!(
745 "isolation probe failed ({status}): {}",
746 String::from_utf8_lossy(&stderr)
747 )));
748 }
749 let expected = serde_json::json!({"version":1,"data_roundtrip":true,"outside_read_denied":true,"outside_write_denied":true,"network_denied":true,"descendant_denied":true});
750 if serde_json::from_slice::<serde_json::Value>(&stdout)? != expected
751 || listener.accept().is_ok()
752 {
753 return Err(io::Error::other(
754 "sandbox probe returned no exact allow/deny receipt",
755 ));
756 }
757 Ok(())
758 }
759
760 pub fn spawn(
761 &self,
762 args: &[String],
763 env: &[(OsString, OsString)],
764 memory_cap: u64,
765 ) -> io::Result<Spawned> {
766 let args = sandbox_args(args, self._assets.path());
767 self.spawn_inner(&args, env, memory_cap, true)
768 }
769
770 fn spawn_inner(
771 &self,
772 args: &[String],
773 env: &[(OsString, OsString)],
774 memory_cap: u64,
775 overlapped: bool,
776 ) -> io::Result<Spawned> {
777 let (stdin, child_stdin) = pipe(false, overlapped)?;
778 let (stdout, child_stdout) = pipe(true, overlapped)?;
779 let (stderr, child_stderr) = pipe(true, overlapped)?;
780 let mut attrs = Attributes::new(4)?;
781 let registry_read = CapabilitySid::registry_read()?;
782 let capability_sid = registry_read.sid();
783 let mut capability = SID_AND_ATTRIBUTES {
784 Sid: capability_sid,
785 Attributes: windows_sys::Win32::System::SystemServices::SE_GROUP_ENABLED as u32,
786 };
787 let capabilities = SECURITY_CAPABILITIES {
788 AppContainerSid: self.profile.sid,
789 Capabilities: &mut capability,
790 CapabilityCount: 1,
791 Reserved: 0,
792 };
793 let lpac = PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT;
794 // Core creates this LPAC from an unrestricted process, so it can opt
795 // the runtime into spawning descendants. Windows gives those children
796 // the parent's AppContainer token and, by default, the same Job; the
797 // startup probe verifies that they keep the same file/network limits.
798 let child_process_policy = PROCESS_CREATION_CHILD_PROCESS_OVERRIDE;
799 let handles = [
800 child_stdin.as_raw_handle(),
801 child_stdout.as_raw_handle(),
802 child_stderr.as_raw_handle(),
803 ];
804 attrs.set(PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, &capabilities)?;
805 attrs.set(PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY, &lpac)?;
806 attrs.set(
807 PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY,
808 &child_process_policy,
809 )?;
810 attrs.set_slice(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &handles)?;
811 let mut startup: STARTUPINFOEXW = unsafe { zeroed() };
812 startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
813 startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
814 startup.StartupInfo.hStdInput = child_stdin.as_raw_handle();
815 startup.StartupInfo.hStdOutput = child_stdout.as_raw_handle();
816 startup.StartupInfo.hStdError = child_stderr.as_raw_handle();
817 startup.lpAttributeList = attrs.ptr();
818 let application = wide(self.program.as_os_str())?;
819 let mut command = command_line(self.program.as_os_str(), args)?;
820 let directory = wide(self.data.as_os_str())?;
821 let mut env = env.to_vec();
822 let temp = self.data.join("tmp").into_os_string();
823 for key in ["TEMP", "TMP", "TMPDIR"] {
824 env.retain(|(name, _)| !name.to_string_lossy().eq_ignore_ascii_case(key));
825 env.push((key.into(), temp.clone()));
826 }
827 let environment = environment_block(&env)?;
828 let mut info: PROCESS_INFORMATION = unsafe { zeroed() };
829 // SAFETY: owned attribute backing/storage/argv/environment outlive
830 // this call; HANDLE_LIST is precisely the three inheritable pipe ends.
831 let created = unsafe {
832 CreateProcessW(
833 application.as_ptr(),
834 command.as_mut_ptr(),
835 null(),
836 null(),
837 1,
838 CREATE_SUSPENDED
839 | CREATE_NO_WINDOW
840 | CREATE_UNICODE_ENVIRONMENT
841 | EXTENDED_STARTUPINFO_PRESENT,
842 environment.as_ptr().cast(),
843 directory.as_ptr(),
844 &startup.StartupInfo,
845 &mut info,
846 )
847 };
848 if created == 0 {
849 return Err(io::Error::last_os_error());
850 }
851 let process = unsafe { OwnedHandle::from_raw_handle(info.hProcess) };
852 let thread = unsafe { OwnedHandle::from_raw_handle(info.hThread) };
853 let setup = || -> io::Result<Arc<ProcessTree>> {
854 let tree = Arc::new(ProcessTree::attach_windows_handle(
855 info.dwProcessId,
856 &process,
857 )?);
858 tree.limit_process_memory(memory_cap)?;
859 verify_token(&process, self.profile.sid, capability_sid)?;
860 // No Native byte executes until Job, memory and actual LPAC token
861 // identity/capabilities have all been checked by Rust.
862 if unsafe { ResumeThread(thread.as_raw_handle()) } != 1 {
863 return Err(io::Error::other(
864 "Native main thread did not resume from its exact suspended state",
865 ));
866 }
867 Ok(tree)
868 };
869 let tree = match setup() {
870 Ok(tree) => tree,
871 Err(error) => {
872 unsafe {
873 windows_sys::Win32::System::Threading::TerminateProcess(
874 process.as_raw_handle(),
875 70,
876 );
877 WaitForSingleObject(process.as_raw_handle(), 2000);
878 }
879 return Err(error);
880 }
881 };
882 drop((child_stdin, child_stdout, child_stderr, thread));
883 Ok(Spawned {
884 child: Child {
885 process: Arc::new(process),
886 tree,
887 pid: info.dwProcessId,
888 _sandbox: self.clone(),
889 reaped: false,
890 },
891 stdin,
892 stdout,
893 stderr,
894 })
895 }
896 }
897
898 pub struct Spawned {
899 pub child: Child,
900 pub stdin: OwnedHandle,
901 pub stdout: OwnedHandle,
902 pub stderr: OwnedHandle,
903 }
904
905 pub struct Child {
906 process: Arc<OwnedHandle>,
907 pub tree: Arc<ProcessTree>,
908 pub pid: u32,
909 _sandbox: NativeSandbox,
910 reaped: bool,
911 }
912
913 impl Child {
914 pub async fn wait(&mut self) -> io::Result<std::process::ExitStatus> {
915 let process = Arc::clone(&self.process);
916 let sandbox = self._sandbox.clone();
917 let status = tokio::task::spawn_blocking(move || {
918 let _sandbox = sandbox;
919 wait(&process, u32::MAX)
920 })
921 .await
922 .map_err(io::Error::other)??;
923 self.reaped = true;
924 Ok(status)
925 }
926 pub async fn kill(&mut self) -> io::Result<()> {
927 self.tree.kill()?;
928 self.wait().await.map(|_| ())
929 }
930 fn wait_timeout(&mut self, after: Duration) -> io::Result<std::process::ExitStatus> {
931 let status = wait(
932 &self.process,
933 after.as_millis().min(u32::MAX as u128 - 1) as u32,
934 )?;
935 self.reaped = true;
936 // The fixed probe must not retain background descendants/pipe handles.
937 let _ = self.tree.kill();
938 Ok(status)
939 }
940 }
941
942 impl Drop for Child {
943 fn drop(&mut self) {
944 if !self.reaped {
945 let _ = self.tree.kill();
946 }
947 }
948 }
949
950 fn wait(process: &OwnedHandle, timeout: u32) -> io::Result<std::process::ExitStatus> {
951 use std::os::windows::process::ExitStatusExt;
952 match unsafe { WaitForSingleObject(process.as_raw_handle(), timeout) } {
953 WAIT_OBJECT_0 => {
954 let mut status = 0;
955 if unsafe { GetExitCodeProcess(process.as_raw_handle(), &mut status) } == 0 {
956 return Err(io::Error::last_os_error());
957 }
958 Ok(std::process::ExitStatus::from_raw(status))
959 }
960 WAIT_TIMEOUT => Err(io::Error::new(
961 io::ErrorKind::TimedOut,
962 "Windows sandbox probe exceeded launch deadline",
963 )),
964 _ => Err(io::Error::last_os_error()),
965 }
966 }
967
968 fn verify_token(process: &OwnedHandle, sid: PSID, capability: PSID) -> io::Result<()> {
969 let mut token = null_mut();
970 if unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut token) } == 0 {
971 return Err(io::Error::last_os_error());
972 }
973 let token = unsafe { OwnedHandle::from_raw_handle(token) };
974 // AppContainer must be confirmed, and LPAC through the token flag or, when
975 // that query fails (hosted Windows Server returned ERROR_INVALID_PARAMETER;
976 // the cause is unknown), through the `WIN://NOALLAPPPKG` security
977 // attribute the LPAC opt-out adds (ntdoc; NtObjectManager's
978 // LowPrivilegeAppContainer). Report each observation, so a refusal says
979 // which property the kernel did not confirm.
980 let query = |class| -> io::Result<u32> {
981 let mut value = 0_u32;
982 let mut read = 0;
983 if unsafe {
984 GetTokenInformation(
985 token.as_raw_handle(),
986 class,
987 (&mut value as *mut u32).cast(),
988 size_of::<u32>() as u32,
989 &mut read,
990 )
991 } == 0
992 {
993 return Err(io::Error::last_os_error());
994 }
995 Ok(value)
996 };
997 let mut observed = Vec::new();
998 let app_container = match query(TokenIsAppContainer) {
999 Ok(value) => {
1000 observed.push(format!("TokenIsAppContainer={value}"));
1001 value == 1
1002 }
1003 Err(error) => {
1004 observed.push(format!("TokenIsAppContainer query failed: {error}"));
1005 false
1006 }
1007 };
1008 let less_privileged = match query(TokenIsLessPrivilegedAppContainer) {
1009 Ok(value) => {
1010 observed.push(format!("TokenIsLessPrivilegedAppContainer={value}"));
1011 value == 1
1012 }
1013 Err(error) => {
1014 observed.push(format!(
1015 "TokenIsLessPrivilegedAppContainer query failed: {error}"
1016 ));
1017 match token_has_lpac_attribute(&token) {
1018 Ok(true) => {
1019 observed.push("WIN://NOALLAPPPKG=1".to_string());
1020 true
1021 }
1022 Ok(false) => {
1023 observed.push("WIN://NOALLAPPPKG absent".to_string());
1024 false
1025 }
1026 Err(error) => {
1027 observed.push(format!("WIN://NOALLAPPPKG unreadable: {error}"));
1028 false
1029 }
1030 }
1031 }
1032 };
1033 if !(app_container && less_privileged) {
1034 return Err(io::Error::other(format!(
1035 "Windows refused the required LPAC token ({})",
1036 observed.join(", ")
1037 )));
1038 }
1039 // Variable-size token buffers are aligned for their SDK structs.
1040 for class in [TokenAppContainerSid, TokenCapabilities] {
1041 let mut size = 0;
1042 unsafe {
1043 GetTokenInformation(token.as_raw_handle(), class, null_mut(), 0, &mut size);
1044 }
1045 if size == 0 || size > 64 * 1024 {
1046 return Err(io::Error::other("invalid sandbox token size"));
1047 }
1048 let mut buffer = vec![0_usize; (size as usize).div_ceil(size_of::<usize>())];
1049 if unsafe {
1050 GetTokenInformation(
1051 token.as_raw_handle(),
1052 class,
1053 buffer.as_mut_ptr().cast(),
1054 size,
1055 &mut size,
1056 )
1057 } == 0
1058 {
1059 return Err(io::Error::last_os_error());
1060 }
1061 let valid = unsafe {
1062 if class == TokenAppContainerSid {
1063 let value = &*buffer.as_ptr().cast::<TOKEN_APPCONTAINER_INFORMATION>();
1064 !value.TokenAppContainer.is_null() && EqualSid(value.TokenAppContainer, sid) != 0
1065 } else {
1066 // Exactly the one granted capability, and nothing else.
1067 let groups = &*buffer.as_ptr().cast::<TOKEN_GROUPS>();
1068 groups.GroupCount == 1 && EqualSid(groups.Groups[0].Sid, capability) != 0
1069 }
1070 };
1071 if !valid {
1072 return Err(io::Error::other(
1073 "sandbox token has unexpected identity/capabilities",
1074 ));
1075 }
1076 }
1077 Ok(())
1078 }
1079
1080 /// Whether the token carries the LPAC opt-out attribute `WIN://NOALLAPPPKG`
1081 /// with a nonzero integer value. `TokenSecurityAttributes` (Windows 8+)
1082 /// returns TOKEN_SECURITY_ATTRIBUTES_INFORMATION whose pointers are absolute
1083 /// addresses into the returned buffer; each is checked to be aligned and to
1084 /// stay inside it before it is read.
1085 fn token_has_lpac_attribute(token: &OwnedHandle) -> io::Result<bool> {
1086 use windows_sys::Win32::Security::TokenSecurityAttributes;
1087 #[repr(C)]
1088 struct UnicodeString {
1089 length: u16,
1090 maximum_length: u16,
1091 buffer: *const u16,
1092 }
1093 #[repr(C)]
1094 struct AttributeV1 {
1095 name: UnicodeString,
1096 value_type: u16,
1097 reserved: u16,
1098 flags: u32,
1099 value_count: u32,
1100 values: *const u64,
1101 }
1102 #[repr(C)]
1103 struct AttributesInformation {
1104 version: u16,
1105 reserved: u16,
1106 attribute_count: u32,
1107 attributes: *const AttributeV1,
1108 }
1109 const VERSION_V1: u16 = 1;
1110 const TYPE_INT64: u16 = 1;
1111 const TYPE_UINT64: u16 = 2;
1112 let mut size = 0;
1113 unsafe {
1114 GetTokenInformation(
1115 token.as_raw_handle(),
1116 TokenSecurityAttributes,
1117 null_mut(),
1118 0,
1119 &mut size,
1120 );
1121 }
1122 if (size as usize) < size_of::<AttributesInformation>() || size > 64 * 1024 {
1123 return Err(io::Error::other("invalid token security attribute size"));
1124 }
1125 let mut buffer = vec![0_usize; (size as usize).div_ceil(size_of::<usize>())];
1126 if unsafe {
1127 GetTokenInformation(
1128 token.as_raw_handle(),
1129 TokenSecurityAttributes,
1130 buffer.as_mut_ptr().cast(),
1131 size,
1132 &mut size,
1133 )
1134 } == 0
1135 {
1136 return Err(io::Error::last_os_error());
1137 }
1138 let start = buffer.as_ptr() as usize;
1139 let end = start + buffer.len() * size_of::<usize>();
1140 let inside = |pointer: usize, bytes: usize, align: usize| {
1141 pointer % align == 0
1142 && pointer >= start
1143 && pointer.checked_add(bytes).is_some_and(|last| last <= end)
1144 };
1145 let information = unsafe { &*buffer.as_ptr().cast::<AttributesInformation>() };
1146 if information.version != VERSION_V1 {
1147 return Err(io::Error::other("unknown token security attribute version"));
1148 }
1149 let count = information.attribute_count as usize;
1150 if count == 0 {
1151 return Ok(false);
1152 }
1153 if !count
1154 .checked_mul(size_of::<AttributeV1>())
1155 .is_some_and(|bytes| {
1156 inside(
1157 information.attributes as usize,
1158 bytes,
1159 align_of::<AttributeV1>(),
1160 )
1161 })
1162 {
1163 return Err(io::Error::other(
1164 "token security attributes exceed their buffer",
1165 ));
1166 }
1167 for index in 0..count {
1168 let attribute = unsafe { &*information.attributes.add(index) };
1169 let name_bytes = usize::from(attribute.name.length);
1170 if name_bytes % 2 != 0
1171 || !inside(
1172 attribute.name.buffer as usize,
1173 name_bytes,
1174 align_of::<u16>(),
1175 )
1176 {
1177 return Err(io::Error::other(
1178 "token security attribute name exceeds its buffer",
1179 ));
1180 }
1181 let name = unsafe { std::slice::from_raw_parts(attribute.name.buffer, name_bytes / 2) };
1182 if !String::from_utf16_lossy(name).eq_ignore_ascii_case("WIN://NOALLAPPPKG") {
1183 continue;
1184 }
1185 let values = attribute.value_count as usize;
1186 if !matches!(attribute.value_type, TYPE_INT64 | TYPE_UINT64)
1187 || values == 0
1188 || !values
1189 .checked_mul(size_of::<u64>())
1190 .is_some_and(|bytes| inside(attribute.values as usize, bytes, align_of::<u64>()))
1191 {
1192 return Ok(false);
1193 }
1194 return Ok(unsafe { *attribute.values } != 0);
1195 }
1196 Ok(false)
1197 }
1198
1199 /// The only capability a Native LPAC host receives: `registryRead`. Without
1200 /// it an LPAC cannot open any registry key, so Winsock initialization, which
1201 /// reads its catalog under HKLM, fails and Node aborts at startup. It grants
1202 /// no file, network or COM access; socket creation stays denied, which the
1203 /// isolation probe checks.
1204 struct CapabilitySid {
1205 sid: PSID,
1206 sids: *mut PSID,
1207 count: u32,
1208 groups: *mut PSID,
1209 group_count: u32,
1210 }
1211
1212 impl CapabilitySid {
1213 fn registry_read() -> io::Result<Self> {
1214 use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
1215 use windows_sys::core::BOOL;
1216 type DeriveCapabilitySidsFromName = unsafe extern "system" fn(
1217 *const u16,
1218 *mut *mut PSID,
1219 *mut u32,
1220 *mut *mut PSID,
1221 *mut u32,
1222 ) -> BOOL;
1223 let module = wide(OsStr::new("kernelbase.dll"))?;
1224 // SAFETY: nul-terminated module name; the module stays loaded for the process.
1225 let handle = unsafe { GetModuleHandleW(module.as_ptr()) };
1226 let address = if handle.is_null() {
1227 None
1228 } else {
1229 // SAFETY: nul-terminated export name and a live module handle.
1230 unsafe { GetProcAddress(handle, c"DeriveCapabilitySidsFromName".as_ptr().cast()) }
1231 };
1232 let Some(address) = address else {
1233 return Err(io::Error::new(
1234 io::ErrorKind::Unsupported,
1235 "this Windows build cannot derive LPAC capability SIDs (DeriveCapabilitySidsFromName is unavailable), so Native plugin hosts are not supported here",
1236 ));
1237 };
1238 // SAFETY: the export has exactly this documented signature.
1239 let derive: DeriveCapabilitySidsFromName = unsafe { std::mem::transmute(address) };
1240 let name = wide(OsStr::new("registryRead"))?;
1241 let mut value = Self {
1242 sid: null_mut(),
1243 sids: null_mut(),
1244 count: 0,
1245 groups: null_mut(),
1246 group_count: 0,
1247 };
1248 // SAFETY: nul-terminated name and initialized out pointers; the
1249 // returned arrays and SIDs are freed by Drop with LocalFree.
1250 if unsafe {
1251 derive(
1252 name.as_ptr(),
1253 &mut value.groups,
1254 &mut value.group_count,
1255 &mut value.sids,
1256 &mut value.count,
1257 )
1258 } == 0
1259 {
1260 return Err(io::Error::last_os_error());
1261 }
1262 if value.count != 1 || value.sids.is_null() {
1263 return Err(io::Error::other(
1264 "registryRead did not derive exactly one capability SID",
1265 ));
1266 }
1267 // SAFETY: DeriveCapabilitySidsFromName succeeded, and the checked
1268 // count says its owned array contains exactly one PSID. The array and
1269 // SID stay alive in `value` until its Drop implementation frees them.
1270 value.sid = unsafe { std::slice::from_raw_parts(value.sids, 1)[0] };
1271 Ok(value)
1272 }
1273
1274 fn sid(&self) -> PSID {
1275 self.sid
1276 }
1277 }
1278
1279 impl Drop for CapabilitySid {
1280 fn drop(&mut self) {
1281 // SAFETY: each SID and each array came from DeriveCapabilitySidsFromName.
1282 unsafe {
1283 for (array, count) in [(self.sids, self.count), (self.groups, self.group_count)] {
1284 if array.is_null() {
1285 continue;
1286 }
1287 for index in 0..count as usize {
1288 LocalFree(*array.add(index));
1289 }
1290 LocalFree(array.cast());
1291 }
1292 }
1293 }
1294 }
1295
1296 fn set_acl(file: &File, sid: PSID, access: u32, inheritance: u32) -> io::Result<()> {
1297 edit_acl(file, sid, access, inheritance, GRANT_ACCESS)
1298 }
1299 /// Edit exactly one SID's allow entries on this pinned handle. Read the stored
1300 /// descriptor with GetKernelObjectSecurity: GetSecurityInfo can normalize a
1301 /// child's inherited ACEs/control while its parent has a grant. Writing that
1302 /// view back freezes the normalized state. The exact kernel reader/writer pair
1303 /// preserves every other ACE and never propagates changes to child objects.
1304 fn edit_acl(
1305 file: &File,
1306 sid: PSID,
1307 access: u32,
1308 inheritance: u32,
1309 mode: windows_sys::Win32::Security::Authorization::ACCESS_MODE,
1310 ) -> io::Result<()> {
1311 use windows_sys::Win32::Security::{
1312 ACCESS_ALLOWED_ACE, ACE_HEADER, AddAccessAllowedAceEx, AddAce, GetAce, GetLengthSid,
1313 INHERITED_ACE, InitializeAcl, InitializeSecurityDescriptor, SE_DACL_AUTO_INHERIT_REQ,
1314 SE_DACL_AUTO_INHERITED, SE_DACL_PROTECTED, SECURITY_DESCRIPTOR, SetKernelObjectSecurity,
1315 SetSecurityDescriptorControl, SetSecurityDescriptorDacl,
1316 };
1317 use windows_sys::Win32::System::SystemServices::{
1318 ACCESS_ALLOWED_ACE_TYPE, SECURITY_DESCRIPTOR_REVISION,
1319 };
1320 // The owning grant/retirement entrypoint holds AclEditGuard while opening
1321 // and editing its exact objects, including all shared pinned ancestors.
1322 let grant = mode == GRANT_ACCESS;
1323 if !grant && mode != REVOKE_ACCESS {
1324 return Err(io::Error::other("unsupported ACL edit mode"));
1325 }
1326 let descriptor = RawDacl::read(file)?;
1327 let old_acl = descriptor.acl();
1328 let preserved = descriptor.control & (SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED);
1329 let old = std::ptr::NonNull::new(old_acl)
1330 .ok_or_else(|| io::Error::other("refusing to replace an unrestricted DACL"))?;
1331 let (acl_revision, acl_size, ace_count) = {
1332 // SAFETY: RawDacl validated this DACL inside its owned descriptor.
1333 let acl = unsafe { old.as_ref() };
1334 (
1335 u32::from(acl.AclRevision),
1336 usize::from(acl.AclSize),
1337 acl.AceCount,
1338 )
1339 };
1340 let added = if grant {
1341 size_of::<ACCESS_ALLOWED_ACE>() - size_of::<u32>() + unsafe { GetLengthSid(sid) } as usize
1342 } else {
1343 0
1344 };
1345 let size = acl_size + added;
1346 if size > 0xFFFC {
1347 return Err(io::Error::other("edited DACL exceeds the ACL size limit"));
1348 }
1349 // ACLs must be DWORD aligned.
1350 let mut storage = vec![0_u32; size.div_ceil(size_of::<u32>())];
1351 let new_acl = storage.as_mut_ptr().cast::<ACL>();
1352 if unsafe {
1353 InitializeAcl(
1354 new_acl,
1355 (storage.len() * size_of::<u32>()) as u32,
1356 acl_revision,
1357 )
1358 } == 0
1359 {
1360 return Err(io::Error::last_os_error());
1361 }
1362 let mut merged = access;
1363 let mut inserted = !grant;
1364 for index in 0..u32::from(ace_count) {
1365 let mut ace = null_mut();
1366 if unsafe { GetAce(old_acl, index, &mut ace) } == 0 {
1367 return Err(io::Error::last_os_error());
1368 }
1369 let ace = std::ptr::NonNull::new(ace)
1370 .ok_or_else(|| io::Error::other("GetAce returned no entry"))?;
1371 // SAFETY: GetAce returned a pointer to an entry inside the live DACL.
1372 let header = unsafe { ace.cast::<ACE_HEADER>().as_ref() };
1373 let flags = u32::from(header.AceFlags);
1374 let inherited = flags & INHERITED_ACE != 0;
1375 // Only ACCESS_ALLOWED_ACE carries its SID at SidStart.
1376 let ours = u32::from(header.AceType) == ACCESS_ALLOWED_ACE_TYPE
1377 && usize::from(header.AceSize) >= size_of::<ACCESS_ALLOWED_ACE>()
1378 && unsafe {
1379 EqualSid(
1380 std::ptr::addr_of_mut!((*ace.cast::<ACCESS_ALLOWED_ACE>().as_ptr()).SidStart)
1381 .cast(),
1382 sid,
1383 )
1384 } != 0;
1385 if ours && grant && !inherited && flags == inheritance {
1386 // GRANT_ACCESS semantics: combine with the existing explicit grant.
1387 merged |= unsafe { ace.cast::<ACCESS_ALLOWED_ACE>().as_ref().Mask };
1388 continue;
1389 }
1390 if ours && !grant {
1391 // Retirement removes explicit entries and the stale inherited
1392 // copies left after the parent's grant was revoked first.
1393 continue;
1394 }
1395 if !inserted && inherited {
1396 // Explicit entries precede inherited ones.
1397 if unsafe { AddAccessAllowedAceEx(new_acl, acl_revision, inheritance, merged, sid) }
1398 == 0
1399 {
1400 return Err(io::Error::last_os_error());
1401 }
1402 inserted = true;
1403 }
1404 if unsafe {
1405 AddAce(
1406 new_acl,
1407 acl_revision,
1408 u32::MAX,
1409 ace.as_ptr(),
1410 u32::from(header.AceSize),
1411 )
1412 } == 0
1413 {
1414 return Err(io::Error::last_os_error());
1415 }
1416 }
1417 if !inserted
1418 && unsafe { AddAccessAllowedAceEx(new_acl, acl_revision, inheritance, merged, sid) } == 0
1419 {
1420 return Err(io::Error::last_os_error());
1421 }
1422 let mut security: SECURITY_DESCRIPTOR = unsafe { zeroed() };
1423 let security_ptr = (&mut security as *mut SECURITY_DESCRIPTOR).cast();
1424 // NTFS stores this descriptor as given, with no inheritance merge. The
1425 // kernel keeps SE_DACL_AUTO_INHERITED only when SE_DACL_AUTO_INHERIT_REQ
1426 // accompanies it, so request it exactly when the object already had it;
1427 // otherwise the object would silently become a legacy DACL.
1428 let requested = preserved
1429 | if preserved & SE_DACL_AUTO_INHERITED != 0 {
1430 SE_DACL_AUTO_INHERIT_REQ
1431 } else {
1432 0
1433 };
1434 if unsafe { InitializeSecurityDescriptor(security_ptr, SECURITY_DESCRIPTOR_REVISION) } == 0
1435 || unsafe { SetSecurityDescriptorDacl(security_ptr, 1, new_acl, 0) } == 0
1436 || unsafe {
1437 SetSecurityDescriptorControl(
1438 security_ptr,
1439 SE_DACL_AUTO_INHERIT_REQ | SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED,
1440 requested,
1441 )
1442 } == 0
1443 || unsafe {
1444 SetKernelObjectSecurity(
1445 file.as_raw_handle(),
1446 DACL_SECURITY_INFORMATION,
1447 security_ptr,
1448 )
1449 } == 0
1450 {
1451 return Err(io::Error::last_os_error());
1452 }
1453 drop(descriptor);
1454 let (still_granted, control) = read_back_dacl(file, sid)?;
1455 // The raw descriptor and exact kernel write preserve both bits on files
1456 // and directories, without re-deriving or propagating inherited entries.
1457 let checked = SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED;
1458 if control & checked != preserved & checked {
1459 return Err(io::Error::other(
1460 "edited DACL changed its inheritance control bits",
1461 ));
1462 }
1463 if !grant && still_granted {
1464 return Err(io::Error::other(
1465 "retired profile SID is still present after ACL retirement",
1466 ));
1467 }
1468 Ok(())
1469 }
1470
1471 /// Read back the object's DACL: whether any allow entry names `sid`, and the
1472 /// descriptor's control bits.
1473 fn read_back_dacl(file: &File, sid: PSID) -> io::Result<(bool, u16)> {
1474 use windows_sys::Win32::Security::{ACCESS_ALLOWED_ACE, ACE_HEADER, GetAce};
1475 use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
1476 let descriptor = RawDacl::read(file)?;
1477 let acl = descriptor.acl();
1478 let control = descriptor.control;
1479 let dacl = std::ptr::NonNull::new(acl)
1480 .ok_or_else(|| io::Error::other("refusing to inspect an unrestricted DACL"))?;
1481 // SAFETY: RawDacl validated this DACL inside its owned descriptor.
1482 for index in 0..u32::from(unsafe { dacl.as_ref().AceCount }) {
1483 let mut ace = null_mut();
1484 if unsafe { GetAce(acl, index, &mut ace) } == 0 {
1485 return Err(io::Error::last_os_error());
1486 }
1487 let ace = std::ptr::NonNull::new(ace)
1488 .ok_or_else(|| io::Error::other("GetAce returned no entry"))?;
1489 // SAFETY: GetAce returned a pointer to an entry inside the live DACL.
1490 let header = unsafe { ace.cast::<ACE_HEADER>().as_ref() };
1491 if u32::from(header.AceType) == ACCESS_ALLOWED_ACE_TYPE
1492 && usize::from(header.AceSize) >= size_of::<ACCESS_ALLOWED_ACE>()
1493 && unsafe {
1494 EqualSid(
1495 std::ptr::addr_of_mut!((*ace.cast::<ACCESS_ALLOWED_ACE>().as_ptr()).SidStart)
1496 .cast(),
1497 sid,
1498 )
1499 } != 0
1500 {
1501 return Ok((true, control));
1502 }
1503 }
1504 Ok((false, control))
1505 }
1506
1507 /// Owned DWORD-aligned storage for a bounded self-relative kernel descriptor.
1508 /// The ACL offset is validated once and never outlives this allocation.
1509 struct RawDacl {
1510 storage: Vec<u32>,
1511 acl_offset: usize,
1512 control: u16,
1513 }
1514 impl RawDacl {
1515 fn read(file: &File) -> io::Result<Self> {
1516 use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
1517 use windows_sys::Win32::Security::{GetKernelObjectSecurity, SECURITY_DESCRIPTOR_RELATIVE};
1518 let mut required = 0_u32;
1519 // SAFETY: a zero-length size query writes only `required`.
1520 if unsafe {
1521 GetKernelObjectSecurity(
1522 file.as_raw_handle(),
1523 DACL_SECURITY_INFORMATION,
1524 null_mut(),
1525 0,
1526 &mut required,
1527 )
1528 } == 0
1529 {
1530 let error = io::Error::last_os_error();
1531 if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) {
1532 return Err(error);
1533 }
1534 }
1535 // An external ACL writer can change the required size between calls.
1536 // Bound both the allocation and the number of attempts; fail closed.
1537 for _ in 0..3 {
1538 if !(size_of::<SECURITY_DESCRIPTOR_RELATIVE>()..=1024 * 1024)
1539 .contains(&(required as usize))
1540 {
1541 return Err(io::Error::other(
1542 "kernel security descriptor exceeds size bounds",
1543 ));
1544 }
1545 let capacity = required;
1546 let mut storage = vec![0_u32; (capacity as usize).div_ceil(size_of::<u32>())];
1547 // SAFETY: storage is aligned, owned, and at least capacity bytes.
1548 if unsafe {
1549 GetKernelObjectSecurity(
1550 file.as_raw_handle(),
1551 DACL_SECURITY_INFORMATION,
1552 storage.as_mut_ptr().cast(),
1553 capacity,
1554 &mut required,
1555 )
1556 } == 0
1557 {
1558 let error = io::Error::last_os_error();
1559 if error.raw_os_error() == Some(ERROR_INSUFFICIENT_BUFFER as i32)
1560 && required > capacity
1561 {
1562 continue;
1563 }
1564 return Err(error);
1565 }
1566 if required > capacity {
1567 return Err(io::Error::other(
1568 "kernel security descriptor exceeds its buffer",
1569 ));
1570 }
1571 return Self::from_storage(storage, required as usize);
1572 }
1573 Err(io::Error::other(
1574 "kernel security descriptor repeatedly changed size",
1575 ))
1576 }
1577
1578 fn from_storage(mut storage: Vec<u32>, length: usize) -> io::Result<Self> {
1579 use windows_sys::Win32::Security::{
1580 ACCESS_ALLOWED_ACE, ACE_HEADER, GetAce, GetSecurityDescriptorControl,
1581 GetSecurityDescriptorDacl, IsValidAcl, IsValidSid, SE_SELF_RELATIVE,
1582 SECURITY_DESCRIPTOR_RELATIVE, SID,
1583 };
1584 use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
1585 if length < size_of::<SECURITY_DESCRIPTOR_RELATIVE>()
1586 || length > storage.len() * size_of::<u32>()
1587 {
1588 return Err(io::Error::other("kernel security descriptor is truncated"));
1589 }
1590 let descriptor = storage.as_mut_ptr().cast();
1591 let mut control = 0_u16;
1592 let mut revision = 0_u32;
1593 // SAFETY: the aligned allocation contains the complete descriptor header.
1594 if unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) } == 0 {
1595 return Err(io::Error::last_os_error());
1596 }
1597 if control & SE_SELF_RELATIVE == 0 {
1598 return Err(io::Error::other(
1599 "kernel security descriptor is not self-relative",
1600 ));
1601 }
1602 let mut present = 0;
1603 let mut defaulted = 0;
1604 let mut acl: *mut ACL = null_mut();
1605 // SAFETY: only the validated self-relative header is read here. Bound
1606 // the returned DACL pointer before dereferencing any of its bytes.
1607 if unsafe { GetSecurityDescriptorDacl(descriptor, &mut present, &mut acl, &mut defaulted) }
1608 == 0
1609 {
1610 return Err(io::Error::last_os_error());
1611 }
1612 if present == 0 || acl.is_null() {
1613 return Err(io::Error::other("refusing an absent or unrestricted DACL"));
1614 }
1615 let acl_offset = (acl as usize)
1616 .checked_sub(descriptor as usize)
1617 .filter(|offset| {
1618 *offset >= size_of::<SECURITY_DESCRIPTOR_RELATIVE>()
1619 && *offset % size_of::<u32>() == 0
1620 && offset
1621 .checked_add(size_of::<ACL>())
1622 .is_some_and(|end| end <= length)
1623 })
1624 .ok_or_else(|| io::Error::other("DACL header is outside its descriptor"))?;
1625 // Read through owned storage at the checked offset, not through the
1626 // out-pointer Windows returned: same address, owned provenance.
1627 // SAFETY: acl_offset + size_of::<ACL>() <= length <= storage bytes.
1628 let acl = unsafe { storage.as_ptr().cast::<u8>().add(acl_offset) }
1629 .cast_mut()
1630 .cast::<ACL>();
1631 // SAFETY: the aligned DACL header lies completely inside storage.
1632 let acl_size = usize::from(unsafe { (*acl).AclSize });
1633 if acl_size < size_of::<ACL>()
1634 || acl_offset
1635 .checked_add(acl_size)
1636 .is_none_or(|end| end > length)
1637 {
1638 return Err(io::Error::other("DACL is outside its descriptor"));
1639 }
1640 // SAFETY: the entire claimed ACL extent is bounded by owned storage.
1641 // IsValidAcl checks revision and whether its ACEs fit that extent.
1642 if unsafe { IsValidAcl(acl) } == 0 {
1643 return Err(io::Error::other(
1644 "kernel descriptor contains an invalid ACL",
1645 ));
1646 }
1647 for index in 0..u32::from(unsafe { (*acl).AceCount }) {
1648 let mut entry = null_mut();
1649 if unsafe { GetAce(acl, index, &mut entry) } == 0 {
1650 return Err(io::Error::last_os_error());
1651 }
1652 let entry_offset = (entry as usize)
1653 .checked_sub(acl as usize)
1654 .filter(|offset| {
1655 *offset >= size_of::<ACL>()
1656 && *offset % size_of::<u32>() == 0
1657 && offset
1658 .checked_add(size_of::<ACE_HEADER>())
1659 .is_some_and(|end| end <= acl_size)
1660 })
1661 .ok_or_else(|| io::Error::other("ACE header is outside its DACL"))?;
1662 // Same rule: address the ACE from the storage-derived ACL.
1663 // SAFETY: entry_offset + size_of::<ACE_HEADER>() <= acl_size.
1664 let entry = unsafe { acl.cast::<u8>().add(entry_offset) };
1665 // SAFETY: the complete, aligned ACE header is inside the DACL.
1666 let header = unsafe { &*entry.cast::<ACE_HEADER>() };
1667 let entry_size = usize::from(header.AceSize);
1668 if entry_size < size_of::<ACE_HEADER>() || entry_offset + entry_size > acl_size {
1669 return Err(io::Error::other("ACE is outside its DACL"));
1670 }
1671 if u32::from(header.AceType) == ACCESS_ALLOWED_ACE_TYPE {
1672 // IsValidAcl does not validate SIDs. Bound the whole SID before
1673 // IsValidSid or either caller's EqualSid can inspect it.
1674 let sid_offset = std::mem::offset_of!(ACCESS_ALLOWED_ACE, SidStart);
1675 let sid_header = std::mem::offset_of!(SID, SubAuthority);
1676 if entry_size < sid_offset + sid_header {
1677 return Err(io::Error::other("allow ACE has a truncated SID header"));
1678 }
1679 // SAFETY: the complete SID header is inside this ACE.
1680 let sid = unsafe { entry.cast::<u8>().add(sid_offset) };
1681 let count = usize::from(unsafe { *sid.add(1) });
1682 if sid_header + count * size_of::<u32>() > entry_size - sid_offset
1683 || unsafe { IsValidSid(sid.cast()) } == 0
1684 {
1685 return Err(io::Error::other(
1686 "allow ACE has an invalid or truncated SID",
1687 ));
1688 }
1689 }
1690 }
1691 Ok(Self {
1692 storage,
1693 acl_offset,
1694 control,
1695 })
1696 }
1697
1698 fn acl(&self) -> *mut ACL {
1699 // SAFETY: from_storage validated the offset, alignment, and ACL extent;
1700 // storage stays owned and unchanged while the returned pointer is used.
1701 unsafe {
1702 self.storage
1703 .as_ptr()
1704 .cast::<u8>()
1705 .add(self.acl_offset)
1706 .cast_mut()
1707 .cast()
1708 }
1709 }
1710 }
1711
1712 #[cfg(test)]
1713 struct LocalAllocation(*mut core::ffi::c_void);
1714 #[cfg(test)]
1715 impl Drop for LocalAllocation {
1716 fn drop(&mut self) {
1717 unsafe {
1718 LocalFree(self.0);
1719 }
1720 }
1721 }
1722
1723 struct Attributes {
1724 bytes: Vec<usize>,
1725 initialized: bool,
1726 }
1727 impl Attributes {
1728 fn new(count: u32) -> io::Result<Self> {
1729 let mut size = 0;
1730 unsafe {
1731 InitializeProcThreadAttributeList(null_mut(), count, 0, &mut size);
1732 }
1733 if size == 0 {
1734 return Err(io::Error::last_os_error());
1735 }
1736 let mut value = Self {
1737 bytes: vec![0; size.div_ceil(size_of::<usize>())],
1738 initialized: false,
1739 };
1740 if unsafe { InitializeProcThreadAttributeList(value.ptr(), count, 0, &mut size) } == 0 {
1741 return Err(io::Error::last_os_error());
1742 }
1743 value.initialized = true;
1744 Ok(value)
1745 }
1746 fn ptr(&mut self) -> *mut core::ffi::c_void {
1747 self.bytes.as_mut_ptr().cast()
1748 }
1749 fn set<T>(&mut self, attribute: u32, value: &T) -> io::Result<()> {
1750 self.set_raw(attribute, (value as *const T).cast(), size_of::<T>())
1751 }
1752 fn set_slice<T>(&mut self, attribute: u32, values: &[T]) -> io::Result<()> {
1753 self.set_raw(
1754 attribute,
1755 values.as_ptr().cast(),
1756 std::mem::size_of_val(values),
1757 )
1758 }
1759 fn set_raw(
1760 &mut self,
1761 attribute: u32,
1762 value: *const core::ffi::c_void,
1763 size: usize,
1764 ) -> io::Result<()> {
1765 if unsafe {
1766 UpdateProcThreadAttribute(
1767 self.ptr(),
1768 0,
1769 attribute as usize,
1770 value,
1771 size,
1772 null_mut(),
1773 null(),
1774 )
1775 } == 0
1776 {
1777 return Err(io::Error::last_os_error());
1778 }
1779 Ok(())
1780 }
1781 }
1782 impl Drop for Attributes {
1783 fn drop(&mut self) {
1784 if self.initialized {
1785 unsafe {
1786 DeleteProcThreadAttributeList(self.ptr());
1787 }
1788 }
1789 }
1790 }
1791
1792 fn pipe(output: bool, overlapped: bool) -> io::Result<(OwnedHandle, OwnedHandle)> {
1793 let name = wide(OsStr::new(&format!(
1794 r"\\.\pipe\Codewhale.Native.{}",
1795 uuid::Uuid::new_v4()
1796 )))?;
1797 // Parent endpoints are overlapped/noninheritable; exactly the synchronous
1798 // child endpoints are included in the process attribute HANDLE_LIST.
1799 let handle = unsafe {
1800 CreateNamedPipeW(
1801 name.as_ptr(),
1802 (if output {
1803 PIPE_ACCESS_INBOUND
1804 } else {
1805 PIPE_ACCESS_OUTBOUND
1806 }) | if overlapped { FILE_FLAG_OVERLAPPED } else { 0 }
1807 | FILE_FLAG_FIRST_PIPE_INSTANCE,
1808 PIPE_WAIT,
1809 1,
1810 8192,
1811 8192,
1812 0,
1813 null(),
1814 )
1815 };
1816 if handle == INVALID_HANDLE_VALUE {
1817 return Err(io::Error::last_os_error());
1818 }
1819 let parent = unsafe { OwnedHandle::from_raw_handle(handle) };
1820 let security = SECURITY_ATTRIBUTES {
1821 nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
1822 lpSecurityDescriptor: null_mut(),
1823 bInheritHandle: 1,
1824 };
1825 let handle = unsafe {
1826 CreateFileW(
1827 name.as_ptr(),
1828 if output {
1829 FILE_GENERIC_WRITE
1830 } else {
1831 FILE_GENERIC_READ
1832 },
1833 0,
1834 &security,
1835 OPEN_EXISTING,
1836 0,
1837 null_mut(),
1838 )
1839 };
1840 if handle == INVALID_HANDLE_VALUE {
1841 return Err(io::Error::last_os_error());
1842 }
1843 let child = unsafe { OwnedHandle::from_raw_handle(handle) };
1844 if unsafe { ConnectNamedPipe(parent.as_raw_handle(), null_mut()) } == 0
1845 && unsafe { GetLastError() } != ERROR_PIPE_CONNECTED
1846 {
1847 return Err(io::Error::last_os_error());
1848 }
1849 Ok((parent, child))
1850 }
1851
1852 fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
1853 let mut value: Vec<_> = value.encode_wide().collect();
1854 if value.contains(&0) {
1855 return Err(io::Error::new(
1856 io::ErrorKind::InvalidInput,
1857 "Windows argv/env contains NUL",
1858 ));
1859 }
1860 value.push(0);
1861 Ok(value)
1862 }
1863
1864 fn sandbox_args(args: &[String], runtime_dir: &Path) -> Vec<String> {
1865 // An LPAC cannot open the NUL device. Both the host and its probe
1866 // descendant read the empty config in the already-granted runtime copy.
1867 let empty_config = format!("--config={}", runtime_dir.join(EMPTY_BUN_CONFIG).display());
1868 args.iter()
1869 .map(|arg| {
1870 if arg == "--config=NUL" {
1871 empty_config.clone()
1872 } else {
1873 arg.clone()
1874 }
1875 })
1876 .collect()
1877 }
1878
1879 fn command_line(program: &OsStr, args: &[String]) -> io::Result<Vec<u16>> {
1880 // The documented CommandLineToArgvW/MS CRT quote+backslash rules. An
1881 // explicit application path means PATH/first-token parsing is never authority.
1882 let mut result = Vec::new();
1883 for arg in std::iter::once(program).chain(args.iter().map(OsStr::new)) {
1884 let units = wide(arg)?;
1885 if !result.is_empty() {
1886 result.push(b' ' as u16);
1887 }
1888 result.push(b'"' as u16);
1889 let mut slashes = 0;
1890 for unit in units.into_iter().take_while(|unit| *unit != 0) {
1891 if unit == b'\\' as u16 {
1892 slashes += 1;
1893 continue;
1894 }
1895 if unit == b'"' as u16 {
1896 result.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2 + 1));
1897 } else {
1898 result.extend(std::iter::repeat_n(b'\\' as u16, slashes));
1899 }
1900 slashes = 0;
1901 result.push(unit);
1902 }
1903 result.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2));
1904 result.push(b'"' as u16);
1905 }
1906 result.push(0);
1907 Ok(result)
1908 }
1909
1910 fn environment_block(env: &[(OsString, OsString)]) -> io::Result<Vec<u16>> {
1911 let mut entries = env.iter().collect::<Vec<_>>();
1912 entries.sort_by_key(|(key, _)| key.to_string_lossy().to_uppercase());
1913 let mut result = Vec::new();
1914 for (key, value) in entries {
1915 let key = wide(key)?;
1916 if key.len() == 1 || key.contains(&(b'=' as u16)) {
1917 return Err(io::Error::other("invalid Windows environment key"));
1918 }
1919 result.extend(&key[..key.len() - 1]);
1920 result.push(b'=' as u16);
1921 result.extend(wide(value)?);
1922 }
1923 if result.is_empty() {
1924 result.push(0);
1925 }
1926 result.push(0);
1927 Ok(result)
1928 }
1929
1930 #[cfg(test)]
1931 #[path = "windows_tests.rs"]
1932 mod tests;
1933
1933 lines RUST