forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWSManPlugin.cs
More file actions
1628 lines (1443 loc) · 67.7 KB
/
Copy pathWSManPlugin.cs
File metadata and controls
1628 lines (1443 loc) · 67.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
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
// ----------------------------------------------------------------------
//
// Microsoft Windows NT
// Copyright (C) Microsoft Corporation, 2007.
//
// Contents: Entry points for managed PowerShell plugin worker used to
// host powershell in a WSMan service.
// ----------------------------------------------------------------------
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Collections.Generic;
using Microsoft.Win32.SafeHandles;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Remoting.WSMan;
using System.Management.Automation.Tracing;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Consolidation of constants for uniformity.
/// </summary>
internal static class WSManPluginConstants
{
internal const int ExitCodeSuccess = 0x00000000;
internal const int ExitCodeFailure = 0x00000001;
internal const string CtrlCSignal = "powershell/signal/crtl_c";
// The following are the only supported streams in PowerShell remoting.
// see WSManNativeApi.cs. These are duplicated here to save on
// Marshalling time.
internal const string SupportedInputStream = "stdin";
internal const string SupportedOutputStream = "stdout";
internal const string SupportedPromptResponseStream = "pr";
internal const string PowerShellStartupProtocolVersionName = "protocolversion";
internal const string PowerShellStartupProtocolVersionValue = "2.0";
internal const string PowerShellOptionPrefix = "PS_";
internal const int WSManPluginParamsGetRequestedLocale = 5;
internal const int WSManPluginParamsGetRequestedDataLocale = 6;
}
/// <summary>
/// Definitions of HRESULT error codes that are passed to the client.
/// 0x8054.... means that it is a PowerShell HRESULT. The PowerShell facility
/// is 84 (0x54).
/// </summary>
internal enum WSManPluginErrorCodes : int
{
NullPluginContext = -2141976624, // 0x805407D0
PluginContextNotFound = -2141976623, // 0x805407D1
NullInvalidInput = -2141975624, // 0x80540BB8
NullInvalidStreamSets = -2141975623, // 0x80540BB9
SessionCreationFailed = -2141975622, // 0x80540BBA
NullShellContext = -2141975621, // 0x80540BBB
InvalidShellContext = -2141975620, // 0x80540BBC
InvalidCommandContext = -2141975619, // 0x80540BBD
InvalidInputStream = -2141975618, // 0x80540BBE
InvalidInputDatatype = -2141975617, // 0x80540BBF
InvalidOutputStream = -2141975616, // 0x80540BC0
InvalidSenderDetails = -2141975615, // 0x80540BC1
ShutdownRegistrationFailed = -2141975614, // 0x80540BC2
ReportContextFailed = -2141975613, // 0x80540BC3
InvalidArgSet = -2141975612, // 0x80540BC4
ProtocolVersionNotMatch = -2141975611, // 0x80540BC5
OptionNotUnderstood = -2141975610, // 0x80540BC6
ProtocolVersionNotFound = -2141975609, // 0x80540BC7
ManagedException = -2141974624, // 0x80540FA0
PluginOperationClose = -2141974623, // 0x80540FA1
PluginConnectNoNegotiationData = -2141974622, // 0x80540FA2
PluginConnectOperationFailed = -2141974621, // 0x80540FA3
NoError = 0,
OutOfMemory = -2147024882 // 0x8007000E
}
/// <summary>
/// class that holds plugin + shell context information used to handle
/// shutdown notifications.
///
/// Explicit destruction and release of the IntPtrs is not required because
/// their lifetime is managed by WinRM.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class WSManPluginOperationShutdownContext // TODO: Rename to OperationShutdownContext when removing the MC++ module.
{
#region Internal Members
internal IntPtr pluginContext;
internal IntPtr shellContext;
internal IntPtr commandContext;
internal bool isReceiveOperation;
internal bool isShuttingDown;
#endregion
#region Constructors
internal WSManPluginOperationShutdownContext(
IntPtr plgContext,
IntPtr shContext,
IntPtr cmdContext,
bool isRcvOp)
{
pluginContext = plgContext;
shellContext = shContext;
commandContext = cmdContext;
isReceiveOperation = isRcvOp;
isShuttingDown = false;
}
#endregion
}
/// <summary>
/// Represents the logical grouping of all actions required to handle the
/// lifecycle of shell sessions through the WinRM plugin.
/// </summary>
internal class WSManPluginInstance
{
#region Private Members
private Dictionary<IntPtr, WSManPluginShellSession> _activeShellSessions;
private object _syncObject;
private static Dictionary<IntPtr, WSManPluginInstance> s_activePlugins = new Dictionary<IntPtr, WSManPluginInstance>();
/// <summary>
/// Enables dependency injection after the static constructor is called.
/// This may be overridden in unit tests to enable different behavoir.
/// It is static because static instances of this class use the facade. Otherwise,
/// it would be passed in via a parameterized constructor.
/// </summary>
internal static IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade();
#endregion
#region Constructor and Destructor
internal WSManPluginInstance()
{
_activeShellSessions = new Dictionary<IntPtr, WSManPluginShellSession>();
_syncObject = new System.Object();
}
/// <summary>
/// static constructor to listen to unhandled exceptions
/// from the AppDomain and log the errors
/// Note: It is not necessary to instantiate IWSManNativeApi here because it is not used.
/// </summary>
static WSManPluginInstance()
{
// NOTE - the order is important here:
// because handler from WindowsErrorReporting is going to terminate the proces
// we want it to fire last
#if !CORECLR
// Register our remoting handler for crashes
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(WSManPluginInstance.UnhandledExceptionHandler);
// Register our Watson handler for crash reports in server mode
System.Management.Automation.WindowsErrorReporting.RegisterWindowsErrorReporting(true);
#endif
}
#endregion
/// <summary>
/// Create a new shell in the plugin context.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="extraInfo"></param>
/// <param name="startupInfo"></param>
/// <param name="inboundShellInformation"></param>
internal void CreateShell(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
string extraInfo,
WSManNativeApi.WSManShellStartupInfo_UnToMan startupInfo,
WSManNativeApi.WSManData_UnToMan inboundShellInformation)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"WSManPluginShell"),
String.Empty);
return;
}
if ((null == requestDetails.senderDetails) ||
(null == requestDetails.operationInfo))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"WSManPluginShell"));
return;
}
if (null == startupInfo)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"startupInfo",
"WSManPluginShell"));
return;
}
if ((0 == startupInfo.inputStreamSet.streamIDsCount) || (0 == startupInfo.outputStreamSet.streamIDsCount))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidStreamSets,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidStreamSet,
WSManPluginConstants.SupportedInputStream,
WSManPluginConstants.SupportedOutputStream));
return;
}
if (String.IsNullOrEmpty(extraInfo))
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullInvalidInput,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"extraInfo",
"WSManPluginShell"));
return;
}
WSManPluginInstance.SetThreadProperties(requestDetails);
// check if protocolversion option is honored
if (!EnsureOptionsComply(requestDetails))
{
return;
}
int result = WSManPluginConstants.ExitCodeSuccess;
WSManPluginShellSession mgdShellSession;
WSManPluginOperationShutdownContext context;
System.Byte[] convertedBase64 = null;
try
{
PSSenderInfo senderInfo = GetPSSenderInfo(requestDetails.senderDetails);
// inbound shell information is already verified by pwrshplugin.dll.. so no need
// to verify here.
WSManPluginServerTransportManager serverTransportMgr;
if (Platform.IsWindows)
{
serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, new PSRemotingCryptoHelperServer());
}
else
{
serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, null);
}
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateRemoteSession,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
requestDetails.ToString(), senderInfo.UserInfo.Identity.Name, requestDetails.resourceUri);
ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo,
requestDetails.resourceUri,
extraInfo,
serverTransportMgr);
if (null == remoteShellSession)
{
WSManPluginInstance.ReportWSManOperationComplete(
requestDetails,
WSManPluginErrorCodes.SessionCreationFailed);
return;
}
context = new WSManPluginOperationShutdownContext(pluginContext, requestDetails.unmanagedHandle, IntPtr.Zero, false);
if (null == context)
{
ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory);
return;
}
// Create a shell session wrapper to track and service future interacations.
mgdShellSession = new WSManPluginShellSession(requestDetails, serverTransportMgr, remoteShellSession, context);
AddToActiveShellSessions(mgdShellSession);
mgdShellSession.SessionClosed += new EventHandler<EventArgs>(HandleShellSessionClosed);
if (null != inboundShellInformation)
{
if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type)
{
// only text data is supported
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidInputDatatype,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidInputDataType,
"WSMAN_DATA_TYPE_TEXT"));
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
else
{
convertedBase64 = ServerOperationHelpers.ExtractEncodedXmlElement(
inboundShellInformation.Text,
WSManNativeApi.PS_CREATION_XML_TAG);
}
}
// now report the shell context to WSMan.
PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
requestDetails.ToString(), requestDetails.ToString());
result = wsmanPinvokeStatic.WSManPluginReportContext(requestDetails.unmanagedHandle, 0, requestDetails.unmanagedHandle);
if (WSManPluginConstants.ExitCodeSuccess != result)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ReportContextFailed,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginReportContextFailed));
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
}
catch (System.Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(PSEventId.TransportError,
PSOpcode.Connect, PSTask.None, PSKeyword.UseAlwaysOperational, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000",
Convert.ToString(WSManPluginErrorCodes.ManagedException, CultureInfo.InvariantCulture), e.Message, e.StackTrace);
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.ManagedException,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginManagedException,
e.Message));
return;
}
bool isRegisterWaitForSingleObjectSucceeded = true;
//always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen
lock (mgdShellSession.shellSyncObject)
{
mgdShellSession.registeredShutdownNotification = 1;
// Wrap the provided handle so it can be passed to the registration function
EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
if (Platform.IsWindows)
{
SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM
ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle);
}
else
{
//On non-windows platforms the shutdown notification is done through a callback instead of a windows event handle.
//Register the callback and this will then signal the event. Note, the gch object is deleted in the shell shutdown
//notification that will always come in to shut down the operation.
GCHandle gch = GCHandle.Alloc(eventWaitHandle);
IntPtr p = GCHandle.ToIntPtr(gch);
wsmanPinvokeStatic.WSManPluginRegisterShutdownCallback(
requestDetails.unmanagedHandle,
WSManPluginManagedEntryWrapper.workerPtrs.UnmanagedStruct.wsManPluginShutdownCallbackNative,
p);
}
mgdShellSession.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
eventWaitHandle,
new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
context,
-1, // INFINITE
true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
if (null == mgdShellSession.registeredShutDownWaitHandle)
{
isRegisterWaitForSingleObjectSucceeded = false;
}
}
if (!isRegisterWaitForSingleObjectSucceeded)
{
mgdShellSession.registeredShutdownNotification = 0;
WSManPluginInstance.ReportWSManOperationComplete(
requestDetails,
WSManPluginErrorCodes.ShutdownRegistrationFailed);
DeleteFromActiveShellSessions(requestDetails.unmanagedHandle);
return;
}
try
{
if (convertedBase64 != null)
{
mgdShellSession.SendOneItemToSessionHelper(convertedBase64, WSManPluginConstants.SupportedInputStream);
}
}
catch (System.Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(PSEventId.TransportError,
PSOpcode.Connect, PSTask.None, PSKeyword.UseAlwaysOperational, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000",
Convert.ToString(WSManPluginErrorCodes.ManagedException, CultureInfo.InvariantCulture), e.Message, e.StackTrace);
if (Interlocked.Exchange(ref mgdShellSession.registeredShutdownNotification, 0) == 1)
{
// unregister callback.. wait for any ongoing callbacks to complete.. nothing much we could do if this fails
bool ignore = mgdShellSession.registeredShutDownWaitHandle.Unregister(null);
mgdShellSession.registeredShutDownWaitHandle = null;
//this will called OperationComplete
PerformCloseOperation(context);
}
return;
}
return;
}
/// <summary>
/// This gets called on a thread pool thread once Shutdown wait handle is notified.
/// </summary>
/// <param name="context"></param>
internal void CloseShellOperation(
WSManPluginOperationShutdownContext context)
{
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)context.shellContext).ToString(),
((IntPtr)context.commandContext).ToString(),
context.isReceiveOperation.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext);
if (null == mgdShellSession)
{
// this should never be the case. this will protect the service.
//Dbg.Assert(false, "context.shellContext not matched");
return;
}
SetThreadProperties(mgdShellSession.creationRequestDetails);
// update the internal data store only if this is not receive operation.
if (!context.isReceiveOperation)
{
DeleteFromActiveShellSessions(context.shellContext);
}
string errorMsg = StringUtil.Format(RemotingErrorIdStrings.WSManPluginOperationClose);
System.Exception reasonForClose = new System.Exception(errorMsg);
mgdShellSession.CloseOperation(context, reasonForClose);
}
internal void CloseCommandOperation(
WSManPluginOperationShutdownContext context)
{
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
context.shellContext.ToString(),
context.commandContext.ToString(),
context.isReceiveOperation.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext);
if (null == mgdShellSession)
{
// this should never be the case. this will protect the service.
//Dbg.Assert(false, "context.shellContext not matched");
return;
}
SetThreadProperties(mgdShellSession.creationRequestDetails);
mgdShellSession.CloseCommandOperation(context);
}
/// <summary>
/// adds shell session to activeShellSessions store and returns the id
/// at which the session is added.
/// </summary>
/// <param name="newShellSession"></param>
private void AddToActiveShellSessions(
WSManPluginShellSession newShellSession)
{
int count = -1;
lock (_syncObject)
{
IntPtr key = newShellSession.creationRequestDetails.unmanagedHandle;
Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided");
if (!_activeShellSessions.ContainsKey(key))
{
_activeShellSessions.Add(key, newShellSession);
// trigger an event outside the lock
count = _activeShellSessions.Count;
}
}
if (-1 != count)
{
// Raise session count changed event
WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count));
}
}
/// <summary>
/// Retrieves a WSManPluginShellSession if matched.
/// </summary>
/// <param name="key">Shell context (WSManPluginRequest.unmanagedHandle)</param>
/// <returns>null WSManPluginShellSession if not matched. The object if matched.</returns>
private WSManPluginShellSession GetFromActiveShellSessions(
IntPtr key)
{
lock (_syncObject)
{
WSManPluginShellSession result;
_activeShellSessions.TryGetValue(key, out result);
return result;
}
}
/// <summary>
/// Removes a WSManPluginShellSession from tracking.
/// </summary>
/// <param name="keyToDelete">IntPtr of a WSManPluginRequest structure.</param>
private void DeleteFromActiveShellSessions(
IntPtr keyToDelete)
{
int count = -1;
lock (_syncObject)
{
if (_activeShellSessions.Remove(keyToDelete))
{
// trigger an event outside the lock
count = _activeShellSessions.Count;
}
}
if (-1 != count)
{
// Raise session count changed event
WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count));
}
}
/// <summary>
/// Triggers a shell close from an event handler.
/// </summary>
/// <param name="source">Shell context</param>
/// <param name="e"></param>
private void HandleShellSessionClosed(
Object source,
EventArgs e)
{
DeleteFromActiveShellSessions((IntPtr)source);
}
/// <summary>
/// Helper function to validate incoming values
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="shellContext"></param>
/// <param name="inputFunctionName"></param>
/// <returns></returns>
private bool validateIncomingContexts(
WSManNativeApi.WSManPluginRequest requestDetails,
IntPtr shellContext,
string inputFunctionName)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
inputFunctionName),
String.Empty);
return false;
}
if (IntPtr.Zero == shellContext)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.NullShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullShellContext,
"ShellContext",
inputFunctionName));
return false;
}
return true;
}
/// <summary>
/// Create a new command in the shell context.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandLine"></param>
/// <param name="arguments"></param>
internal void CreateCommand(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
string commandLine,
WSManNativeApi.WSManCommandArgSet arguments)
{
if (!validateIncomingContexts(requestDetails, shellContext, "WSManRunShellCommandEx"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateCommandSession,
PSOpcode.Connect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(), requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
mgdShellSession.CreateCommand(pluginContext, requestDetails, flags, commandLine, arguments);
}
internal void StopCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
IntPtr shellContext,
IntPtr commandContext)
{
if (null == requestDetails)
{
// Nothing can be done because requestDetails are required to report operation complete
PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
"null",
Convert.ToString(WSManPluginErrorCodes.NullInvalidInput, CultureInfo.InvariantCulture),
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginNullInvalidInput,
"requestDetails",
"StopCommand"),
String.Empty);
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerStopCommand,
PSOpcode.Disconnect, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(),
((IntPtr)commandContext).ToString(),
requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
WSManPluginCommandSession mgdCommandSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCommandSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCommandSession.Stop(requestDetails);
}
internal void Shutdown()
{
PSEtwLog.LogAnalyticInformational(PSEventId.WSManPluginShutdown,
PSOpcode.ShuttingDown, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic);
// all active shells should be closed at this point
Dbg.Assert(_activeShellSessions.Count == 0, "All active shells should be closed");
// raise shutting down notification
WSManServerChannelEvents.RaiseShuttingDownEvent();
}
/// <summary>
/// Connect
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="inboundConnectInformation"></param>
internal void ConnectShellOrCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
WSManNativeApi.WSManData_UnToMan inboundConnectInformation)
{
if (!validateIncomingContexts(requestDetails, shellContext, "ConnectShellOrCommand"))
{
return;
}
//TODO... What does this mean from a new client that has specified diff locale from original client?
SetThreadProperties(requestDetails);
//TODO.. Add new ETW events and log
/*etwTracer.AnalyticChannel.WriteInformation(PSEventId.ServerReceivedData,
PSOpcode.Open, PSTask.None,
((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), ((IntPtr)requestDetails).ToString());*/
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext));
return;
}
if (IntPtr.Zero == commandContext)
{
mgdShellSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation);
return;
}
// this connect is on a commad
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCmdSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation);
}
/// <summary>
/// Send data to the shell / command specified.
/// </summary>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="stream"></param>
/// <param name="inboundData"></param>
internal void SendOneItemToShellOrCommand(
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
string stream,
WSManNativeApi.WSManData_UnToMan inboundData)
{
if (!validateIncomingContexts(requestDetails, shellContext, "SendOneItemToShellOrCommand"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerReceivedData,
PSOpcode.Open, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext)
);
return;
}
if (IntPtr.Zero == commandContext)
{
// the data is destined for shell (runspace) session. so let shell handle it
mgdShellSession.SendOneItemToSession(requestDetails, flags, stream, inboundData);
return;
}
// the data is destined for command.
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
mgdCmdSession.SendOneItemToSession(requestDetails, flags, stream, inboundData);
}
/// <summary>
/// unlock the shell / command specified so that the shell / command
/// starts sending data to the client.
/// </summary>
/// <param name="pluginContext"></param>
/// <param name="requestDetails"></param>
/// <param name="flags"></param>
/// <param name="shellContext"></param>
/// <param name="commandContext"></param>
/// <param name="streamSet"></param>
internal void EnableShellOrCommandToSendDataToClient(
IntPtr pluginContext,
WSManNativeApi.WSManPluginRequest requestDetails,
int flags,
IntPtr shellContext,
IntPtr commandContext,
WSManNativeApi.WSManStreamIDSet_UnToMan streamSet)
{
if (!validateIncomingContexts(requestDetails, shellContext, "EnableShellOrCommandToSendDataToClient"))
{
return;
}
SetThreadProperties(requestDetails);
PSEtwLog.LogAnalyticInformational(PSEventId.ServerClientReceiveRequest,
PSOpcode.Open, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
((IntPtr)shellContext).ToString(),
((IntPtr)commandContext).ToString(),
requestDetails.ToString());
WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext);
if (null == mgdShellSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidShellContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidShellContext)
);
return;
}
WSManPluginOperationShutdownContext ctxtToReport = new WSManPluginOperationShutdownContext(pluginContext, shellContext, IntPtr.Zero, true);
if (null == ctxtToReport)
{
ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory);
return;
}
if (IntPtr.Zero == commandContext)
{
// the instruction is destined for shell (runspace) session. so let shell handle it
if (mgdShellSession.EnableSessionToSendDataToClient(requestDetails, flags, streamSet, ctxtToReport))
{
return;
}
}
else
{
// the instruction is destined for command
ctxtToReport.commandContext = commandContext;
WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext);
if (null == mgdCmdSession)
{
ReportOperationComplete(
requestDetails,
WSManPluginErrorCodes.InvalidCommandContext,
StringUtil.Format(
RemotingErrorIdStrings.WSManPluginInvalidCommandContext));
return;
}
if (mgdCmdSession.EnableSessionToSendDataToClient(requestDetails, flags, streamSet, ctxtToReport))
{
return;
}
}
}
/// <summary>
/// used to create PSPrincipal object from senderDetails struct.
/// </summary>
/// <param name="senderDetails"></param>
/// <returns></returns>
private PSSenderInfo GetPSSenderInfo(
WSManNativeApi.WSManSenderDetails senderDetails)
{
// senderDetails will not be null.
Dbg.Assert(null != senderDetails, "senderDetails cannot be null");
// Construct PSIdentity
PSCertificateDetails psCertDetails = null;
// Construct Certificate Details
if (null != senderDetails.certificateDetails)
{
psCertDetails = new PSCertificateDetails(
senderDetails.certificateDetails.subject,
senderDetails.certificateDetails.issuerName,
senderDetails.certificateDetails.issuerThumbprint);
}
// Construct PSPrincipal
PSIdentity psIdentity = new PSIdentity(senderDetails.authenticationMechanism, true, senderDetails.senderName, psCertDetails);
// For Virtual and RunAs accounts WSMan specifies the client token via an environment variable and
// senderDetails.clientToken should not be used.
IntPtr clientToken = GetRunAsClientToken();
clientToken = (clientToken != IntPtr.Zero) ? clientToken : senderDetails.clientToken;
WindowsIdentity windowsIdentity = null;
if (clientToken != IntPtr.Zero)
{
try
{
windowsIdentity = new WindowsIdentity(clientToken, senderDetails.authenticationMechanism);
}
// Suppress exceptions..So windowsIdentity = null in these cases
catch (ArgumentException)
{
// userToken is 0.
// -or-
// userToken is duplicated and invalid for impersonation.
}
catch (System.Security.SecurityException)
{
// The caller does not have the correct permissions.
// -or-