Skip to content

Commit cab6f02

Browse files
authored
fix: make Gateway shell execution work on Windows nodes (#972)
* fix: authorize exact commands inside gateway wrappers * fix: preserve wrapper prompt semantics * fix: make Windows MXC defaults executable * fix: report Windows node command success
1 parent 622c0e2 commit cab6f02

5 files changed

Lines changed: 315 additions & 53 deletions

File tree

‎src/OpenClaw.Shared/Capabilities/SystemCapability.cs‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@ private async Task<NodeInvokeResponse> HandleRunAsync(NodeInvokeRequest request)
472472
stderr = result.Stderr,
473473
exitCode = result.ExitCode,
474474
timedOut = result.TimedOut,
475+
success = result.ExitCode == 0 && !result.TimedOut,
475476
durationMs = result.DurationMs
476477
});
477478
}
@@ -547,25 +548,39 @@ private async Task<ExecApprovalCheckResult> EnsureApprovedAsync(
547548
if (_approvalPolicy == null)
548549
return null;
549550

550-
var approval = _approvalPolicy.Evaluate(fullCommand, shell);
551-
var approvalCheck = await EnsureApprovedAsync(fullCommand, shell, approval, sessionKey, correlationId);
552-
if (!approvalCheck.Allowed)
553-
{
554-
Logger.Warn($"system.run DENIED: {fullCommand} ({approval.Reason})");
555-
return Error($"Command denied by exec policy: {approval.Reason}");
556-
}
557-
558-
var outerApprovalCoversNestedTargets =
559-
approvalCheck.PromptDecisionKind != null ||
560-
IsExactAllowRuleForCommand(approval, fullCommand);
561-
562551
var parseResult = ExecShellWrapperParser.Expand(fullCommand, shell);
563552
if (!string.IsNullOrWhiteSpace(parseResult.Error))
564553
{
565554
Logger.Warn($"system.run DENIED: {fullCommand} ({parseResult.Error})");
566555
return Error($"Command denied by exec policy: {parseResult.Error}");
567556
}
568557

558+
var approval = _approvalPolicy.Evaluate(fullCommand, shell);
559+
var hasNestedTargets = parseResult.Targets.Count > 0;
560+
var hasExplicitOuterRule = !string.IsNullOrWhiteSpace(approval.MatchedPattern);
561+
var evaluateOuter =
562+
!hasNestedTargets ||
563+
hasExplicitOuterRule ||
564+
approval.Allowed ||
565+
approval.Action == ExecApprovalAction.Prompt;
566+
var approvalCheck = new ExecApprovalCheckResult(false, null);
567+
if (evaluateOuter)
568+
{
569+
approvalCheck = await EnsureApprovedAsync(fullCommand, shell, approval, sessionKey, correlationId);
570+
if (!approvalCheck.Allowed)
571+
{
572+
Logger.Warn($"system.run DENIED: {fullCommand} ({approval.Reason})");
573+
return Error($"Command denied by exec policy: {approval.Reason}");
574+
}
575+
}
576+
577+
var outerApprovalCoversNestedTargets =
578+
approvalCheck.PromptDecisionKind != null ||
579+
IsExactAllowRuleForCommand(approval, fullCommand);
580+
581+
// Gateway execution wraps Windows commands in cmd.exe. Only an
582+
// unmatched default deny may defer to exact parsed-payload rules;
583+
// explicit/default prompts still show and persist the full wrapper.
569584
foreach (var target in parseResult.Targets)
570585
{
571586
var innerApproval = _approvalPolicy.Evaluate(target.Command, target.Shell);
@@ -590,6 +605,15 @@ private async Task<ExecApprovalCheckResult> EnsureApprovedAsync(
590605
Logger.Warn($"system.run DENIED: {target.Command} ({innerApproval.Reason})");
591606
return Error($"Command denied by exec policy: {innerApproval.Reason}");
592607
}
608+
609+
if (!evaluateOuter &&
610+
innerApprovalCheck.PromptDecisionKind == null &&
611+
!IsExactAllowRuleForCommand(innerApproval, target.Command))
612+
{
613+
const string reason = "Wrapped commands require an exact allow rule";
614+
Logger.Warn($"system.run DENIED: {target.Command} ({reason})");
615+
return Error($"Command denied by exec policy: {reason}");
616+
}
593617
}
594618

595619
return null;

‎src/OpenClaw.Shared/Mcp/McpToolBridge.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ private object HandleToolsList()
187187
["system.notify"] =
188188
"Show a Windows toast notification on the node. Args: title (string, default 'OpenClaw'), body (string), subtitle (string), sound (bool, default true). Returns { sent: true }.",
189189
["system.run"] =
190-
"Execute a shell command on the Windows node host. Args: command (string or string[] argv, required), args (string[]), shell (string), cwd (string), timeoutMs (int, default 30000), env (object). Subject to the local exec approval policy. Returns { stdout, stderr, exitCode, timedOut, durationMs }.",
190+
"Execute a shell command on the Windows node host. Args: command (string or string[] argv, required), args (string[]), shell (string), cwd (string), timeoutMs (int, default 30000), env (object). Subject to the local exec approval policy. Returns { stdout, stderr, exitCode, timedOut, success, durationMs }.",
191191
["system.run.prepare"] =
192192
"Pre-flight a system.run invocation: returns the parsed execution plan (argv, cwd, rawCommand, agentId, sessionKey) without running anything. The gateway uses this to build its approval context before the actual run.",
193193
["system.which"] =

‎src/OpenClaw.Shared/Mxc/MxcConfigBuilder.cs‎

Lines changed: 54 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Text;
22
using System.Security.AccessControl;
33
using System.Security.Principal;
4+
using System.Runtime.Versioning;
45

56
namespace OpenClaw.Shared.Mxc;
67

@@ -22,9 +23,9 @@ namespace OpenClaw.Shared.Mxc;
2223
/// launched shell. Explicit <c>process.env</c> injection is intentionally
2324
/// disabled for the current Windows MXC 0.7 processcontainer backend because
2425
/// non-empty env entries fail process creation.</item>
25-
/// <item>Cwd auto-grant — adds <c>request.Cwd</c> as readonly when not already
26-
/// covered by an allow grant. AppContainer does NOT auto-grant cwd, so this
27-
/// is required for commands to even start.</item>
26+
/// <item>Cwd handling — defaults omitted cwd to the writable per-run scratch
27+
/// directory, and adds an explicit request cwd as readonly when not already
28+
/// covered by an allow grant. AppContainer does NOT auto-grant cwd.</item>
2829
/// <item>Defensive re-filter of allow lists against the deny list.</item>
2930
/// <item>Shell command-line construction (cmd <c>/S /C</c>, powershell
3031
/// <c>-EncodedCommand</c>).</item>
@@ -68,6 +69,7 @@ internal static MxcConfig Build(
6869
var readonlyGrantIsBackendSafe = context.ReadonlyGrantIsBackendSafe ?? IsBackendSafeReadonlyGrant;
6970

7071
var policy = request.Policy;
72+
var workingDirectory = string.IsNullOrWhiteSpace(request.Cwd) ? scratchDir : request.Cwd;
7173
var args = ParseSystemRunArgs(request.Args);
7274
var shell = NormalizeSupportedShell(args.Shell);
7375
if (IsPowerShellFamilyShell(shell) && policy?.Ui?.AllowWindows != true)
@@ -171,7 +173,7 @@ internal static MxcConfig Build(
171173
Process = new MxcProcess
172174
{
173175
CommandLine = commandLine,
174-
Cwd = string.IsNullOrWhiteSpace(request.Cwd) ? null : request.Cwd,
176+
Cwd = workingDirectory,
175177
Env = env,
176178
TimeoutMs = timeoutMs,
177179
},
@@ -263,52 +265,72 @@ private static bool CanMxcDaclFallbackPreparePath(string dir)
263265
if (!OperatingSystem.IsWindows())
264266
return true;
265267

268+
return CanMxcDaclFallbackPreparePathWindows(dir);
269+
}
270+
271+
[SupportedOSPlatform("windows")]
272+
private static bool CanMxcDaclFallbackPreparePathWindows(string dir)
273+
{
266274
try
267275
{
268276
var identity = WindowsIdentity.GetCurrent();
269-
var principals = new HashSet<SecurityIdentifier>();
270-
if (identity.User is not null)
271-
principals.Add(identity.User);
277+
if (identity.User is null)
278+
return false;
279+
280+
var tokenSids = new HashSet<SecurityIdentifier> { identity.User };
272281
if (identity.Groups is not null)
273282
{
274-
foreach (var group in identity.Groups)
275-
{
276-
if (group is SecurityIdentifier sid)
277-
principals.Add(sid);
278-
}
283+
foreach (var group in identity.Groups.OfType<SecurityIdentifier>())
284+
tokenSids.Add(group);
279285
}
280286

281-
if (principals.Count == 0)
282-
return false;
283-
284287
var rules = new DirectoryInfo(dir)
285288
.GetAccessControl(AccessControlSections.Access)
286289
.GetAccessRules(includeExplicit: true, includeInherited: true, targetType: typeof(SecurityIdentifier));
287290

288-
var allowed = false;
289-
foreach (FileSystemAccessRule rule in rules)
290-
{
291-
if (rule.IdentityReference is not SecurityIdentifier sid || !principals.Contains(sid))
292-
continue;
293-
294-
if ((rule.FileSystemRights & (FileSystemRights.ChangePermissions | FileSystemRights.FullControl)) == 0)
295-
continue;
296-
297-
if (rule.AccessControlType == AccessControlType.Deny)
298-
return false;
299-
300-
if (rule.AccessControlType == AccessControlType.Allow)
301-
allowed = true;
302-
}
303-
304-
return allowed;
291+
return HasDirectUserChangePermissions(
292+
rules.OfType<FileSystemAccessRule>(),
293+
identity.User,
294+
tokenSids.Contains);
305295
}
306296
catch
307297
{
308298
return false;
309299
}
310300
}
311301

302+
[SupportedOSPlatform("windows")]
303+
internal static bool HasDirectUserChangePermissions(
304+
IEnumerable<FileSystemAccessRule> rules,
305+
SecurityIdentifier userSid,
306+
Func<SecurityIdentifier, bool> isTokenSid)
307+
{
308+
ArgumentNullException.ThrowIfNull(rules);
309+
ArgumentNullException.ThrowIfNull(userSid);
310+
ArgumentNullException.ThrowIfNull(isTokenSid);
311+
312+
var allowed = false;
313+
foreach (var rule in rules)
314+
{
315+
if (rule.IdentityReference is not SecurityIdentifier sid)
316+
continue;
317+
318+
if ((rule.FileSystemRights & FileSystemRights.ChangePermissions) == 0)
319+
continue;
320+
321+
var isUser = sid.Equals(userSid);
322+
if (rule.AccessControlType == AccessControlType.Deny && (isUser || isTokenSid(sid)))
323+
return false;
324+
325+
// MXC's DACL fallback runs under a restricted token. An admin-group
326+
// allow on the host does not grant that token WRITE_DAC.
327+
if (rule.AccessControlType == AccessControlType.Allow && isUser)
328+
allowed = true;
329+
}
330+
331+
return allowed;
332+
}
333+
312334
private static bool IsProtectedSystemPath(string dir)
313335
{
314336
if (!OperatingSystem.IsWindows())

0 commit comments

Comments
 (0)