Skip to content

Commit 8327091

Browse files
shanselmanCopilot
andcommitted
fix(connection): bind WSL relay fallback to package
Require package-owned WindowsApps paths or a protected external relay whose ACLs and version bind it to the installed Microsoft WSL package. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 76619eef-66f0-45be-ad09-b753347eea6b
1 parent 7396130 commit 8327091

2 files changed

Lines changed: 481 additions & 38 deletions

File tree

‎src/OpenClaw.Connection/WindowsAuthenticodeVerifier.cs‎

Lines changed: 275 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
using System.Diagnostics;
33
using System.IO;
44
using System.Linq;
5+
using System.Runtime.Versioning;
6+
using System.Security.AccessControl;
7+
using System.Security.Principal;
58
using System.Text.Json;
69
using System.Threading;
710
using Microsoft.Security.Extensions;
@@ -24,7 +27,21 @@ internal readonly record struct AuthenticodeTrustResult(bool IsTrusted, string?
2427
internal readonly record struct AppxPackageInfo(
2528
string? PackageFamilyName,
2629
string? Publisher,
27-
string? SignatureKind);
30+
string? SignatureKind,
31+
string? InstallLocation,
32+
string? Version);
33+
34+
internal readonly record struct WslRelayPathInspection(
35+
bool IsSecure,
36+
string? FileVersion,
37+
string? Detail)
38+
{
39+
public static WslRelayPathInspection Secure(string? fileVersion) =>
40+
new(true, fileVersion, null);
41+
42+
public static WslRelayPathInspection Rejected(string detail) =>
43+
new(false, null, detail);
44+
}
2845

2946
internal static class WindowsAuthenticodeVerifier
3047
{
@@ -33,19 +50,37 @@ internal static class WindowsAuthenticodeVerifier
3350
// re-signed with a different certificate would get a different family name.
3451
private const string WslPackageFamilyName =
3552
"MicrosoftCorporationII.WindowsSubsystemForLinux_8wekyb3d8bbwe";
53+
private const string TrustedInstallerSid =
54+
"S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
3655

3756
public static AuthenticodeTrustResult VerifyMicrosoftSignedFile(string path) =>
38-
VerifyMicrosoftSignedFile(path, LookupWslAppxPackageViaPowerShell);
57+
VerifyMicrosoftSignedFile(
58+
path,
59+
VerifyAuthenticodeSignature,
60+
LookupWslAppxPackageViaPowerShell,
61+
InspectWslRelayPath);
3962

4063
/// <summary>
41-
/// Test seam: allows callers to substitute a fake WSL AppX package lookup
42-
/// instead of shelling out to PowerShell.
64+
/// Test seam for the primary signature, WSL package, and protected-path
65+
/// evidence used by the package fallback.
4366
/// </summary>
4467
internal static AuthenticodeTrustResult VerifyMicrosoftSignedFile(
4568
string path,
46-
Func<AppxPackageInfo?> lookupWslPackage)
69+
Func<string, AuthenticodeTrustResult> verifyAuthenticode,
70+
Func<AppxPackageInfo?> lookupWslPackage,
71+
Func<string, string, WslRelayPathInspection> inspectRelayPath)
4772
{
48-
var primary = VerifyAuthenticodeSignature(path);
73+
AuthenticodeTrustResult primary;
74+
try
75+
{
76+
primary = verifyAuthenticode(path);
77+
}
78+
catch
79+
{
80+
return AuthenticodeTrustResult.Rejected(
81+
"WSL relay Authenticode verification could not complete.");
82+
}
83+
4984
if (primary.IsTrusted)
5085
return primary;
5186

@@ -56,7 +91,7 @@ internal static AuthenticodeTrustResult VerifyMicrosoftSignedFile(
5691
if (!string.Equals(Path.GetFileName(path), "wslrelay.exe", StringComparison.OrdinalIgnoreCase))
5792
return primary;
5893

59-
return VerifyWslPackageFallback(primary, lookupWslPackage);
94+
return VerifyWslPackageFallback(path, primary, lookupWslPackage, inspectRelayPath);
6095
}
6196

6297
private static AuthenticodeTrustResult VerifyAuthenticodeSignature(string path)
@@ -92,8 +127,10 @@ private static AuthenticodeTrustResult VerifyAuthenticodeSignature(string path)
92127
}
93128

94129
private static AuthenticodeTrustResult VerifyWslPackageFallback(
130+
string path,
95131
AuthenticodeTrustResult primaryFailure,
96-
Func<AppxPackageInfo?> lookupWslPackage)
132+
Func<AppxPackageInfo?> lookupWslPackage,
133+
Func<string, string, WslRelayPathInspection> inspectRelayPath)
97134
{
98135
AppxPackageInfo? package;
99136
try
@@ -132,9 +169,98 @@ private static AuthenticodeTrustResult VerifyWslPackageFallback(
132169
"WSL package signature verification failed: the installed WSL package's publisher is not Microsoft Corporation.");
133170
}
134171

172+
if (string.IsNullOrWhiteSpace(info.InstallLocation) ||
173+
!Path.IsPathFullyQualified(info.InstallLocation))
174+
{
175+
return AuthenticodeTrustResult.Rejected(
176+
"WSL package provenance verification failed: package location data is unavailable.");
177+
}
178+
179+
string fullPath;
180+
string installLocation;
181+
try
182+
{
183+
fullPath = Path.GetFullPath(path);
184+
installLocation = Path.GetFullPath(info.InstallLocation);
185+
}
186+
catch
187+
{
188+
return AuthenticodeTrustResult.Rejected(
189+
"WSL package provenance verification failed: package location data is invalid.");
190+
}
191+
192+
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
193+
var windowsAppsRoot = Path.Combine(programFiles, "WindowsApps");
194+
if (IsPathWithin(installLocation, windowsAppsRoot) &&
195+
IsPathWithin(fullPath, installLocation))
196+
{
197+
return ToTrustResult(
198+
InspectProtectedRelayPath(fullPath, programFiles, inspectRelayPath));
199+
}
200+
201+
var externalRelayPath = Path.Combine(programFiles, "WSL", "wslrelay.exe");
202+
if (!string.Equals(fullPath, externalRelayPath, StringComparison.OrdinalIgnoreCase))
203+
{
204+
return AuthenticodeTrustResult.Rejected(
205+
"WSL package provenance verification failed: the relay is not owned by the installed WSL package.");
206+
}
207+
208+
var inspection = InspectProtectedRelayPath(
209+
fullPath,
210+
programFiles,
211+
inspectRelayPath);
212+
if (!inspection.IsSecure)
213+
return ToTrustResult(inspection);
214+
215+
// The external WSL layout stamps wslrelay.exe with the package version.
216+
// Exact equality binds the protected external bytes to the installed package.
217+
if (!VersionsMatch(info.Version, inspection.FileVersion))
218+
{
219+
return AuthenticodeTrustResult.Rejected(
220+
"WSL package provenance verification failed: the external relay version does not match the installed WSL package.");
221+
}
222+
135223
return AuthenticodeTrustResult.Trusted();
136224
}
137225

226+
private static WslRelayPathInspection InspectProtectedRelayPath(
227+
string fullPath,
228+
string trustedRoot,
229+
Func<string, string, WslRelayPathInspection> inspectRelayPath)
230+
{
231+
try
232+
{
233+
return inspectRelayPath(fullPath, trustedRoot);
234+
}
235+
catch
236+
{
237+
return WslRelayPathInspection.Rejected(
238+
"WSL package provenance verification failed: the relay path could not be inspected.");
239+
}
240+
}
241+
242+
private static AuthenticodeTrustResult ToTrustResult(WslRelayPathInspection inspection) =>
243+
inspection.IsSecure
244+
? AuthenticodeTrustResult.Trusted()
245+
: AuthenticodeTrustResult.Rejected(
246+
inspection.Detail ??
247+
"WSL package provenance verification failed: the relay path is not protected.");
248+
249+
private static bool VersionsMatch(string? packageVersion, string? fileVersion) =>
250+
Version.TryParse(packageVersion, out var parsedPackageVersion) &&
251+
Version.TryParse(fileVersion, out var parsedFileVersion) &&
252+
parsedPackageVersion.Equals(parsedFileVersion);
253+
254+
private static bool IsPathWithin(string path, string root)
255+
{
256+
var relative = Path.GetRelativePath(root, path);
257+
return !Path.IsPathRooted(relative) &&
258+
!string.Equals(relative, "..", StringComparison.Ordinal) &&
259+
!relative.StartsWith(
260+
$"..{Path.DirectorySeparatorChar}",
261+
StringComparison.Ordinal);
262+
}
263+
138264
internal static bool HasMicrosoftPublisherIdentity(string subject) =>
139265
subject.Split(',')
140266
.Select(part => part.Trim())
@@ -162,7 +288,10 @@ internal static bool HasMicrosoftPublisherIdentity(string subject) =>
162288
psi.ArgumentList.Add("-Command");
163289
psi.ArgumentList.Add(
164290
"Get-AppxPackage -Name 'MicrosoftCorporationII.WindowsSubsystemForLinux' | " +
165-
"Select-Object -First 1 PackageFamilyName, Publisher, SignatureKind | " +
291+
"Sort-Object Version -Descending | " +
292+
"Select-Object -First 1 PackageFamilyName, Publisher, InstallLocation, " +
293+
"@{Name='SignatureKind'; Expression={$_.SignatureKind.ToString()}}, " +
294+
"@{Name='Version'; Expression={$_.Version.ToString()}} | " +
166295
"ConvertTo-Json -Compress");
167296

168297
process = Process.Start(psi);
@@ -237,7 +366,9 @@ private static string ResolvePowerShellPath()
237366
return new AppxPackageInfo(
238367
familyName,
239368
GetStringProperty(root, "Publisher"),
240-
GetStringProperty(root, "SignatureKind"));
369+
GetStringProperty(root, "SignatureKind"),
370+
GetStringProperty(root, "InstallLocation"),
371+
GetStringProperty(root, "Version"));
241372
}
242373
catch
243374
{
@@ -249,4 +380,138 @@ private static string ResolvePowerShellPath()
249380
element.TryGetProperty(propertyName, out var value) && value.ValueKind == JsonValueKind.String
250381
? value.GetString()
251382
: null;
383+
384+
private static WslRelayPathInspection InspectWslRelayPath(
385+
string path,
386+
string trustedRoot)
387+
{
388+
if (!OperatingSystem.IsWindows())
389+
{
390+
return WslRelayPathInspection.Rejected(
391+
"WSL package provenance verification is only available on Windows.");
392+
}
393+
394+
try
395+
{
396+
var fullPath = Path.GetFullPath(path);
397+
var fullRoot = Path.GetFullPath(trustedRoot);
398+
if (!File.Exists(fullPath) || !IsPathWithin(fullPath, fullRoot))
399+
{
400+
return WslRelayPathInspection.Rejected(
401+
"WSL package provenance verification failed: the relay path is unavailable or outside its trusted root.");
402+
}
403+
404+
for (var current = fullPath; ; current = Path.GetDirectoryName(current)!)
405+
{
406+
if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
407+
{
408+
return WslRelayPathInspection.Rejected(
409+
"WSL package provenance verification failed: the relay path contains a reparse point.");
410+
}
411+
412+
FileSystemSecurity security =
413+
string.Equals(current, fullPath, StringComparison.OrdinalIgnoreCase)
414+
? new FileInfo(current).GetAccessControl(
415+
AccessControlSections.Owner | AccessControlSections.Access)
416+
: new DirectoryInfo(current).GetAccessControl(
417+
AccessControlSections.Owner | AccessControlSections.Access);
418+
if (!HasProtectedOwnershipAndWriteAcl(security))
419+
{
420+
return WslRelayPathInspection.Rejected(
421+
"WSL package provenance verification failed: the relay path permits untrusted modification.");
422+
}
423+
424+
if (string.Equals(current, fullRoot, StringComparison.OrdinalIgnoreCase))
425+
break;
426+
427+
if (string.IsNullOrWhiteSpace(Path.GetDirectoryName(current)))
428+
{
429+
return WslRelayPathInspection.Rejected(
430+
"WSL package provenance verification failed: the relay path escaped its trusted root.");
431+
}
432+
}
433+
434+
return WslRelayPathInspection.Secure(
435+
FileVersionInfo.GetVersionInfo(fullPath).FileVersion);
436+
}
437+
catch
438+
{
439+
return WslRelayPathInspection.Rejected(
440+
"WSL package provenance verification failed: the relay path could not be inspected.");
441+
}
442+
}
443+
444+
[SupportedOSPlatform("windows")]
445+
private static bool HasProtectedOwnershipAndWriteAcl(FileSystemSecurity security)
446+
{
447+
var owner = security.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
448+
var rules = security.GetAccessRules(
449+
includeExplicit: true,
450+
includeInherited: true,
451+
targetType: typeof(SecurityIdentifier))
452+
.OfType<FileSystemAccessRule>();
453+
var descriptor = new RawSecurityDescriptor(
454+
security.GetSecurityDescriptorBinaryForm(),
455+
offset: 0);
456+
var hasDiscretionaryAcl =
457+
(descriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 &&
458+
descriptor.DiscretionaryAcl is not null;
459+
return HasProtectedOwnershipAndWriteAcl(
460+
owner,
461+
rules,
462+
hasDiscretionaryAcl);
463+
}
464+
465+
[SupportedOSPlatform("windows")]
466+
internal static bool HasProtectedOwnershipAndWriteAcl(
467+
SecurityIdentifier? owner,
468+
IEnumerable<FileSystemAccessRule> rules,
469+
bool hasDiscretionaryAcl)
470+
{
471+
if (!hasDiscretionaryAcl)
472+
return false;
473+
474+
var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
475+
var administrators = new SecurityIdentifier(
476+
WellKnownSidType.BuiltinAdministratorsSid,
477+
null);
478+
var trustedInstaller = new SecurityIdentifier(TrustedInstallerSid);
479+
if (owner is null ||
480+
(!owner.Equals(system) &&
481+
!owner.Equals(administrators) &&
482+
!owner.Equals(trustedInstaller)))
483+
{
484+
return false;
485+
}
486+
487+
const FileSystemRights writeRights =
488+
FileSystemRights.WriteData |
489+
FileSystemRights.AppendData |
490+
FileSystemRights.WriteExtendedAttributes |
491+
FileSystemRights.WriteAttributes |
492+
FileSystemRights.DeleteSubdirectoriesAndFiles |
493+
FileSystemRights.Delete |
494+
FileSystemRights.ChangePermissions |
495+
FileSystemRights.TakeOwnership;
496+
497+
foreach (var rule in rules)
498+
{
499+
if ((rule.PropagationFlags & PropagationFlags.InheritOnly) != 0 ||
500+
rule.AccessControlType != AccessControlType.Allow ||
501+
(rule.FileSystemRights & writeRights) == 0)
502+
{
503+
continue;
504+
}
505+
506+
if (rule.IdentityReference is not SecurityIdentifier sid ||
507+
(!sid.Equals(system) &&
508+
!sid.Equals(administrators) &&
509+
!sid.Equals(trustedInstaller)))
510+
{
511+
return false;
512+
}
513+
}
514+
515+
return true;
516+
}
252517
}

0 commit comments

Comments
 (0)