File size: 16,029 Bytes
8c763fb | 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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Security;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Provides a reference to a runspace that can be used to temporarily
/// push a remote runspace on top of a local runspace. This is
/// primary used by Start-PSSession. The purpose of this class is to hide
/// the CreatePipeline method and force it to be used as defined in this
/// class.
/// </summary>
internal class RunspaceRef
{
/// <summary>
/// Runspace ref.
/// </summary>
private readonly ObjectRef<Runspace> _runspaceRef;
private bool _stopInvoke;
private readonly object _localSyncObject;
private static readonly RobustConnectionProgress s_RCProgress = new RobustConnectionProgress();
/// <summary>
/// Constructor for RunspaceRef.
/// </summary>
internal RunspaceRef(Runspace runspace)
{
Dbg.Assert(runspace != null, "Expected runspace != null");
_runspaceRef = new ObjectRef<Runspace>(runspace);
_stopInvoke = false;
_localSyncObject = new object();
}
/// <summary>
/// Revert.
/// </summary>
internal void Revert()
{
_runspaceRef.Revert();
lock (_localSyncObject)
{
_stopInvoke = true;
}
}
/// <summary>
/// Runspace.
/// </summary>
internal Runspace Runspace
{
get
{
return _runspaceRef.Value;
}
}
internal Runspace OldRunspace
{
get { return _runspaceRef.OldValue; }
}
/// <summary>
/// Is runspace overridden.
/// </summary>
internal bool IsRunspaceOverridden
{
get
{
return _runspaceRef.IsOverridden;
}
}
/// <summary>
/// Parse ps command using script block.
/// </summary>
private PSCommand ParsePsCommandUsingScriptBlock(string line, bool? useLocalScope)
{
try
{
// Extract execution context from local runspace.
Runspace localRunspace = _runspaceRef.OldValue;
ExecutionContext context = localRunspace.ExecutionContext;
// This is trusted input as long as we're in FullLanguage mode
// and if we are not in a loopback configuration mode, in which case we always force remote script commands
// to be parsed and evaluated on the remote session (not in the current local session).
RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace;
bool isConfiguredLoopback = remoteRunspace != null && remoteRunspace.IsConfiguredLoopBack;
bool inFullLanguage = context.LanguageMode == PSLanguageMode.FullLanguage;
if (context.LanguageMode == PSLanguageMode.ConstrainedLanguage
&& SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit)
{
// In audit mode, report but don't enforce.
inFullLanguage = true;
SystemPolicy.LogWDACAuditMessage(
context: context,
title: RemotingErrorIdStrings.WDACGetPowerShellLogTitle,
message: RemotingErrorIdStrings.WDACGetPowerShellLogMessage,
fqid: "GetPowerShellMayFail",
dropIntoDebugger: true);
}
bool isTrustedInput = !isConfiguredLoopback && inFullLanguage;
// Create PowerShell from ScriptBlock.
ScriptBlock scriptBlock = ScriptBlock.Create(context, line);
PowerShell powerShell = scriptBlock.GetPowerShell(context, isTrustedInput, useLocalScope, null);
return powerShell.Commands;
}
catch (ScriptBlockToPowerShellNotSupportedException)
{
}
catch (RuntimeException)
{
}
// If parsing failed return null.
return null;
}
/// <summary>
/// Create ps command.
/// </summary>
internal PSCommand CreatePsCommand(string line, bool isScript, bool? useNewScope)
{
// Fall-back to traditional approach if runspace is not pushed.
if (!this.IsRunspaceOverridden)
{
return CreatePsCommandNotOverridden(line, isScript, useNewScope);
}
// Try to parse commands as script-block.
PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, useNewScope);
// If that didn't work fall back to traditional approach.
if (psCommand == null)
{
return CreatePsCommandNotOverridden(line, isScript, useNewScope);
}
// Otherwise return the psCommandCollection we got.
return psCommand;
}
/// <summary>
/// Creates the PSCommand when the runspace is not overridden.
/// </summary>
private static PSCommand CreatePsCommandNotOverridden(string line, bool isScript, bool? useNewScope)
{
PSCommand command = new PSCommand();
if (isScript)
{
if (useNewScope.HasValue)
{
command.AddScript(line, useNewScope.Value);
}
else
{
command.AddScript(line);
}
}
else
{
if (useNewScope.HasValue)
{
command.AddCommand(line, useNewScope.Value);
}
else
{
command.AddCommand(line);
}
}
return command;
}
/// <summary>
/// Create pipeline.
/// </summary>
internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedPipelines)
{
// This method allows input commands to work against no-language runspaces. If a runspace
// is pushed, it tries to parse the line using a ScriptBlock object. If a runspace is not
// pushed, or if the parsing fails, in these cases it reverts to calling CreatePipeline
// using the unparsed line.
Pipeline pipeline = null;
// In Start-PSSession scenario try to create a pipeline by parsing the line as a script block.
if (this.IsRunspaceOverridden)
{
// Win8: exit should work to escape from the restrictive session
if ((_runspaceRef.Value is RemoteRunspace) &&
(!string.IsNullOrEmpty(line) && string.Equals(line.Trim(), "exit", StringComparison.OrdinalIgnoreCase)))
{
line = "Exit-PSSession";
}
PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, null);
if (psCommand != null)
{
pipeline = useNestedPipelines ?
_runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory) :
_runspaceRef.Value.CreatePipeline(psCommand.Commands[0].CommandText, addToHistory);
pipeline.Commands.Clear();
foreach (Command command in psCommand.Commands)
{
pipeline.Commands.Add(command);
}
}
}
// If that didn't work out fall-back to the traditional approach.
pipeline ??= useNestedPipelines ?
_runspaceRef.Value.CreateNestedPipeline(line, addToHistory) :
_runspaceRef.Value.CreatePipeline(line, addToHistory);
// Add robust connection callback if this is a pushed runspace.
RemotePipeline remotePipeline = pipeline as RemotePipeline;
if (this.IsRunspaceOverridden && remotePipeline != null)
{
PowerShell shell = remotePipeline.PowerShell;
if (shell.RemotePowerShell != null)
{
shell.RemotePowerShell.RCConnectionNotification += HandleRCConnectionNotification;
}
// Add callback to write robust connection errors from stream.
shell.ErrorBuffer.DataAdded += (sender, eventArgs) =>
{
RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace;
PSDataCollection<ErrorRecord> erBuffer = sender as PSDataCollection<ErrorRecord>;
if (remoteRunspace != null && erBuffer != null &&
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null)
{
Collection<ErrorRecord> erRecords = erBuffer.ReadAll();
foreach (var er in erRecords)
{
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(er.ToString());
}
}
};
}
pipeline.SetHistoryString(line);
return pipeline;
}
/// <summary>
/// Create pipeline.
/// </summary>
internal Pipeline CreatePipeline()
{
return _runspaceRef.Value.CreatePipeline();
}
/// <summary>
/// Create nested pipeline.
/// </summary>
internal Pipeline CreateNestedPipeline()
{
return _runspaceRef.Value.CreateNestedPipeline();
}
/// <summary>
/// Override.
/// </summary>
internal void Override(RemoteRunspace remoteRunspace)
{
bool isRunspacePushed = false;
Override(remoteRunspace, null, out isRunspacePushed);
}
/// <summary>
/// Override inside a safe lock.
/// </summary>
/// <param name="remoteRunspace">Runspace to override.</param>
/// <param name="syncObject">Object to use in synchronization.</param>
/// <param name="isRunspacePushed">Set is runspace pushed.</param>
internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
{
lock (_localSyncObject)
{
_stopInvoke = false;
}
try
{
if (syncObject != null)
{
lock (syncObject)
{
_runspaceRef.Override(remoteRunspace);
isRunspacePushed = true;
}
}
else
{
_runspaceRef.Override(remoteRunspace);
isRunspacePushed = true;
}
if ((remoteRunspace.GetCurrentlyRunningPipeline() != null))
{
// Don't execute command if pushed runspace is already running one.
return;
}
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.AddCommand("Get-Command");
powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
powerShell.Runspace = _runspaceRef.Value;
bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersion_2_0;
powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode;
int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3;
powerShell.RemotePowerShell.HostCallReceived += HandleHostCall;
IAsyncResult asyncResult = powerShell.BeginInvoke();
PSDataCollection<PSObject> results = new PSDataCollection<PSObject>();
while (!_stopInvoke)
{
asyncResult.AsyncWaitHandle.WaitOne(1000);
if (asyncResult.IsCompleted)
{
results = powerShell.EndInvoke(asyncResult);
break;
}
}
if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults)
{
throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
}
}
}
catch (Exception)
{
_runspaceRef.Revert();
isRunspacePushed = false;
throw;
}
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleHostCall(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs)
{
ClientRemotePowerShell.ExitHandler(sender, eventArgs);
}
#region Robust Connection Support
private void HandleRCConnectionNotification(object sender, PSConnectionRetryStatusEventArgs e)
{
switch (e.Notification)
{
case PSConnectionRetryStatus.NetworkFailureDetected:
StartProgressBar(sender.GetHashCode(), e.ComputerName, (e.MaxRetryConnectionTime / 1000));
break;
case PSConnectionRetryStatus.AutoDisconnectStarting:
case PSConnectionRetryStatus.ConnectionRetrySucceeded:
StopProgressBar(sender.GetHashCode());
break;
case PSConnectionRetryStatus.AutoDisconnectSucceeded:
case PSConnectionRetryStatus.InternalErrorAbort:
WriteRCFailedError();
StopProgressBar(sender.GetHashCode());
break;
}
}
private void WriteRCFailedError()
{
RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace;
if (remoteRunspace != null &&
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null)
{
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(
StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError,
remoteRunspace.ConnectionInfo.ComputerName));
}
}
private void StartProgressBar(
long sourceId,
string computerName,
int totalSeconds)
{
RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace;
if (remoteRunspace != null)
{
s_RCProgress.StartProgress(
sourceId,
computerName,
totalSeconds,
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host);
}
}
private static void StopProgressBar(
long sourceId)
{
s_RCProgress.StopProgress(sourceId);
}
#endregion
}
}
|