使用 InitialSessionState 约束 PowerShell Runspace:PowerShell01 示例深度解析

原创2026-10-14 20:05:001,360 阅读
文章标签:示例工程

使用 InitialSessionState 约束 PowerShell Runspace:PowerShell01 示例深度解析

导读

在 Windows 桌面应用中宿主 PowerShell 时,如何安全、可控地创建执行环境是核心问题。本指南基于 Windows-classic-samples 仓库中的 PowerShell/InitialSessionState 示例,系统讲解如何通过 SDK 层面的 InitialSessionState API 约束 Runspace——包括限制语言模式、增删命令与别名、标记命令为私有以及增删 Provider。读完本文,你将掌握用 C# 构建"最小化、可审计、按需放权"的 PowerShell 宿主环境的完整实战方案,并能对照仓库源码验证每一步的底层行为。

示例概述:用 SDK 而非脚本约束 Runspace

该示例(对应解决方案 PowerShell01.sln)聚焦于用 SDK 机制限制 Runspace 的六项能力,全部围绕 System.Management.Automation.Runspaces.InitialSessionState 类型展开。示例的完整实现位于 PowerShell01.cs,主体是 PowerShell01.RunCommands() 方法(见 PowerShell01.cs#L109-L217),其中串联执行了 13 段实验性脚本,每段运行后打印输出与错误信息,直观对比不同配置下的行为差异。

README 明确强调:本示例专注 SDK 路径,而脚本替代方案包括 $ExecutionContext.SessionState.LanguageMode 以及 PSSessionConfiguration cmdlets。也就是说,同样的约束能力既可在托管代码里声明式配置,也可在 PowerShell 会话内部或通过会话配置(Endpoint)达成;示例选择了前者,便于在桌面应用、自动化宿主等场景中把安全策略固化在代码里。

示例的六项目标(README 原文要点)

  1. 通过设置 InitialSessionState.LanguageMode 属性限制语言;
  2. 通过 InitialSessionState.Commands 属性向环境添加别名;
  3. 将命令标记为私有(Private);
  4. 通过 InitialSessionState.Providers 属性移除 Provider;
  5. 通过 InitialSessionState.Commands 属性移除命令;
  6. 添加命令与 Provider。

下文将逐一结合源码展开,并补充示例代码中未明说但源码已体现的进阶细节(如代理命令、Create() 与 CreateDefault() 的差异)。

前置概念:Runspace 与 InitialSessionState

在进入代码之前,先厘清两个核心对象的关系:

  • Runspace:PowerShell 命令实际执行的宿主运行空间,可以理解为一次独立的"PowerShell 进程内会话"。示例通过 RunspaceFactory.CreateRunspace(...) 创建,再调用 Open() 开启、Close() 关闭。
  • InitialSessionState:描述 Runspace 初始化时"预置了什么"的对象——包含默认加载的命令集合(Commands)、Provider 集合(Providers)、语言模式(LanguageMode)等。它相当于 Runspace 的"出生配置",在 Runspace 打开前完成设置。

示例的程序入口非常简洁(见 PowerShell01.cs#L61-L64):Main 直接实例化 PowerShell01 并调用 RunCommands(),所有实验按顺序执行,控制台等待按键后退出(Console.ReadLine())。

实验执行器 RunScript

所有对比实验复用同一个私有方法 RunScript(string script, string scriptComment)(见 PowerShell01.cs#L71-L104),它的实现揭示了"托管宿主 PowerShell"的标准调用链:

  1. PowerShell.Create() 创建命令管线对象;
  2. powerShellCommand.AddScript(script) 把要执行的脚本加入管线;
  3. powerShellCommand.Runspace = this.runspace 将脚本绑定到指定 Runspace——这是约束得以生效的关键,脚本不会在默认的全局会话里运行;
  4. powerShellCommand.Invoke() 同步执行并返回 Collection<PSObject>;
  5. 逐条打印结果对象;再遍历 powerShellCommand.Streams.Error 输出非终止性错误;
  6. 捕获 RuntimeException 处理终止性错误(如"命令不存在"、语言被禁止)。

理解了这套调用链,后续每个实验的输出差异就都源自 InitialSessionState 的配置差异,而非脚本本身。

目标一:用 LanguageMode 限制语言能力

PSLanguageMode 枚举控制 Runspace 内脚本引擎允许执行的语法子集,示例共演示了三种取值:

RestrictedLanguage:禁止变量赋值

this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
this.runspace.Open();
this.RunScript("$a=0;$a", "Assigning to a variable will not work in RestrictedLanguage LanguageMode");
this.runspace.Close();

(见 PowerShell01.cs#L116-L120)

注意一个容易被忽略的细节:示例是在 CreateRunspace 之后、Open() 之前通过 runspace.InitialSessionState 修改属性——只要 Runspace 尚未打开,配置仍可变。在 RestrictedLanguage 下,$a=0 这类变量赋值会被禁止,脚本执行报错,从而防止会话中出现状态写入类操作。

NoLanguage:彻底禁止脚本执行

this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.NoLanguage;
this.runspace.Open();
this.RunScript("10/2", "A script will not work in NoLanguage LanguageMode");
this.runspace.Close();

(见 PowerShell01.cs#L122-L126)

NoLanguage 是最严格的模式:即使 10/2 这样的简单表达式也无法作为脚本执行。该模式适合"只允许调用预设命令、禁止任何脚本逻辑"的高安全宿主场景。

FullLanguage:完整语言能力

示例在最后一段实验中将 cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage(见 PowerShell01.cs#L187-L194),用于在空白会话中恢复完整脚本能力。需要强调的是,LanguageMode 只约束"脚本语言能力",与命令/Provider 是否存在是两回事——这一点正是目标五、六要解决的问题。

目标二:通过 Commands 属性添加别名

别名本质上是一种 SessionStateAliasEntry 命令项。示例在默认会话基础上新增别名 dir2 指向 get-childitem:

InitialSessionState defaultSessionState = InitialSessionState.CreateDefault();
defaultSessionState.Commands.Add(new SessionStateAliasEntry("dir2", "get-childitem"));
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("dir2", "An alias, like dir2, can be added to InitialSessionState");
this.runspace.Close();

(见 PowerShell01.cs#L135-L140)

Commands.Add 接受各类 SessionStateCommandEntry 子类——本示例先后使用了 SessionStateAliasEntry、SessionStateFunctionEntry 和 SessionStateCmdletEntry,说明 Commands 集合是一套统一的"命令注入接口",别名、函数、cmdlet 都通过它登记进会话。

目标三:将命令标记为私有,并借助代理命令弥补缺口

这是示例中技术含量最高的部分(见 PowerShell01.cs#L158-L177),完整展示了"私有化 + 代理命令"的组合拳:

defaultSessionState = InitialSessionState.CreateDefault();
commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "get-childitem");
defaultSessionState.Commands[commandIndex].Visibility = SessionStateEntryVisibility.Private;

CommandMetadata getChildItemMetadata = new CommandMetadata(
    typeof(Microsoft.PowerShell.Commands.GetChildItemCommand));
getChildItemMetadata.Parameters.Remove("Recurse");
string getChildItemBody = ProxyCommand.Create(getChildItemMetadata);
defaultSessionState.Commands.Add(new SessionStateFunctionEntry("get-childitem2", getChildItemBody));

流程分四步:

  1. 定位命令项:用泛型辅助方法 GetIndexOfEntry<T>(见 PowerShell01.cs#L39-L55)在 Commands 集合中按名称(忽略大小写)找到 get-childitem 的下标;
  2. 标记私有:将该命令项的 Visibility 设为 SessionStateEntryVisibility.Private,此后 get-childitem 在会话中对用户不可见、不可调用;
  3. 生成代理命令体:以 GetChildItemCommand 类型构造 CommandMetadata,移除 Recurse 参数,再调用 ProxyCommand.Create(...) 生成一段代理函数脚本;
  4. 注册代理函数:把代理脚本作为 SessionStateFunctionEntry("get-childitem2", ...) 加入 Commands。

随后示例运行三段脚本验证效果:

  • get-childitem → 报错("get-childitem is private so it will not be available");
  • get-childitem2 → 成功("It works even when get-childitem is private");
  • get-childitem2 -Recurse → 失败("Unlike get-childitem, get-childitem2 does not have -Recurse")。

代理命令的典型用途由此显现:原命令被私有化后,宿主通过代理暴露一个"删减了危险参数"的精简版本,既保留核心功能,又收紧了攻击面。源码注释还指出,更完整的代理命令示例参见仓库中的 Runspace11 示例,读者可沿 PowerShell 目录继续深入。

目标四:移除 Provider

Provider 是 PowerShell 暴露"非命令资源"(文件系统、注册表、环境变量等)的机制。示例清空全部 Provider 后,即使命令本身仍存在,也会因缺少底层提供程序而无法工作:

defaultSessionState = InitialSessionState.CreateDefault();
defaultSessionState.Providers.Clear();
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("get-childitem", "There are no providers so get-childitem will not work");
this.runspace.Close();

(见 PowerShell01.cs#L151-L156)

Providers.Clear() 直接清空 InitialSessionState.Providers 集合,效果与"移除命令"类似但作用层面不同:命令是"可执行的操作",Provider 是"数据来源"。两者结合即可实现"命令在、数据源无"或"数据源在、命令无"的精细控制。

目标五:移除命令

示例用 GetIndexOfEntry 找到 get-childitem 后调用 Commands.RemoveItem(index) 将其删除:

defaultSessionState = InitialSessionState.CreateDefault();
int commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "get-childitem");
defaultSessionState.Commands.RemoveItem(commandIndex);
this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
this.runspace.Open();
this.RunScript("get-childitem", "get-childitem was removed ... it will no longer be found");
this.runspace.Close();

(见 PowerShell01.cs#L142-L149)

需要注意 RemoveItem 的入参是下标而非名称,这正是 GetIndexOfEntry 存在的意义——它负责把"命令名"转换为集合下标,体现了对 InitialSessionStateEntryCollection<T> 这类集合 API 的典型操作模式。

目标六:向空白会话添加命令与 Provider

前文所有实验都以 CreateDefault() 为起点(预置了标准 cmdlet 与 Provider),而最后一段实验改用 InitialSessionState.Create() 创建空白会话,再显式注入所需能力(见 PowerShell01.cs#L196-L213):

cleanSessionState = InitialSessionState.Create();
cleanSessionState.Commands.Add(
    new SessionStateCmdletEntry(
        "Get-ChildItem",
        typeof(Microsoft.PowerShell.Commands.GetChildItemCommand),
        null));
cleanSessionState.Providers.Add(
    new SessionStateProviderEntry(
        "FileSystem",
        typeof(Microsoft.PowerShell.Commands.FileSystemProvider),
        null));
cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage;
this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
this.runspace.Open();
this.RunScript("get-childitem", "... so get-childitem will work");
this.runspace.Close();

Create() 与 CreateDefault() 的关键差异

示例通过三连实验把两者差异讲得很透彻:

  • Create() 默认 LanguageMode 为 NoLanguage,且不含标准 cmdlet 与 Provider——示例先验证 10/2 无法执行(PowerShell01.cs#L179-L185),再验证即使把 LanguageMode 调成 FullLanguage,get-childitem 依然不存在(PowerShell01.cs#L187-L194);
  • 直到最后一段把 Get-ChildItem 命令项、FileSystem Provider 项和 FullLanguage 三者全部补齐,get-childitem 才恢复正常工作。

这一组实验是理解"语言模式、命令集、Provider 集三个维度相互独立"的最佳教材:任何单一维度都无法单独让一个命令可用,必须三者协同。对追求最小化攻击面的宿主而言,Create() + 白名单注入正是推荐的基线做法——默认什么都没有,需要什么就显式添加什么。

构建与运行示例

README 提供了标准 Visual Studio 流程:

构建

  1. 启动 Visual Studio,选择 File → Open → Project/Solution;
  2. 进入示例目录,双击解决方案文件 PowerShell01.sln;
  3. 按 F7 或使用 Build → Build Solution 构建。

可执行文件输出到默认的 bin 或 bin\Debug 目录。从 PowerShell01.csproj 可确认工程细节:OutputType 为 Exe,AssemblyName 为 PowerShell01,目标框架为 .NET Framework v4.0,并通过 HintPath 引用 GAC 中的 System.Management.Automation(3.0 版)与 Microsoft.PowerShell.Commands.Management 程序集。

运行

  1. 打开命令提示符;
  2. 切换到包含可执行文件的目录;
  3. 运行可执行文件;
  4. 对照输出结果阅读 PowerShell01.cs 中对应的代码段。

运行环境要求

README 明确列出的操作系统前提:

角色 系统
Client Windows 8.1
Server Windows Server 2012 R2

该版本要求与程序集引用(PowerShell 3.0 的 System.Management.Automation)一致,说明示例面向 Windows PowerShell 3.0 时代的内置 SDK 程序集;在新版本 Windows 上通常也可直接编译运行,但应确认目标框架与 PowerShell 程序集可用性。

补充:脚本替代方案与进阶方向

示例 README 特意点明的脚本替代方案值得记住:

  • $ExecutionContext.SessionState.LanguageMode:可在 PowerShell 会话内部动态查看/调整语言模式,适合脚本内自适应逻辑;
  • PSSessionConfiguration cmdlets(如 Register-PSSessionConfiguration):用于创建带约束的远程会话端点,适合服务端会话管理。

与 SDK 方式相比,脚本方案更灵活、可热调整,但策略散落在脚本与配置中;SDK 方式则在应用启动时即固化约束,适合桌面应用宿主。生产实践中两者常结合使用:SDK 负责"默认收敛",脚本/配置负责"运行期微调"。

小结

InitialSessionState 为 Windows 桌面应用宿主 PowerShell 提供了一整套声明式安全边界:LanguageMode 管语法、Commands 管可执行操作(含别名、函数、cmdlet 的增删与私有化)、Providers 管数据来源。PowerShell01 示例以 13 段对照实验完整演示了这套 API 的每个维度,其中"私有命令 + ProxyCommand 生成代理"与"Create() 白名单注入"两种模式尤其适合直接迁移到真实产品中。建议读者在阅读完本指南后,结合 PowerShell01.cs 逐段运行验证,并把 Readme.txt 中列出的六项目标作为自测清单。

登录后查看全文
Windows-classic-samples