File size: 48,248 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 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Tracing;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Diagnostics.Debug;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Shared named pipe utilities.
/// </summary>
internal static class NamedPipeUtils
{
#region Strings
internal const string NamedPipeNamePrefix = "PSHost.";
#if UNIX
internal const string DefaultAppDomainName = "None";
// This `CoreFxPipe` prefix is defined by CoreFx
internal const string NamedPipeNamePrefixSearch = "CoreFxPipe_PSHost*";
#else
internal const string DefaultAppDomainName = "DefaultAppDomain";
internal const string NamedPipeNamePrefixSearch = "PSHost*";
#endif
// On non-Windows, .NET named pipes are limited to up to 104 characters
internal const int MaxNamedPipeNameSize = 104;
#endregion
#region Static Methods
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId)
{
return CreateProcessPipeName(
System.Diagnostics.Process.GetProcessById(procId));
}
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc)
{
return CreateProcessPipeName(proc, DefaultAppDomainName);
}
/// <summary>
/// Create a pipe name based on process Id and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId,
string appDomainName)
{
return CreateProcessPipeName(System.Diagnostics.Process.GetProcessById(procId), appDomainName);
}
/// <summary>
/// Create a pipe name based on process and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc,
string appDomainName)
{
if (proc == null)
{
throw new PSArgumentNullException(nameof(proc));
}
if (string.IsNullOrEmpty(appDomainName))
{
appDomainName = DefaultAppDomainName;
}
System.Text.StringBuilder pipeNameBuilder = new System.Text.StringBuilder(MaxNamedPipeNameSize);
pipeNameBuilder.Append(NamedPipeNamePrefix)
// The starttime is there to prevent another process easily guessing the pipe name
// and squatting on it.
// There is a limit of 104 characters in total including the temp path to the named pipe file
// on non-Windows systems, so we'll convert the starttime to hex and just take the first 8 characters.
#if UNIX
.Append(proc.StartTime.ToFileTime().ToString("X8").AsSpan(1, 8))
#else
.Append(proc.StartTime.ToFileTime().ToString(CultureInfo.InvariantCulture))
#endif
.Append('.')
.Append(proc.Id.ToString(CultureInfo.InvariantCulture))
.Append('.')
.Append(CleanAppDomainNameForPipeName(appDomainName))
.Append('.')
.Append(proc.ProcessName);
#if UNIX
int charsToTrim = pipeNameBuilder.Length - MaxNamedPipeNameSize;
if (charsToTrim > 0)
{
// TODO: In the case the pipe name is truncated, the user cannot connect to it using the cmdlet
// unless we add a `-Force` type switch as it attempts to validate the current process name
// matches the process name in the pipe name
pipeNameBuilder.Remove(MaxNamedPipeNameSize + 1, charsToTrim);
}
#endif
return pipeNameBuilder.ToString();
}
private static string CleanAppDomainNameForPipeName(string appDomainName)
{
// Pipe names cannot contain the ':' character. Remove unwanted characters.
return appDomainName.Replace(":", string.Empty).Replace(" ", string.Empty);
}
/// <summary>
/// Returns the current process AppDomain name.
/// </summary>
/// <returns>AppDomain Name string.</returns>
internal static string GetCurrentAppDomainName()
{
#if CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
return DefaultAppDomainName;
#else // Use the AppDomain in which current powershell is running
return AppDomain.CurrentDomain.IsDefaultAppDomain() ? DefaultAppDomainName : AppDomain.CurrentDomain.FriendlyName;
#endif
}
#endregion
}
/// <summary>
/// Native API for Named Pipes.
/// </summary>
internal static class NamedPipeNative
{
#region Pipe constants
// Pipe open modes
internal const uint PIPE_ACCESS_DUPLEX = 0x00000003;
internal const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
internal const uint PIPE_ACCESS_INBOUND = 0x00000001;
// Pipe modes
internal const uint PIPE_TYPE_BYTE = 0x00000000;
internal const uint PIPE_TYPE_MESSAGE = 0x00000004;
internal const uint FILE_FLAG_OVERLAPPED = 0x40000000;
internal const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const uint PIPE_WAIT = 0x00000000;
internal const uint PIPE_NOWAIT = 0x00000001;
internal const uint PIPE_READMODE_BYTE = 0x00000000;
internal const uint PIPE_READMODE_MESSAGE = 0x00000002;
internal const uint PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
internal const uint PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
// Pipe errors
internal const uint ERROR_FILE_NOT_FOUND = 2;
internal const uint ERROR_BROKEN_PIPE = 109;
internal const uint ERROR_PIPE_BUSY = 231;
internal const uint ERROR_NO_DATA = 232;
internal const uint ERROR_MORE_DATA = 234;
internal const uint ERROR_PIPE_CONNECTED = 535;
internal const uint ERROR_IO_INCOMPLETE = 996;
internal const uint ERROR_IO_PENDING = 997;
#endregion
#region Data structures
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
/// <summary>
/// The size, in bytes, of this structure. Set this value to the size of the SECURITY_ATTRIBUTES structure.
/// </summary>
public int NLength;
/// <summary>
/// A pointer to a security descriptor for the object that controls the sharing of it.
/// </summary>
public IntPtr LPSecurityDescriptor = IntPtr.Zero;
/// <summary>
/// A Boolean value that specifies whether the returned handle is inherited when a new process is created.
/// </summary>
public bool InheritHandle;
/// <summary>
/// Initializes a new instance of the SECURITY_ATTRIBUTES class.
/// </summary>
public SECURITY_ATTRIBUTES()
{
this.NLength = 12;
}
}
#endregion
#region Pipe methods
[DllImport(PinvokeDllNames.CreateNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafePipeHandle CreateNamedPipe(
string lpName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
SECURITY_ATTRIBUTES securityAttributes);
internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescriptorPinnedHandle, bool inheritHandle = false)
{
SECURITY_ATTRIBUTES securityAttributes = new NamedPipeNative.SECURITY_ATTRIBUTES();
securityAttributes.InheritHandle = inheritHandle;
securityAttributes.NLength = (int)Marshal.SizeOf(securityAttributes);
securityAttributes.LPSecurityDescriptor = securityDescriptorPinnedHandle.AddrOfPinnedObject();
return securityAttributes;
}
#endregion
}
/// <summary>
/// Event arguments for listener thread end event.
/// </summary>
internal sealed class ListenerEndedEventArgs : EventArgs
{
#region Properties
/// <summary>
/// Exception reason for listener end event. Can be null
/// which indicates listener thread end is not due to an error.
/// </summary>
public Exception Reason { get; }
/// <summary>
/// True if listener should be restarted after ending.
/// </summary>
public bool RestartListener { get; }
#endregion
#region Constructors
private ListenerEndedEventArgs() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="reason">Listener end reason.</param>
/// <param name="restartListener">Restart listener.</param>
public ListenerEndedEventArgs(
Exception reason,
bool restartListener)
{
Reason = reason;
RestartListener = restartListener;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeServerStream class, that
/// creates the named pipe server with process named pipe name,
/// having correct access restrictions, and provides a listener
/// thread loop.
/// </summary>
public sealed class RemoteSessionNamedPipeServer : IDisposable
{
#region Members
private readonly object _syncObject;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
private const string _threadName = "IPC Listener Thread";
private const int _namedPipeBufferSizeForRemoting = 32768;
private const int _maxPipePathLengthLinux = 108;
private const int _maxPipePathLengthMacOS = 104;
// Singleton server.
private static readonly object s_syncObject;
internal static RemoteSessionNamedPipeServer IPCNamedPipeServer;
internal static bool IPCNamedPipeServerEnabled;
// Optional custom server.
private static RemoteSessionNamedPipeServer _customNamedPipeServer;
// Access mask constant taken from PipeSecurity access rights and is equivalent to
// PipeAccessRights.FullControl.
// See: https://msdn.microsoft.com/library/vstudio/bb348408(v=vs.100).aspx
//
private const int _pipeAccessMaskFullControl = 0x1f019f;
#endregion
#region Properties
/// <summary>
/// Returns the Named Pipe stream object.
/// </summary>
internal NamedPipeServerStream Stream { get; }
/// <summary>
/// Returns the Named Pipe name.
/// </summary>
internal string PipeName { get; }
/// <summary>
/// Returns true if listener is currently running.
/// </summary>
internal bool IsListenerRunning { get; private set; }
/// <summary>
/// Name of session configuration.
/// </summary>
internal string ConfigurationName { get; set; }
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
internal StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
internal StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
internal bool IsDisposed { get; private set; }
/// <summary>
/// Buffer size for PSRP fragmentor.
/// </summary>
internal static int NamedPipeBufferSizeForRemoting
{
get { return _namedPipeBufferSizeForRemoting; }
}
#endregion
#region Events
/// <summary>
/// Event raised when the named pipe server listening thread
/// ends.
/// </summary>
internal event EventHandler<ListenerEndedEventArgs> ListenerEnded;
#endregion
#region Constructors
/// <summary>
/// Creates a RemoteSessionNamedPipeServer with the current process and AppDomain information.
/// </summary>
/// <returns>RemoteSessionNamedPipeServer.</returns>
internal static RemoteSessionNamedPipeServer CreateRemoteSessionNamedPipeServer()
{
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
return new RemoteSessionNamedPipeServer(NamedPipeUtils.CreateProcessPipeName(
System.Diagnostics.Process.GetCurrentProcess(), appDomainName));
}
/// <summary>
/// Constructor. Creates named pipe server with provided pipe name.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeServer(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
_syncObject = new object();
PipeName = pipeName;
Stream = CreateNamedPipe(
serverName: ".",
namespaceName: "pipe",
coreName: pipeName,
securityDesc: GetServerPipeSecurity());
}
/// <summary>
/// Helper method to create a PowerShell transport named pipe via native API, along
/// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
/// </summary>
/// <param name="serverName">Named pipe server name.</param>
/// <param name="namespaceName">Named pipe namespace name.</param>
/// <param name="coreName">Named pipe core name.</param>
/// <param name="securityDesc"></param>
/// <returns>NamedPipeServerStream.</returns>
private static NamedPipeServerStream CreateNamedPipe(
string serverName,
string namespaceName,
string coreName,
CommonSecurityDescriptor securityDesc)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
#if !UNIX
string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Create optional security attributes based on provided PipeSecurity.
NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
GCHandle? securityDescHandle = null;
if (securityDesc != null)
{
byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
securityDesc.GetBinaryForm(securityDescBuffer, 0);
securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
}
// Create named pipe.
SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
fullPipeName,
NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE | NamedPipeNative.PIPE_REJECT_REMOTE_CLIENTS,
1,
_namedPipeBufferSizeForRemoting,
_namedPipeBufferSizeForRemoting,
0,
securityAttributes);
int lastError = Marshal.GetLastWin32Error();
securityDescHandle?.Free();
if (pipeHandle.IsInvalid)
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
}
// Create the .Net NamedPipeServerStream wrapper.
try
{
return new NamedPipeServerStream(
PipeDirection.InOut,
true, // IsAsync
false, // IsConnected
pipeHandle);
}
catch (Exception)
{
pipeHandle.Dispose();
throw;
}
#else
return new NamedPipeServerStream(
pipeName: coreName,
direction: PipeDirection.InOut,
maxNumberOfServerInstances: 1,
transmissionMode: PipeTransmissionMode.Byte,
options: PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly,
inBufferSize: _namedPipeBufferSizeForRemoting,
outBufferSize: _namedPipeBufferSizeForRemoting);
#endif
}
static RemoteSessionNamedPipeServer()
{
s_syncObject = new object();
// Unless opt-out, all PowerShell instances will start with the named-pipe listener created and running.
IPCNamedPipeServerEnabled = !Utils.GetEnvironmentVariableAsBool(name: "POWERSHELL_DIAGNOSTICS_OPTOUT", defaultValue: false);
if (IPCNamedPipeServerEnabled)
{
CreateIPCNamedPipeServerSingleton();
CreateProcessExitHandler();
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates the custom named pipe server with the given pipename.
/// </summary>
/// <param name="pipeName">The name of the pipe to create.</param>
public static void CreateCustomNamedPipeServer(string pipeName)
{
lock (s_syncObject)
{
if (_customNamedPipeServer != null && !_customNamedPipeServer.IsDisposed)
{
if (pipeName == _customNamedPipeServer.PipeName)
{
// we shouldn't recreate the server object if we're using the same pipeName
return;
}
// Dispose of the current pipe server so we can create a new one with the new pipeName
_customNamedPipeServer.Dispose();
}
if (!Platform.IsWindows)
{
int maxNameLength = (Platform.IsLinux ? _maxPipePathLengthLinux : _maxPipePathLengthMacOS) - Path.GetTempPath().Length;
if (pipeName.Length > maxNameLength)
{
throw new InvalidOperationException(
string.Format(
RemotingErrorIdStrings.CustomPipeNameTooLong,
maxNameLength,
pipeName,
pipeName.Length));
}
}
try
{
try
{
_customNamedPipeServer = new RemoteSessionNamedPipeServer(pipeName);
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
_customNamedPipeServer.ListenerEnded += OnCustomNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
_customNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
_customNamedPipeServer = null;
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Starts named pipe server listening thread. When a client connects this thread
/// makes a callback to implement the client communication. When the thread ends
/// this object is disposed and a new RemoteSessionNamedPipeServer must be created
/// and a new listening thread started to handle subsequent client connections.
/// </summary>
/// <param name="clientConnectCallback">Connection callback.</param>
internal void StartListening(
Action<RemoteSessionNamedPipeServer> clientConnectCallback)
{
if (clientConnectCallback == null)
{
throw new PSArgumentNullException(nameof(clientConnectCallback));
}
lock (_syncObject)
{
if (IsListenerRunning)
{
throw new InvalidOperationException(RemotingErrorIdStrings.NamedPipeAlreadyListening);
}
IsListenerRunning = true;
// Create listener thread.
Thread listenerThread = new Thread(ProcessListeningThread);
listenerThread.Name = _threadName;
listenerThread.IsBackground = true;
listenerThread.Start(clientConnectCallback);
}
}
internal static CommonSecurityDescriptor GetServerPipeSecurity()
{
#if UNIX
return null;
#else
// Built-in Admin SID
SecurityIdentifier adminSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1);
dacl.AddAccess(
AccessControlType.Allow,
adminSID,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
CommonSecurityDescriptor securityDesc = new CommonSecurityDescriptor(
false, false,
ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted,
null, null, null, dacl);
// Conditionally add User SID
bool isAdminElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
if (!isAdminElevated)
{
securityDesc.DiscretionaryAcl.AddAccess(
AccessControlType.Allow,
WindowsIdentity.GetCurrent().User,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
}
return securityDesc;
#endif
}
/// <summary>
/// Wait for client connection.
/// </summary>
private void WaitForConnection()
{
Stream.WaitForConnection();
}
/// <summary>
/// Process listening thread.
/// </summary>
/// <param name="state">Client callback delegate.</param>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
private void ProcessListeningThread(object state)
{
string processId = Environment.ProcessId.ToString(CultureInfo.InvariantCulture);
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
Exception ex = null;
string userName = string.Empty;
bool restartListenerThread = true;
// Wait for connection.
try
{
// Begin listening for a client connect.
this.WaitForConnection();
try
{
#if UNIX
userName = System.Environment.UserName;
#else
userName = WindowsIdentity.GetCurrent().Name;
#endif
}
catch (System.Security.SecurityException) { }
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
// Create reader/writer streams.
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
}
catch (Exception e)
{
ex = e;
}
if (ex != null)
{
// Error during connection handling. Don't try to restart listening thread.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
Dispose();
return;
}
// Start server session on new connection.
ex = null;
try
{
Action<RemoteSessionNamedPipeServer> clientConnectCallback = state as Action<RemoteSessionNamedPipeServer>;
Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");
// Handle a new client connect by making the callback.
// The callback must handle all exceptions except
// for a named pipe disposed or disconnected exception
// which propagates up to the thread listener loop.
clientConnectCallback(this);
}
catch (IOException)
{
// Expected connection terminated.
}
catch (ObjectDisposedException)
{
// Expected from PS transport close/dispose.
}
catch (Exception e)
{
ex = e;
restartListenerThread = false;
}
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
if (ex == null)
{
// Normal listener exit.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
}
else
{
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
}
lock (_syncObject)
{
IsListenerRunning = false;
}
// Ensure this named pipe server object is disposed.
Dispose();
ListenerEnded.SafeInvoke(
this,
new ListenerEndedEventArgs(ex, restartListenerThread));
}
#endregion
#region Static Methods
/// <summary>
/// Ensures the namedpipe singleton server is running and waits for a client connection.
/// This is a blocking call that returns after the client connection ends.
/// This method supports PowerShell running in "NamedPipeServerMode", which is used for
/// PowerShell Direct Windows Server Container connection and management.
/// </summary>
/// <param name="configurationName">Name of the configuration to use.</param>
internal static void RunServerMode(string configurationName)
{
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
if (IPCNamedPipeServer == null)
{
throw new RuntimeException(RemotingErrorIdStrings.NamedPipeServerCannotStart);
}
IPCNamedPipeServer.ConfigurationName = configurationName;
ManualResetEventSlim clientConnectionEnded = new ManualResetEventSlim(false);
IPCNamedPipeServer.ListenerEnded -= OnIPCNamedPipeServerEnded;
IPCNamedPipeServer.ListenerEnded += (sender, e) => clientConnectionEnded.Set();
// Wait for server to service a single client connection.
clientConnectionEnded.Wait();
clientConnectionEnded.Dispose();
IPCNamedPipeServerEnabled = false;
}
/// <summary>
/// Creates the process named pipe server object singleton and
/// starts the client listening thread.
/// </summary>
internal static void CreateIPCNamedPipeServerSingleton()
{
lock (s_syncObject)
{
if (!IPCNamedPipeServerEnabled) { return; }
if (IPCNamedPipeServer == null || IPCNamedPipeServer.IsDisposed)
{
try
{
try
{
IPCNamedPipeServer = CreateRemoteSessionNamedPipeServer();
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
IPCNamedPipeServer.ListenerEnded += OnIPCNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
IPCNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
IPCNamedPipeServer = null;
}
}
}
}
private static void CreateProcessExitHandler()
{
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
IPCNamedPipeServerEnabled = false;
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
if (namedPipeServer != null)
{
try
{
// Terminate the IPC thread.
namedPipeServer.Dispose();
}
catch (ObjectDisposedException)
{
// Ignore if object already disposed.
}
catch (Exception)
{
// Don't throw an exception on the app domain unload event thread.
}
}
};
}
private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener)
{
CreateIPCNamedPipeServerSingleton();
}
}
private static void OnCustomNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener && sender is RemoteSessionNamedPipeServer server)
{
CreateCustomNamedPipeServer(server.PipeName);
}
}
private static void ClientConnectionCallback(RemoteSessionNamedPipeServer pipeServer)
{
// Create server mediator object and begin remote session with client.
NamedPipeProcessMediator.Run(
string.Empty,
pipeServer);
}
#endregion
}
/// <summary>
/// Base class for RemoteSessionNamedPipeClient and ContainerSessionNamedPipeClient.
/// </summary>
internal class NamedPipeClientBase : IDisposable
{
#region Members
private NamedPipeClientStream _clientPipeStream;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#endregion
#region Properties
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Name of pipe.
/// </summary>
public string PipeName
{
get;
internal set;
}
#endregion
#region IDisposable
/// <summary>
/// Dispose object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (_clientPipeStream != null)
{
try { _clientPipeStream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Methods
/// <summary>
/// Connect to named pipe server. This is a blocking call until a
/// connection occurs or the timeout time has elapsed.
/// </summary>
/// <param name="timeout">Connection attempt timeout in milliseconds.</param>
public void Connect(
int timeout)
{
// Uses Native API to connect to pipe and return NamedPipeClientStream object.
_clientPipeStream = DoConnect(timeout);
// Create reader/writer streams.
TextReader = new StreamReader(_clientPipeStream);
TextWriter = new StreamWriter(_clientPipeStream);
TextWriter.AutoFlush = true;
_tracer.WriteMessage("NamedPipeClientBase", "Connect", Guid.Empty,
"Connection started on pipe: {0}", PipeName);
}
/// <summary>
/// Closes the named pipe.
/// </summary>
public void Close() => _clientPipeStream?.Dispose();
/// <summary>
/// Abort connection attempt.
/// </summary>
public virtual void AbortConnect()
{ }
/// <summary>
/// Begin connection attempt.
/// </summary>
protected virtual NamedPipeClientStream DoConnect(int timeout)
{
return null;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server.
/// </summary>
internal sealed class RemoteSessionNamedPipeClient : NamedPipeClientBase
{
#region Members
private volatile bool _connecting;
#endregion
#region Constructors
private RemoteSessionNamedPipeClient()
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process object.
/// </summary>
/// <param name="process">Target process object for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(System.Diagnostics.Process process, string appDomainName)
: this(NamedPipeUtils.CreateProcessPipeName(process, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process Id.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(int procId, string appDomainName)
: this(NamedPipeUtils.CreateProcessPipeName(procId, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on name argument.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeClient(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
PipeName = pipeName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="serverName"></param>
/// <param name="namespaceName"></param>
/// <param name="coreName"></param>
internal RemoteSessionNamedPipeClient(
string serverName,
string namespaceName,
string coreName)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
PipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
#endregion
#region Public Methods
/// <summary>
/// Abort connection attempt.
/// </summary>
public override void AbortConnect()
{
_connecting = false;
}
#endregion
#region Protected Methods
/// <summary>
/// Begin connection attempt.
/// </summary>
protected override NamedPipeClientStream DoConnect(int timeout)
{
// Repeatedly attempt connection to pipe until timeout expires.
int startTime = Environment.TickCount;
int elapsedTime = 0;
_connecting = true;
NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(
serverName: ".",
pipeName: PipeName,
direction: PipeDirection.InOut,
options: PipeOptions.Asynchronous);
namedPipeClientStream.ConnectAsync(timeout);
do
{
if (!namedPipeClientStream.IsConnected)
{
Thread.Sleep(100);
elapsedTime = unchecked(Environment.TickCount - startTime);
continue;
}
_connecting = false;
return namedPipeClientStream;
} while (_connecting && (elapsedTime < timeout));
_connecting = false;
throw new TimeoutException(RemotingErrorIdStrings.ConnectNamedPipeTimeout);
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server inside Windows Server container.
/// </summary>
internal sealed class ContainerSessionNamedPipeClient : NamedPipeClientBase
{
#region Constructors
/// <summary>
/// Constructor. Creates Named Pipe based on process Id, app domain name and container object root path.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
/// <param name="containerObRoot">Container OB root.</param>
public ContainerSessionNamedPipeClient(
int procId,
string appDomainName,
string containerObRoot)
{
if (string.IsNullOrEmpty(containerObRoot))
{
throw new PSArgumentNullException(nameof(containerObRoot));
}
//
// Named pipe inside Windows Server container is under different name space.
//
PipeName = containerObRoot + @"\Device\NamedPipe\" +
NamedPipeUtils.CreateProcessPipeName(procId, appDomainName);
}
#endregion
#region Protected Methods
/// <summary>
/// Helper method to open a named pipe via native APIs and return in
/// .Net NamedPipeClientStream wrapper object.
/// </summary>
protected override NamedPipeClientStream DoConnect(int timeout)
{
#if UNIX
// TODO: `CreateFileWithSafePipeHandle` pinvoke below clearly says
// that the code is only for Windows and we could exclude
// a lot of code from compilation on Unix.
throw new NotSupportedException(nameof(DoConnect));
#else
//
// WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly
// attempt connection to pipe server until timeout expires.
//
int startTime = Environment.TickCount;
int elapsedTime = 0;
nint handle;
do
{
// Get handle to pipe.
handle = Interop.Windows.CreateFileWithPipeHandle(
lpFileName: PipeName,
FileAccess.ReadWrite,
FileShare.None,
FileMode.Open,
Interop.Windows.FileAttributes.Overlapped);
if (handle == nint.Zero || handle == (nint)(-1))
{
int lastError = Marshal.GetLastPInvokeError();
if (lastError == Interop.Windows.ERROR_FILE_NOT_FOUND)
{
elapsedTime = unchecked(Environment.TickCount - startTime);
Thread.Sleep(100);
continue;
}
else
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotConnectContainerNamedPipe, lastError));
}
}
else
{
break;
}
} while (elapsedTime < timeout);
SafePipeHandle pipeHandle = null;
try
{
pipeHandle = new SafePipeHandle(handle, ownsHandle: true);
return new NamedPipeClientStream(
PipeDirection.InOut,
isAsync: true,
pipeHandle);
}
catch (Exception)
{
pipeHandle?.Dispose();
throw;
}
#endif
}
#endregion
}
}
|