-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathProgram.cs
More file actions
298 lines (253 loc) · 12.7 KB
/
Program.cs
File metadata and controls
298 lines (253 loc) · 12.7 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Management.Configuration;
using Microsoft.Management.Configuration.Processor;
using Microsoft.Management.Configuration.Processor.Helpers;
using WinRT;
using IConfigurationSetProcessorFactory = global::Microsoft.Management.Configuration.IConfigurationSetProcessorFactory;
namespace ConfigurationRemotingServer
{
/// <summary>
/// Custom assembly load context.
/// </summary>
internal class NativeAssemblyLoadContext : AssemblyLoadContext
{
private static readonly string PackageRootPath;
private static readonly NativeAssemblyLoadContext NativeALC = new();
static NativeAssemblyLoadContext()
{
var self = typeof(NativeAssemblyLoadContext).Assembly;
PackageRootPath = Path.Combine(
Path.GetDirectoryName(self.Location)!,
"..");
}
private NativeAssemblyLoadContext()
: base("NativeAssemblyLoadContext", isCollectible: false)
{
}
/// <summary>
/// Handler to resolve unmanaged assemblies.
/// </summary>
/// <param name="context">Assembly load context.</param>
/// <param name="name">Assembly name.</param>
/// <returns>The assembly, null if not in our assembly location.</returns>
internal static IntPtr ResolvingUnmanagedHandler(Assembly context, string name)
{
if (name.Equals("WindowsPackageManager.dll", StringComparison.OrdinalIgnoreCase))
{
return NativeALC.LoadUnmanagedDll(name);
}
return IntPtr.Zero;
}
/// <inheritdoc/>
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string path = Path.Combine(PackageRootPath, unmanagedDllName);
if (File.Exists(path))
{
return this.LoadUnmanagedDllFromPath(path);
}
return IntPtr.Zero;
}
}
internal class Program
{
private const string CommandLineSectionSeparator = "~~~~~~";
private const string ExternalModulesName = "ExternalModules";
static int Main(string[] args)
{
// Remove any attached console to prevent modules (or their actions) from writing to our console.
FreeConsole();
// Help find WindowsPackageManager.dll
AssemblyLoadContext.Default.ResolvingUnmanagedDll += NativeAssemblyLoadContext.ResolvingUnmanagedHandler;
string staticsCallback = args[1];
// Listen for setting change message and update PATH if needed.
EnvironmentChangeListener.EnvironmentChanged += OnEnvironmentChanged;
EnvironmentChangeListener environmentChangeListener = new EnvironmentChangeListener();
try
{
string completionEventName = args[2];
uint parentProcessId = uint.Parse(args[3]);
string processorEngine = args[4];
ConfigurationSet? limitationSet = null;
LimitationSetMetadata? limitationSetMetadata = null;
// Parse limitation set if applicable.
// The format will be:
// <Common args for initialization> ~~~~~~ <Metadata json> ~~~~~~ <Limitation Set in yaml>
// Metadata json format:
// {
// "path": "C:\full\file\path.yaml"
// }
// If a limitation set is provided, the processor will be limited
// to only work on units defined inside the limitation set.
var commandPtr = GetCommandLineW();
var commandStr = Marshal.PtrToStringUni(commandPtr) ?? string.Empty;
// In case the limitation set content contains the separator, we'll not use Split method.
var firstSeparatorIndex = commandStr.IndexOf(CommandLineSectionSeparator);
if (firstSeparatorIndex > 0)
{
var secondSeparatorIndex = commandStr.IndexOf(CommandLineSectionSeparator, firstSeparatorIndex + CommandLineSectionSeparator.Length);
if (secondSeparatorIndex <= 0)
{
throw new ArgumentException("The input command contains only one separator string.");
}
// Parse limitation set.
byte[] limitationSetBytes = Encoding.UTF8.GetBytes(commandStr.Substring(secondSeparatorIndex + CommandLineSectionSeparator.Length));
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(limitationSetBytes);
memoryStream.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
ConfigurationProcessor processor = new ConfigurationProcessor((IConfigurationSetProcessorFactory?)null);
var limitationSetResult = processor.OpenConfigurationSet(memoryStream.AsInputStream());
memoryStream.Close();
if (limitationSetResult.ResultCode != null)
{
throw limitationSetResult.ResultCode;
}
limitationSet = limitationSetResult.Set;
if (limitationSet == null)
{
throw new ArgumentException("The limitation set cannot be parsed.");
}
// Now parse metadata json and update the limitation set
limitationSetMetadata = JsonSerializer.Deserialize<LimitationSetMetadata>(commandStr.Substring(
firstSeparatorIndex + CommandLineSectionSeparator.Length,
secondSeparatorIndex - firstSeparatorIndex - CommandLineSectionSeparator.Length));
if (limitationSetMetadata != null)
{
limitationSet.Path = limitationSetMetadata.Path;
}
}
IConfigurationSetProcessorFactory factory = CreateFactory(processorEngine, limitationSet, limitationSetMetadata);
IObjectReference factoryInterface = MarshalInterface<IConfigurationSetProcessorFactory>.CreateMarshaler(factory);
return WindowsPackageManagerConfigurationCompleteOutOfProcessFactoryInitialization(0, factoryInterface.ThisPtr, staticsCallback, completionEventName, parentProcessId);
}
catch (Exception ex)
{
WindowsPackageManagerConfigurationCompleteOutOfProcessFactoryInitialization(ex.HResult, IntPtr.Zero, staticsCallback, null, 0);
return ex.HResult;
}
finally
{
environmentChangeListener.Stop();
}
}
private static void OnEnvironmentChanged()
{
PathEnvironmentVariableHandler.UpdatePath();
}
private class LimitationSetMetadata
{
[JsonPropertyName("path")]
public string Path { get; set; } = string.Empty;
[JsonPropertyName("modulePath")]
public string? ModulePath { get; set; } = null;
[JsonPropertyName("processorPath")]
public string? ProcessorPath { get; set; } = null;
}
private static IConfigurationSetProcessorFactory CreateFactory(string processorEngine, ConfigurationSet? limitationSet, LimitationSetMetadata? limitationSetMetadata)
{
switch (processorEngine)
{
case "pwsh":
return CreatePowerShellFactory(limitationSet, limitationSetMetadata);
case "dscv3":
return CreateDSCv3Factory(limitationSet, limitationSetMetadata);
}
throw new NotImplementedException($"Processor engine unknown: {processorEngine}");
}
private static IConfigurationSetProcessorFactory CreatePowerShellFactory(ConfigurationSet? limitationSet, LimitationSetMetadata? limitationSetMetadata)
{
PowerShellConfigurationSetProcessorFactory factory = new PowerShellConfigurationSetProcessorFactory();
// Set default properties.
var externalModulesPath = GetExternalModulesPath();
if (string.IsNullOrWhiteSpace(externalModulesPath))
{
throw new DirectoryNotFoundException("Failed to get ExternalModules.");
}
// Set as implicit module paths so it will be always included in AdditionalModulePaths
factory.ImplicitModulePaths = new List<string>() { externalModulesPath };
factory.ProcessorType = PowerShellConfigurationProcessorType.Hosted;
if (limitationSetMetadata != null)
{
if (limitationSetMetadata.ModulePath != null)
{
PowerShellConfigurationProcessorLocation parsedLocation = PowerShellConfigurationProcessorLocation.Default;
if (Enum.TryParse(limitationSetMetadata.ModulePath, out parsedLocation))
{
factory.Location = parsedLocation;
}
else
{
factory.Location = PowerShellConfigurationProcessorLocation.Custom;
factory.CustomLocation = limitationSetMetadata.ModulePath;
}
}
}
// Apply limitation set and thereby disable changing properties.
if (limitationSet != null)
{
factory.LimitationSet = limitationSet;
}
return factory;
}
private static IConfigurationSetProcessorFactory CreateDSCv3Factory(ConfigurationSet? limitationSet, LimitationSetMetadata? limitationSetMetadata)
{
DSCv3ConfigurationSetProcessorFactory factory = new DSCv3ConfigurationSetProcessorFactory();
if (limitationSetMetadata != null)
{
if (limitationSetMetadata.ProcessorPath != null)
{
factory.DscExecutablePath = limitationSetMetadata.ProcessorPath;
}
else
{
// Require that the path to the DSC executable be presented to the user in limitation mode.
// This helps prevent path attacks against an elevated process (as long as the user checks the value).
throw new ArgumentNullException("The path to the DSC executable must be supplied in limitation mode.");
}
}
// Apply limitation set and thereby disable changing properties.
if (limitationSet != null)
{
factory.LimitationSet = limitationSet;
}
return factory;
}
private static string GetExternalModulesPath()
{
var currentAssemblyDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (currentAssemblyDirectoryPath != null)
{
var packageRootPath = Directory.GetParent(currentAssemblyDirectoryPath)?.FullName;
if (packageRootPath != null)
{
var externalModulesPath = Path.Combine(packageRootPath, ExternalModulesName);
if (Directory.Exists(externalModulesPath))
{
return externalModulesPath;
}
}
}
return string.Empty;
}
[DllImport("WindowsPackageManager.dll")]
private static extern int WindowsPackageManagerConfigurationCompleteOutOfProcessFactoryInitialization(
int result,
IntPtr factory,
[MarshalAs(UnmanagedType.LPWStr)]string staticsCallback,
[MarshalAs(UnmanagedType.LPWStr)]string? completionEventName,
uint parentProcessId);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetCommandLineW();
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
}
}