Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-desktop): verify staged helper inputs

Lizi9e8691a33d6d
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/main.rs b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
index 439c38b9d0..ccb6c8882a 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/main.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/main.rs
@@ -80,13 +80,20 @@ fn run() -> Staged<()> {
service::install(&installation)?;
service::authorize(&installation, pid)
}
- Some("--install-from") if args.len() == 3 || args.len() == 4 => {
+ Some("--install-from") if args.len() == 5 || args.len() == 6 => {
let source = std::path::PathBuf::from(&args[1]);
- let pid = args[2]
+ let expected_host_hash = &args[2];
+ let expected_input_hash = &args[3];
+ let pid = args[4]
.parse::<u32>()
.map_err(|_| Failure::new(Step::Args, 0))?;
- let development = args.get(3).is_some_and(|arg| arg == "--development");
- if args.len() == 4 && !development {
+ let development = args.get(5).is_some_and(|arg| arg == "--development");
+ if args.len() == 6 && !development
+ || expected_host_hash.len() != 64
+ || expected_input_hash.len() != 64
+ || !expected_host_hash.bytes().all(|b| b.is_ascii_hexdigit())
+ || !expected_input_hash.bytes().all(|b| b.is_ascii_hexdigit())
+ {
return refuse(Step::Args);
}
let installation = if development {
@@ -98,7 +105,12 @@ fn run() -> Staged<()> {
// before replacing its host and input binaries, then stage bytes
// read from the user installation as data.
uninstall_before_install(&installation, &source)?;
- staging::stage_from(&installation, &source)?;
+ staging::stage_from_verified(
+ &installation,
+ &source,
+ Some(expected_host_hash),
+ Some(expected_input_hash),
+ )?;
service::install_staged(&installation)?;
service::authorize(&installation, pid)
}
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/service.rs b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
index a981f514be..50adde936e 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/service.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
@@ -256,6 +256,7 @@ fn powershell_script(
source: &std::path::Path,
bootstrap: &std::path::Path,
source_hash: &str,
+ input_hash: &str,
child_args: &[String],
remove_staging: bool,
) -> String {
@@ -279,13 +280,18 @@ fn powershell_script(
script.push_str(&powershell_literal(&bootstrap.to_string_lossy()));
script.push_str("; $expectedHash=");
script.push_str(&powershell_literal(source_hash));
+ script.push_str("; $expectedInputHash=");
+ script.push_str(&powershell_literal(input_hash));
+ script.push_str(
+ "; $inputPath=Join-Path (Split-Path -Parent $source) 'cindy-windows-desktop-input.exe';",
+ );
script.push_str("; $bootstrapDir=Split-Path -Parent $bootstrap; $stagingRoot=Split-Path -Parent $bootstrapDir; $programFiles=Split-Path -Parent $stagingRoot;");
script.push_str(" $trusted=@('S-1-5-18','S-1-5-32-544','S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464');");
script.push_str(" $writeMask=[System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::WriteData -bor [System.Security.AccessControl.FileSystemRights]::AppendData -bor [System.Security.AccessControl.FileSystemRights]::WriteAttributes -bor [System.Security.AccessControl.FileSystemRights]::WriteExtendedAttributes -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership;");
- script.push_str(" function Test-Protected([string]$Path) { $item=Get-Item -LiteralPath $Path -Force -ErrorAction Stop; if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { return $false }; $acl=$item.GetAccessControl(); if ($trusted -notcontains $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value) { return $false }; foreach ($rule in $acl.Access) { if ($rule.AccessControlType -ne 'Allow') { continue }; $sid=$rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value; if (($trusted -notcontains $sid) -and (($rule.FileSystemRights -band $writeMask) -ne 0)) { return $false } }; return $true };");
+ script.push_str(" function Test-Protected([string]$Path) { $item=Get-Item -LiteralPath $Path -Force -ErrorAction Stop; if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { return $false }; $acl=$item.GetAccessControl(); if ($trusted -notcontains $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value) { return $false }; foreach ($rule in $acl.Access) { if ($rule.AccessControlType -ne 'Allow' -or (($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0)) { continue }; $sid=$rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value; if (($trusted -notcontains $sid) -and (($rule.FileSystemRights -band $writeMask) -ne 0)) { return $false } }; return $true };");
script.push_str(" if (-not (Test-Path -LiteralPath $programFiles) -or -not (Test-Protected $programFiles)) { exit 1 };");
script.push_str(" foreach ($dir in @($stagingRoot,$bootstrapDir)) { if (Test-Path -LiteralPath $dir) { if (-not (Test-Protected $dir)) { exit 1 } } else { New-Item -ItemType Directory -Path $dir -Force | Out-Null }; $security=New-Object System.Security.AccessControl.DirectorySecurity; $security.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)'); Set-Acl -LiteralPath $dir -AclObject $security; if (-not (Test-Protected $dir)) { exit 1 } };");
- script.push_str(" if ((Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expectedHash) { exit 1 }; Copy-Item -LiteralPath $source -Destination $bootstrap -Force; if (-not (Test-Protected $bootstrap)) { exit 1 }; if ((Get-FileHash -LiteralPath $bootstrap -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expectedHash) { exit 1 }; $child=Start-Process -FilePath $bootstrap -ArgumentList @(");
+ script.push_str(" if ((Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expectedHash) { exit 1 }; if ((Get-FileHash -LiteralPath $inputPath -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expectedInputHash) { exit 1 }; if (Test-Path -LiteralPath $bootstrap) { if (-not (Test-Protected $bootstrap)) { exit 1 } }; Copy-Item -LiteralPath $source -Destination $bootstrap -Force; if (-not (Test-Protected $bootstrap)) { exit 1 }; if ((Get-FileHash -LiteralPath $bootstrap -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expectedHash) { exit 1 }; $child=Start-Process -FilePath $bootstrap -ArgumentList @(");
script.push_str(&args);
script.push_str(") -Wait -PassThru -WindowStyle Hidden;");
if remove_staging {
@@ -314,8 +320,20 @@ pub fn elevate(installation: &Installation, child_args: &[String]) -> Staged<()>
read_lock(&source.with_file_name(crate::naming::INPUT_EXE)).stage(Step::ElevateLaunch)?;
let source_hash = Sha256::digest(std::fs::read(&source).stage(Step::ElevateLaunch)?);
let source_hash = format!("{source_hash:x}");
+ let input_hash = Sha256::digest(
+ std::fs::read(source.with_file_name(crate::naming::INPUT_EXE))
+ .stage(Step::ElevateLaunch)?,
+ );
+ let input_hash = format!("{input_hash:x}");
let mut child_args = child_args.to_vec();
child_args.insert(1, source.to_string_lossy().into_owned());
+ if child_args
+ .first()
+ .is_some_and(|arg| arg == "--install-from")
+ {
+ child_args.insert(2, source_hash.clone());
+ child_args.insert(3, input_hash.clone());
+ }
let remove_staging = child_args
.first()
.is_some_and(|arg| arg == "--uninstall-from");
@@ -323,6 +341,7 @@ pub fn elevate(installation: &Installation, child_args: &[String]) -> Staged<()>
&source,
&installation.bootstrap(),
&source_hash,
+ &input_hash,
&child_args,
remove_staging,
);
@@ -965,6 +984,8 @@ mod tests {
"--install-from".to_owned(),
r"C:\Users\dev user\resources\tools\remote-desktop\cindy-windows-desktop-host.exe"
.to_owned(),
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_owned(),
+ "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210".to_owned(),
"1234".to_owned(),
"--development".to_owned(),
];
@@ -975,7 +996,8 @@ mod tests {
Path::new(
r"C:\Program Files\Cindy Remote Desktop\abc\cindy-windows-desktop-bootstrap.exe",
),
- "0123456789abcdef",
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210",
&args,
false,
);
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/staging.rs b/apps/desktop/native/remote-desktop/windows-host/src/staging.rs
index f1eb447439..7241ff542c 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/staging.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/staging.rs
@@ -25,6 +25,7 @@
use crate::naming::*;
use crate::security;
use crate::win::*;
+use sha2::{Digest, Sha256};
use std::io::{Read, Write};
use std::os::windows::io::FromRawHandle;
use std::path::{Path, PathBuf};
@@ -127,11 +128,18 @@ fn read_exclusively(path: &Path) -> Staged<Vec<u8>> {
FILE_SHARE_READ,
ptr::null(),
OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
})
.stage(Step::StageRead)?;
+ let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { mem::zeroed() };
+ if unsafe { GetFileInformationByHandle(handle.0, &mut info) } == 0 {
+ return Err(Failure::new(Step::StageRead, last_error()));
+ }
+ if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ return refuse(Step::StageRead);
+ }
let mut file = unsafe { std::fs::File::from_raw_handle(handle.0.cast()) };
mem::forget(handle);
let length = file.metadata().stage(Step::StageRead)?.len();
@@ -191,8 +199,27 @@ pub fn stage(installation: &Installation) -> Staged<PathBuf> {
/// The bootstrap itself is already in Program Files, so the helper from the
/// user-writable installation is treated strictly as input bytes.
pub fn stage_from(installation: &Installation, bundled: &Path) -> Staged<PathBuf> {
+ stage_from_verified(installation, bundled, None, None)
+}
+
+/// Stages helpers after the unelevated launcher has measured both source
+/// files. The elevated child re-reads them through non-reparse handles and
+/// compares those bytes before anything reaches the SYSTEM service.
+pub fn stage_from_verified(
+ installation: &Installation,
+ bundled: &Path,
+ expected_host_hash: Option<&str>,
+ expected_input_hash: Option<&str>,
+) -> Staged<PathBuf> {
let host = read_exclusively(bundled)?;
let input = read_exclusively(&bundled.with_file_name(INPUT_EXE))?;
+ if expected_host_hash.is_some_and(|expected| {
+ !format!("{:x}", Sha256::digest(&host)).eq_ignore_ascii_case(expected)
+ }) || expected_input_hash.is_some_and(|expected| {
+ !format!("{:x}", Sha256::digest(&input)).eq_ignore_ascii_case(expected)
+ }) {
+ return refuse(Step::StageRead);
+ }
let directory_rights = Descriptor::parse(DIRECTORY_RIGHTS)?;
let attributes = directory_rights.attributes();
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/win.rs b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
index df0b9df03e..63ce007eb8 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/win.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/win.rs
@@ -35,17 +35,27 @@ pub fn system_file(name: &str) -> Result<PathBuf> {
/// the protected PowerShell bootstrap copies them. The handle is held by the
/// unelevated helper until the elevated child has finished.
pub fn read_lock(path: &Path) -> Result<Handle> {
- Handle::new(unsafe {
+ let handle = Handle::new(unsafe {
CreateFileW(
wide(&path.to_string_lossy()).as_ptr(),
GENERIC_READ,
FILE_SHARE_READ,
ptr::null(),
OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
- })
+ })?;
+ let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
+ if unsafe { GetFileInformationByHandle(handle.0, &mut info) } == 0 {
+ return Err(error());
+ }
+ if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ return Err(io::Error::from_raw_os_error(
+ ERROR_REPARSE_TAG_INVALID as i32,
+ ));
+ }
+ Ok(handle)
}
/// The elevated child is hidden, so its step and raw Win32 error have to cross