landstrip 0.17.38

Sandbox for coding agents with parametrized state
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2026 Jarkko Sakkinen

//! Elevated installation lifecycle for the restricted-user backend.

use super::account;
use super::lease;
use super::state::{self, INSTALLATION_VERSION, Installation, NetworkMode};
use super::wfp;
use crate::cli::WindowsCommand;
use anyhow::{Context, Result, bail};
use serde_json::json;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::ptr;
use windows_sys::Win32::Foundation::{
    CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_FAILED, WAIT_OBJECT_0,
};
use windows_sys::Win32::Security::{
    GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation,
};
use windows_sys::Win32::System::Threading::{
    CreateMutexW, GetCurrentProcess, GetExitCodeProcess, INFINITE, OpenProcessToken, ReleaseMutex,
    WaitForSingleObject,
};
use windows_sys::Win32::UI::Shell::{
    SEE_MASK_NO_CONSOLE, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, SHELLEXECUTEINFOW_0,
    ShellExecuteExW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;

const FILTERS_PER_RESTRICTED_ACCOUNT: usize = 8;
const INSTALL_DIRECTORY: &str = "Landstrip";
const RUNNER_FILE: &str = "landstrip-restricted-user-runner.exe";
const MANAGEMENT_MUTEX: &str = "Global\\LandstripRestrictedUserManagement";

pub(crate) fn manage(command: &WindowsCommand) -> Result<()> {
    match command {
        WindowsCommand::Setup {
            restricted_accounts,
            unrestricted_accounts,
            proxy_port_low,
            proxy_port_high,
            elevated,
        } => {
            if !is_elevated()? {
                if *elevated {
                    bail!("restricted-user setup requires elevation");
                }
                return elevate_setup(
                    *restricted_accounts,
                    *unrestricted_accounts,
                    *proxy_port_low,
                    *proxy_port_high,
                );
            }
            let _management_lock = ManagementLock::acquire()?;
            setup(
                *restricted_accounts,
                *unrestricted_accounts,
                *proxy_port_low,
                *proxy_port_high,
            )
        }
        WindowsCommand::Status => status(),
        WindowsCommand::Uninstall { elevated } => {
            if !is_elevated()? {
                if *elevated {
                    bail!("restricted-user uninstall requires elevation");
                }
                return elevate_uninstall();
            }
            let _management_lock = ManagementLock::acquire()?;
            uninstall()
        }
        WindowsCommand::Worker { .. } => bail!("worker command cannot be managed"),
    }
}

fn setup(
    restricted_accounts: u16,
    unrestricted_accounts: u16,
    proxy_port_low: u16,
    proxy_port_high: u16,
) -> Result<()> {
    if state::load_optional()?.is_some() {
        uninstall().context("remove previous restricted-user installation")?;
    }

    let id = account::random_identifier(8)?;
    let restricted_count = usize::from(restricted_accounts);
    let filter_count = restricted_count
        .checked_mul(FILTERS_PER_RESTRICTED_ACCOUNT)
        .context("WFP filter count overflow")?;
    let mut wfp_filters = Vec::with_capacity(filter_count);
    for _ in 0..filter_count {
        wfp_filters.push(wfp::generate_key()?);
    }
    let runner_path = install_runner()?;

    let mut installation = Installation {
        version: INSTALLATION_VERSION,
        id,
        proxy_port_low,
        proxy_port_high,
        wfp_provider: wfp::generate_key()?,
        wfp_sublayer: wfp::generate_key()?,
        wfp_filters,
        complete: false,
        runner_path,
        accounts: Vec::with_capacity(restricted_count + usize::from(unrestricted_accounts)),
    };
    if let Err(error) = state::save(&installation) {
        let cleanup = remove_runner(&installation.runner_path);
        return match cleanup {
            Ok(()) => Err(error),
            Err(cleanup_error) => {
                Err(error.context(format!("automatic cleanup also failed: {cleanup_error:#}")))
            }
        };
    }

    let setup_result = (|| {
        state::initialize_runtime_directories()?;
        provision_accounts(
            &mut installation,
            restricted_accounts,
            NetworkMode::Restricted,
            "r",
        )?;
        provision_accounts(
            &mut installation,
            unrestricted_accounts,
            NetworkMode::Unrestricted,
            "u",
        )?;
        wfp::install(&installation)?;
        installation.complete = true;
        state::save(&installation)?;
        Ok(())
    })();

    if let Err(error) = setup_result {
        let cleanup = uninstall();
        return match cleanup {
            Ok(()) => Err(error),
            Err(cleanup_error) => {
                Err(error.context(format!("automatic cleanup also failed: {cleanup_error:#}")))
            }
        };
    }

    println!(
        "restricted-user backend installed: {restricted_accounts} restricted account(s), {unrestricted_accounts} unrestricted account(s), proxy ports {proxy_port_low}-{proxy_port_high}"
    );
    Ok(())
}

fn provision_accounts(
    installation: &mut Installation,
    count: u16,
    network_mode: NetworkMode,
    mode_tag: &str,
) -> Result<()> {
    let prefix = &installation.id[..installation.id.len().min(8)];
    for index in 0..count {
        let name = format!("ls_{prefix}_{mode_tag}{index:02}");
        let provisioned = account::provision(&name, network_mode)
            .with_context(|| format!("provision restricted-user account {name}"))?;
        installation.accounts.push(provisioned);
        if let Err(error) = state::save(installation) {
            let provisioned = installation
                .accounts
                .pop()
                .context("newly provisioned account disappeared from installation state")?;
            let cleanup = account::remove(&provisioned.name);
            return match cleanup {
                Ok(()) => Err(error),
                Err(cleanup_error) => Err(error.context(format!(
                    "remove unrecorded restricted-user account also failed: {cleanup_error:#}"
                ))),
            };
        }
    }
    Ok(())
}

fn uninstall() -> Result<()> {
    let Some(mut installation) = state::load_optional()? else {
        println!("restricted-user backend is not installed");
        return Ok(());
    };

    installation.complete = false;
    state::save(&installation).context("mark restricted-user installation unavailable")?;

    lease::recover_all(&installation)
        .context("recover restricted-user filesystem grants before uninstall")?;
    wfp::uninstall(&installation).context("remove restricted-user WFP policy")?;
    for provisioned in &installation.accounts {
        account::remove(&provisioned.name)
            .with_context(|| format!("remove restricted-user account {}", provisioned.name))?;
    }
    remove_runner(&installation.runner_path)?;
    state::remove()?;
    println!("restricted-user backend uninstalled");
    Ok(())
}

fn status() -> Result<()> {
    let Some(installation) = state::load_optional()? else {
        println!("{}", json!({ "installed": false }));
        return Ok(());
    };

    let accounts_healthy = installation.accounts.iter().all(|provisioned| {
        account::lookup_sid(&provisioned.name)
            .is_ok_and(|sid| sid.eq_ignore_ascii_case(&provisioned.sid))
    });
    let runner_healthy = installation.runner_path.is_file();
    println!(
        "{}",
        json!({
            "installed": true,
            "healthy": installation.complete && accounts_healthy && runner_healthy,
            "version": installation.version,
            "complete": installation.complete,
            "restrictedAccounts": installation.accounts.iter().filter(|account| account.network_mode == NetworkMode::Restricted).count(),
            "unrestrictedAccounts": installation.accounts.iter().filter(|account| account.network_mode == NetworkMode::Unrestricted).count(),
            "proxyPortLow": installation.proxy_port_low,
            "proxyPortHigh": installation.proxy_port_high,
            "runner": installation.runner_path,
            "runnerHealthy": runner_healthy,
            "accountsHealthy": accounts_healthy,
        })
    );
    if !installation.complete || !accounts_healthy || !runner_healthy {
        bail!("restricted-user installation is unhealthy");
    }
    Ok(())
}

fn install_runner() -> Result<PathBuf> {
    let program_files = env::var_os("ProgramFiles")
        .map(PathBuf::from)
        .context("ProgramFiles is unavailable")?;
    let directory = program_files.join(INSTALL_DIRECTORY);
    fs::create_dir_all(&directory)
        .with_context(|| format!("create runner directory {}", directory.display()))?;
    let source = env::current_exe().context("locate current landstrip executable")?;
    let destination = directory.join(RUNNER_FILE);
    let temporary = directory.join(format!("{RUNNER_FILE}.tmp-{}", std::process::id()));
    fs::copy(&source, &temporary).with_context(|| {
        format!(
            "copy restricted-user runner from {} to {}",
            source.display(),
            temporary.display()
        )
    })?;
    if destination.exists() {
        fs::remove_file(&destination)
            .with_context(|| format!("replace restricted-user runner {}", destination.display()))?;
    }
    fs::rename(&temporary, &destination)
        .with_context(|| format!("install restricted-user runner {}", destination.display()))?;
    Ok(destination)
}

fn remove_runner(path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Ok(()) => {}
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(error)
                .with_context(|| format!("remove restricted-user runner {}", path.display()));
        }
    }
    if let Some(directory) = path.parent() {
        let _ = fs::remove_dir(directory);
    }
    Ok(())
}

fn elevate_setup(
    restricted_accounts: u16,
    unrestricted_accounts: u16,
    proxy_port_low: u16,
    proxy_port_high: u16,
) -> Result<()> {
    elevate(&format!(
        "windows setup --restricted-accounts {restricted_accounts} --unrestricted-accounts {unrestricted_accounts} --proxy-port-low {proxy_port_low} --proxy-port-high {proxy_port_high} --elevated"
    ))
}

fn elevate_uninstall() -> Result<()> {
    elevate("windows uninstall --elevated")
}

fn elevate(parameters: &str) -> Result<()> {
    let executable = env::current_exe().context("locate current landstrip executable")?;
    let executable = wide(executable.as_os_str());
    let parameters = wide(OsStr::new(parameters));
    let verb = wide(OsStr::new("runas"));
    let mut execute = SHELLEXECUTEINFOW {
        cbSize: u32::try_from(mem::size_of::<SHELLEXECUTEINFOW>())
            .context("ShellExecute structure is too large")?,
        fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
        hwnd: ptr::null_mut(),
        lpVerb: verb.as_ptr(),
        lpFile: executable.as_ptr(),
        lpParameters: parameters.as_ptr(),
        lpDirectory: ptr::null(),
        nShow: SW_SHOWNORMAL,
        hInstApp: ptr::null_mut(),
        lpIDList: ptr::null_mut(),
        lpClass: ptr::null(),
        hkeyClass: ptr::null_mut(),
        dwHotKey: 0,
        Anonymous: SHELLEXECUTEINFOW_0::default(),
        hProcess: ptr::null_mut(),
    };
    if unsafe { ShellExecuteExW(&raw mut execute) } == 0 {
        return Err(io::Error::last_os_error()).context("request Windows elevation");
    }
    if execute.hProcess.is_null() {
        bail!("Windows elevation returned no process handle");
    }
    let process = Handle(execute.hProcess);
    if unsafe { WaitForSingleObject(process.0, INFINITE) } != WAIT_OBJECT_0 {
        return Err(io::Error::last_os_error()).context("wait for elevated landstrip");
    }
    let mut exit_code = 0;
    if unsafe { GetExitCodeProcess(process.0, &raw mut exit_code) } == 0 {
        return Err(io::Error::last_os_error()).context("query elevated landstrip exit code");
    }
    if exit_code != 0 {
        bail!("elevated landstrip exited with status {exit_code}");
    }
    Ok(())
}

fn is_elevated() -> Result<bool> {
    let mut token = ptr::null_mut();
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut token) } == 0 {
        return Err(io::Error::last_os_error()).context("open current process token");
    }
    let token = Handle(token);
    let mut elevation = TOKEN_ELEVATION::default();
    let mut returned = 0;
    if unsafe {
        GetTokenInformation(
            token.0,
            TokenElevation,
            (&raw mut elevation).cast(),
            u32::try_from(mem::size_of::<TOKEN_ELEVATION>())
                .context("token elevation structure is too large")?,
            &raw mut returned,
        )
    } == 0
    {
        return Err(io::Error::last_os_error()).context("query process elevation");
    }
    Ok(elevation.TokenIsElevated != 0)
}

fn wide(value: &OsStr) -> Vec<u16> {
    value.encode_wide().chain(Some(0)).collect()
}

struct Handle(HANDLE);

impl Drop for Handle {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                CloseHandle(self.0);
            }
        }
    }
}

struct ManagementLock(HANDLE);

impl ManagementLock {
    fn acquire() -> Result<Self> {
        let name = wide(OsStr::new(MANAGEMENT_MUTEX));
        let handle = unsafe { CreateMutexW(ptr::null(), 0, name.as_ptr()) };
        if handle.is_null() {
            return Err(io::Error::last_os_error())
                .context("create restricted-user management mutex");
        }
        let wait = unsafe { WaitForSingleObject(handle, INFINITE) };
        if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED {
            unsafe { CloseHandle(handle) };
            let error = if wait == WAIT_FAILED {
                io::Error::last_os_error()
            } else {
                io::Error::other(format!("unexpected mutex wait result {wait}"))
            };
            return Err(error).context("acquire restricted-user management mutex");
        }
        Ok(Self(handle))
    }
}

impl Drop for ManagementLock {
    fn drop(&mut self) {
        unsafe {
            ReleaseMutex(self.0);
            CloseHandle(self.0);
        }
    }
}