File size: 26,669 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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using System.Threading;
#if !UNIX
using System.Security.Principal;
#endif
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting.Server
{
internal abstract class OutOfProcessMediatorBase
{
#region Protected Data
protected TextReader originalStdIn;
protected OutOfProcessTextWriter originalStdOut;
protected OutOfProcessTextWriter originalStdErr;
protected OutOfProcessServerSessionTransportManager sessionTM;
protected OutOfProcessUtils.DataProcessingDelegates callbacks;
protected static object SyncObject = new object();
protected object _syncObject = new object();
protected string _initialCommand;
protected ManualResetEvent allcmdsClosedEvent;
#if !UNIX
// Thread impersonation.
protected WindowsIdentity _windowsIdentityToImpersonate;
#endif
/// <summary>
/// Count of commands in progress.
/// </summary>
protected int _inProgressCommandsCount = 0;
protected PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected bool _exitProcessOnError;
#endregion
#region Constructor
protected OutOfProcessMediatorBase(bool exitProcessOnError)
{
_exitProcessOnError = exitProcessOnError;
// Set up data handling callbacks.
callbacks = new OutOfProcessUtils.DataProcessingDelegates();
callbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived);
callbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived);
callbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived);
callbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived);
callbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived);
callbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckPacketReceived);
callbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived);
callbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSignalAckPacketReceived);
allcmdsClosedEvent = new ManualResetEvent(true);
}
#endregion
#region Data Processing handlers
protected void ProcessingThreadStart(object state)
{
try
{
string data = state as string;
OutOfProcessUtils.ProcessData(data, callbacks);
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError,
PSOpcode.Open,
PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic,
PSOpcode.Open,
PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
// notify the remote client of any errors and fail gracefully
if (_exitProcessOnError)
{
originalStdErr.WriteLine(e.Message + e.StackTrace);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid)
{
string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDIN;
if (stream.Equals(nameof(DataPriorityType.PromptResponse), StringComparison.OrdinalIgnoreCase))
{
streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE;
}
if (psGuid == Guid.Empty)
{
lock (_syncObject)
{
sessionTM.ProcessRawData(rawData, streamTemp);
}
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
if (cmdTM != null)
{
// not throwing when there is no associated command as the command might have
// legitimately closed while the client is sending data. however the client
// should die after timeout as we are not sending an ACK back.
cmdTM.ProcessRawData(rawData, streamTemp);
}
else
{
// There is no command transport manager to process the input data.
// However, we still need to acknowledge to the client that this input data
// was received. This can happen with some cmdlets such as Select-Object -First
// where the cmdlet completes before all input data is received.
originalStdOut.WriteLine(OutOfProcessUtils.CreateDataAckPacket(psGuid));
}
}
}
protected void OnDataAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(
PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG);
}
protected void OnCommandCreationPacketReceived(Guid psGuid)
{
lock (_syncObject)
{
sessionTM.CreateCommandTransportManager(psGuid);
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Reset();
_inProgressCommandsCount++;
tracer.WriteMessage("OutOfProcessMediator.OnCommandCreationPacketReceived, in progress command count : " + _inProgressCommandsCount + " psGuid : " + psGuid.ToString());
}
}
protected void OnCommandCreationAckReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG);
}
protected void OnSignalPacketReceived(Guid psGuid)
{
if (psGuid == Guid.Empty)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCNoSignalForSession, RemotingErrorIdStrings.IPCNoSignalForSession,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG);
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
try
{
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
cmdTM?.Close(null);
}
finally
{
// Always send ack signal to avoid not responding in client.
originalStdOut.WriteLine(OutOfProcessUtils.CreateSignalAckPacket(psGuid));
}
}
}
protected void OnSignalAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG);
}
protected void OnClosePacketReceived(Guid psGuid)
{
PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
if (psGuid == Guid.Empty)
{
tracer.WriteMessage("BEGIN calling close on session transport manager");
bool waitForAllcmdsClosedEvent = false;
lock (_syncObject)
{
if (_inProgressCommandsCount > 0)
waitForAllcmdsClosedEvent = true;
}
// Wait outside sync lock if required for all cmds to be closed
//
if (waitForAllcmdsClosedEvent)
allcmdsClosedEvent.WaitOne();
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
// it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests
// changing PSRP/IPC at this point is too risky, therefore protecting about this duplication
sessionTM?.Close(null);
tracer.WriteMessage("END calling close on session transport manager");
sessionTM = null;
}
}
else
{
tracer.WriteMessage("Closing command with GUID " + psGuid.ToString());
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
cmdTM?.Close(null);
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be greater than zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
_inProgressCommandsCount--;
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Set();
}
}
// send close ack
originalStdOut.WriteLine(OutOfProcessUtils.CreateCloseAckPacket(psGuid));
}
protected void OnCloseAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG);
}
#endregion
#region Methods
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(
string configurationName,
string configurationFile,
PSRemotingCryptoHelperServer cryptoHelper,
string workingDirectory)
{
PSSenderInfo senderInfo;
#if !UNIX
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
PSPrincipal userPrincipal = new PSPrincipal(
new PSIdentity(string.Empty, true, currentIdentity.Name, null),
currentIdentity);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#else
PSPrincipal userPrincipal = new PSPrincipal(
new PSIdentity(string.Empty, true, string.Empty, null),
null);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#endif
var tm = new OutOfProcessServerSessionTransportManager(
originalStdOut,
originalStdErr,
cryptoHelper);
ServerRemoteSession.CreateServerRemoteSession(
senderInfo: senderInfo,
configurationProviderId: "Microsoft.PowerShell",
initializationParameters: string.Empty,
transportManager: tm,
initialCommand: _initialCommand,
configurationName: configurationName,
configurationFile: configurationFile,
initialLocation: workingDirectory);
return tm;
}
protected void Start(
string initialCommand,
PSRemotingCryptoHelperServer cryptoHelper,
string workingDirectory,
string configurationName,
string configurationFile)
{
_initialCommand = initialCommand;
sessionTM = CreateSessionTransportManager(
configurationName: configurationName,
configurationFile: configurationFile,
cryptoHelper: cryptoHelper,
workingDirectory: workingDirectory);
try
{
while (true)
{
string data = originalStdIn.ReadLine();
lock (_syncObject)
{
sessionTM ??= CreateSessionTransportManager(
configurationName: configurationName,
configurationFile: configurationFile,
cryptoHelper: cryptoHelper,
workingDirectory: workingDirectory);
}
if (string.IsNullOrEmpty(data))
{
lock (_syncObject)
{
// give a chance to runspace/pipelines to close (as it looks like the client died
// intermittently)
sessionTM.Close(null);
sessionTM = null;
}
throw new PSRemotingTransportException(
PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived,
string.Empty);
}
// process data in a thread pool thread..this way Runspace, Command
// data can be processed concurrently.
#if !UNIX
Utils.QueueWorkItemWithImpersonation(
_windowsIdentityToImpersonate,
new WaitCallback(ProcessingThreadStart),
data);
#else
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessingThreadStart), data);
#endif
}
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError,
PSOpcode.Open,
PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic,
PSOpcode.Open,
PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
if (_exitProcessOnError)
{
// notify the remote client of any errors and fail gracefully
originalStdErr.WriteLine(e.Message);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
#endregion
}
internal sealed class StdIOProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static StdIOProcessMediator s_singletonInstance;
#endregion
#region Constructors
/// <summary>
/// The mediator will take actions from the StdIn stream and responds to them.
/// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null. This is
/// to make sure these streams are totally used by our Mediator.
/// </summary>
/// <param name="combineErrOutStream">Redirects remoting errors to the Out stream.</param>
private StdIOProcessMediator(bool combineErrOutStream) : base(exitProcessOnError: true)
{
// Create input stream reader from Console standard input stream.
// We don't use the provided Console.In TextReader because it can have
// an incorrect encoding, e.g., Hyper-V Container console where the
// TextReader has incorrect default console encoding instead of the actual
// stream encoding. This way the stream encoding is determined by the
// stream BOM as needed.
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
// Remoting errors can optionally be written to stdErr or stdOut with
// special formatting.
originalStdOut = new OutOfProcessTextWriter(Console.Out);
if (combineErrOutStream)
{
originalStdErr = new FormattedErrorTextWriter(Console.Out);
}
else
{
originalStdErr = new OutOfProcessTextWriter(Console.Error);
}
// Replacing StdIn, StdOut, StdErr with Null so that no other app messes with the
// original streams.
Console.SetIn(TextReader.Null);
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
}
#endregion
#region Static Methods
/// <summary>
/// Starts the out-of-process powershell server instance.
/// </summary>
/// <param name="initialCommand">Specifies the initialization script.</param>
/// <param name="workingDirectory">Specifies the initial working directory. The working directory is set before the initial command.</param>
/// <param name="configurationName">Specifies an optional configuration name that configures the endpoint session.</param>
/// <param name="configurationFile">Specifies an optional path to a configuration (.pssc) file for the session.</param>
/// <param name="combineErrOutStream">Specifies the option to write remoting errors to stdOut stream, with special formatting.</param>
internal static void Run(
string initialCommand,
string workingDirectory,
string configurationName,
string configurationFile,
bool combineErrOutStream)
{
lock (SyncObject)
{
if (s_singletonInstance != null)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new StdIOProcessMediator(combineErrOutStream);
}
s_singletonInstance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: workingDirectory,
configurationName: configurationName,
configurationFile: configurationFile);
}
#endregion
}
internal sealed class NamedPipeProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static NamedPipeProcessMediator s_singletonInstance;
private readonly RemoteSessionNamedPipeServer _namedPipeServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _namedPipeServer.IsDisposed; }
}
#endregion
#region Constructors
private NamedPipeProcessMediator() : base(false) { }
private NamedPipeProcessMediator(
RemoteSessionNamedPipeServer namedPipeServer) : base(false)
{
if (namedPipeServer == null)
{
throw new PSArgumentNullException(nameof(namedPipeServer));
}
_namedPipeServer = namedPipeServer;
// Create transport reader/writers from named pipe.
originalStdIn = namedPipeServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
originalStdErr = new FormattedErrorTextWriter(namedPipeServer.TextWriter);
#if !UNIX
// Flow impersonation as needed.
Utils.TryGetWindowsImpersonatedIdentity(out _windowsIdentityToImpersonate);
#endif
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
RemoteSessionNamedPipeServer namedPipeServer)
{
lock (SyncObject)
{
if (s_singletonInstance != null && !s_singletonInstance.IsDisposed)
{
Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed.");
return;
}
s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer);
}
s_singletonInstance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: null,
configurationName: namedPipeServer.ConfigurationName,
configurationFile: null);
}
#endregion
}
internal sealed class FormattedErrorTextWriter : OutOfProcessTextWriter
{
#region Constructors
internal FormattedErrorTextWriter(
TextWriter textWriter) : base(textWriter)
{ }
#endregion
#region Base class overrides
// Write error data to stream with 'ErrorPrefix' prefix that will
// be interpreted by the client.
public override void WriteLine(string data)
{
string dataToWrite = (data != null) ? ErrorPrefix + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
internal sealed class HyperVSocketMediator : OutOfProcessMediatorBase
{
#region Private Data
private static HyperVSocketMediator s_instance;
private readonly RemoteSessionHyperVSocketServer _hypervSocketServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _hypervSocketServer.IsDisposed; }
}
#endregion
#region Constructors
private HyperVSocketMediator()
: base(false)
{
_hypervSocketServer = new RemoteSessionHyperVSocketServer(false);
originalStdIn = _hypervSocketServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
}
private HyperVSocketMediator(string token,
DateTimeOffset tokenCreationTime)
: base(false)
{
_hypervSocketServer = new RemoteSessionHyperVSocketServer(false, token: token, tokenCreationTime: tokenCreationTime);
originalStdIn = _hypervSocketServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
string configurationName)
{
lock (SyncObject)
{
s_instance = new HyperVSocketMediator();
}
s_instance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: null,
configurationName: configurationName,
configurationFile: null);
}
internal static void Run(
string initialCommand,
string configurationName,
string token,
DateTimeOffset tokenCreationTime)
{
lock (SyncObject)
{
s_instance = new HyperVSocketMediator(token, tokenCreationTime);
}
s_instance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: null,
configurationName: configurationName,
configurationFile: null);
}
#endregion
}
internal sealed class HyperVSocketErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__HyperVSocketError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal HyperVSocketErrorTextWriter(
TextWriter textWriter)
: base(textWriter)
{ }
#endregion
#region Base class overrides
public override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
}
|