forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInitialSessionStateProvider.cs
More file actions
2875 lines (2539 loc) · 122 KB
/
Copy pathInitialSessionStateProvider.cs
File metadata and controls
2875 lines (2539 loc) · 122 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
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation.Tracing;
using Microsoft.PowerShell.Commands;
using Microsoft.Win32;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This struct is used to represent contents from configuration xml. The
/// XML is passed to plugins by WSMan API.
/// This helper does not validate XML content as it is already validated
/// by WSMan.
/// </summary>
internal class ConfigurationDataFromXML
{
#region Config XML Constants
internal const string INITPARAMETERSTOKEN = "InitializationParameters";
internal const string PARAMTOKEN = "Param";
internal const string NAMETOKEN = "Name";
internal const string VALUETOKEN = "Value";
internal const string APPBASETOKEN = "applicationbase";
internal const string ASSEMBLYTOKEN = "assemblyname";
internal const string SHELLCONFIGTYPETOKEN = "pssessionconfigurationtypename";
internal const string STARTUPSCRIPTTOKEN = "startupscript";
internal const string MAXRCVDOBJSIZETOKEN = "psmaximumreceivedobjectsizemb";
internal const string MAXRCVDOBJSIZETOKEN_CamelCase = "PSMaximumReceivedObjectSizeMB";
internal const string MAXRCVDCMDSIZETOKEN = "psmaximumreceiveddatasizepercommandmb";
internal const string MAXRCVDCMDSIZETOKEN_CamelCase = "PSMaximumReceivedDataSizePerCommandMB";
internal const string THREADOPTIONSTOKEN = "pssessionthreadoptions";
#if !CORECLR // No ApartmentState In CoreCLR
internal const string THREADAPTSTATETOKEN = "pssessionthreadapartmentstate";
#endif
internal const string SESSIONCONFIGTOKEN = "sessionconfigurationdata";
internal const string PSVERSIONTOKEN = "PSVersion";
internal const string MAXPSVERSIONTOKEN = "MaxPSVersion";
internal const string MODULESTOIMPORT = "ModulesToImport";
internal const string HOSTMODE = "hostmode";
internal const string ENDPOINTCONFIGURATIONTYPE = "sessiontype";
internal const string WORKFLOWCOREASSEMBLY = "Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL";
internal const string WORKFLOWCORETYPENAME = "Microsoft.PowerShell.Workflow.PSWorkflowSessionConfiguration";
internal const string PSWORKFLOWMODULE = "%windir%\\system32\\windowspowershell\\v1.0\\Modules\\PSWorkflow";
internal const string CONFIGFILEPATH = "configfilepath";
internal const string CONFIGFILEPATH_CamelCase = "ConfigFilePath";
#endregion
internal string StartupScript;
// this field is used only by an Out-Of-Process (IPC) server process
internal string InitializationScriptForOutOfProcessRunspace;
internal string ApplicationBase;
internal string AssemblyName;
internal string EndPointConfigurationTypeName;
internal Type EndPointConfigurationType;
internal Nullable<int> MaxReceivedObjectSizeMB;
internal Nullable<int> MaxReceivedCommandSizeMB;
// Used to set properties on the RunspacePool created for this shell.
internal Nullable<PSThreadOptions> ShellThreadOptions;
#if !CORECLR // No ApartmentState In CoreCLR
internal Nullable<System.Threading.ApartmentState> ShellThreadApartmentState;
#endif
internal PSSessionConfigurationData SessionConfigurationData;
internal string ConfigFilePath;
/// <summary>
/// Using optionName and optionValue updates the current object
/// </summary>
/// <param name="optionName"></param>
/// <param name="optionValue"></param>
/// <exception cref="ArgumentException">
/// 1. "optionName" is not valid in "InitializationParameters" section.
/// 2. "startupscript" must specify a PowerShell script file that ends with extension ".ps1".
/// </exception>
private void Update(string optionName, string optionValue)
{
switch (optionName.ToLowerInvariant())
{
case APPBASETOKEN:
AssertValueNotAssigned(APPBASETOKEN, ApplicationBase);
// this is a folder pointing to application base of the plugin shell
// allow the folder path to use environment variables.
ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue);
break;
case ASSEMBLYTOKEN:
AssertValueNotAssigned(ASSEMBLYTOKEN, AssemblyName);
AssemblyName = optionValue;
break;
case SHELLCONFIGTYPETOKEN:
AssertValueNotAssigned(SHELLCONFIGTYPETOKEN, EndPointConfigurationTypeName);
EndPointConfigurationTypeName = optionValue;
break;
case STARTUPSCRIPTTOKEN:
AssertValueNotAssigned(STARTUPSCRIPTTOKEN, StartupScript);
if (!optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
throw PSTraceSource.NewArgumentException(STARTUPSCRIPTTOKEN,
RemotingErrorIdStrings.StartupScriptNotCorrect,
STARTUPSCRIPTTOKEN);
}
// allow the script file to exist in any path..and support
// environment variable expansion.
StartupScript = Environment.ExpandEnvironmentVariables(optionValue);
break;
case MAXRCVDOBJSIZETOKEN:
AssertValueNotAssigned(MAXRCVDOBJSIZETOKEN, MaxReceivedObjectSizeMB);
MaxReceivedObjectSizeMB = GetIntValueInBytes(optionValue);
break;
case MAXRCVDCMDSIZETOKEN:
AssertValueNotAssigned(MAXRCVDCMDSIZETOKEN, MaxReceivedCommandSizeMB);
MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue);
break;
case THREADOPTIONSTOKEN:
AssertValueNotAssigned(THREADOPTIONSTOKEN, ShellThreadOptions);
ShellThreadOptions = (PSThreadOptions)LanguagePrimitives.ConvertTo(
optionValue, typeof(PSThreadOptions), CultureInfo.InvariantCulture);
break;
#if !CORECLR // No ApartmentState In CoreCLR
case THREADAPTSTATETOKEN:
AssertValueNotAssigned(THREADAPTSTATETOKEN, ShellThreadApartmentState);
ShellThreadApartmentState = (System.Threading.ApartmentState)LanguagePrimitives.ConvertTo(
optionValue, typeof(System.Threading.ApartmentState), CultureInfo.InvariantCulture);
break;
#endif
case SESSIONCONFIGTOKEN:
{
AssertValueNotAssigned(SESSIONCONFIGTOKEN, SessionConfigurationData);
SessionConfigurationData = PSSessionConfigurationData.Create(optionValue);
}
break;
case CONFIGFILEPATH:
{
AssertValueNotAssigned(CONFIGFILEPATH, ConfigFilePath);
ConfigFilePath = optionValue.ToString();
}
break;
default:
// we dont need to evaluate PSVersion and other custom authz
// related tokens
break;
}
}
/// <summary>
/// Checks if the originalValue is empty. If not throws an exception
/// </summary>
/// <param name="optionName"></param>
/// <param name="originalValue"></param>
/// <exception cref="ArgumentException">
/// 1. "optionName" is already defined
/// </exception>
private void AssertValueNotAssigned(string optionName, object originalValue)
{
if (originalValue != null)
{
throw PSTraceSource.NewArgumentException(optionName,
RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN);
}
}
/// <summary>
/// Converts the value specified by <paramref name="optionValue"/> to int.
/// Multiplies the value by 1MB (1024*1024) to get the number in bytes.
/// </summary>
/// <param name="optionValueInMB"></param>
/// <returns>
/// If value is specified, specified value as int . otherwise null.
/// </returns>
private static Nullable<int> GetIntValueInBytes(string optionValueInMB)
{
Nullable<int> result = null;
try
{
double variableValue = (double)LanguagePrimitives.ConvertTo(optionValueInMB,
typeof(double), System.Globalization.CultureInfo.InvariantCulture);
result = unchecked((int)(variableValue * 1024 * 1024)); // Multiply by 1MB
}
catch (InvalidCastException)
{
}
if (result < 0)
{
result = null;
}
return result;
}
/// <summary>
/// Creates the struct from initialization parameters xml.
/// </summary>
/// <param name="initializationParameters">
/// Initialization Parameters xml passed by WSMan API. This data is read from the config
/// xml and is in the following format:
/// </param>
/// <returns></returns>
/// <exception cref="ArgumentException">
/// 1. "optionName" is already defined
/// </exception>
/*
<InitializationParameters>
<Param Name="PSVersion" Value="2.0" />
<Param Name="ApplicationBase" Value="<folder path>" />
...
</InitializationParameters>
*/
/* The following extensions have been added in V3 providing the user
* the ability to pass data to the session configuration for initialization
*
<Param Name="SessionConfigurationData" Value="<SessionConfigurationData with XML escaping>" />
*
* The session configuration data blob can be defined as under
<SessionConfigurationData>
<Param Name="ModulesToImport" Value="<folder path>" />
<Param Name="PrivateData" />
<PrivateData>
...
</PrivateData>
</Param>
</SessionConfigurationData>
*/
internal static ConfigurationDataFromXML Create(string initializationParameters)
{
ConfigurationDataFromXML result = new ConfigurationDataFromXML();
if (string.IsNullOrEmpty(initializationParameters))
{
return result;
}
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CheckCharacters = false;
readerSettings.IgnoreComments = true;
readerSettings.IgnoreProcessingInstructions = true;
readerSettings.MaxCharactersInDocument = 10000;
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
#if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR
readerSettings.XmlResolver = null;
#endif
using (XmlReader reader = XmlReader.Create(new StringReader(initializationParameters), readerSettings))
{
// read the header <InitializationParameters>
if (reader.ReadToFollowing(INITPARAMETERSTOKEN))
{
bool isParamFound = reader.ReadToDescendant(PARAMTOKEN);
while (isParamFound)
{
if (!reader.MoveToAttribute(NAMETOKEN))
{
throw PSTraceSource.NewArgumentException(initializationParameters,
RemotingErrorIdStrings.NoAttributesFoundForParamElement,
NAMETOKEN, VALUETOKEN, PARAMTOKEN);
}
string optionName = reader.Value;
if (!reader.MoveToAttribute(VALUETOKEN))
{
throw PSTraceSource.NewArgumentException(initializationParameters,
RemotingErrorIdStrings.NoAttributesFoundForParamElement,
NAMETOKEN, VALUETOKEN, PARAMTOKEN);
}
string optionValue = reader.Value;
result.Update(optionName, optionValue);
// move to next Param token.
isParamFound = reader.ReadToFollowing(PARAMTOKEN);
}
}
}
// assign defaults after parsing the xml content.
if (null == result.MaxReceivedObjectSizeMB)
{
result.MaxReceivedObjectSizeMB = BaseTransportManager.MaximumReceivedObjectSize;
}
if (null == result.MaxReceivedCommandSizeMB)
{
result.MaxReceivedCommandSizeMB = BaseTransportManager.MaximumReceivedDataSize;
}
return result;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="ArgumentException">
/// 1. Unable to load type "{0}" specified in "InitializationParameters" section.
/// </exception>
internal PSSessionConfiguration CreateEndPointConfigurationInstance()
{
try
{
return (PSSessionConfiguration)Activator.CreateInstance(EndPointConfigurationType);
}
catch (TypeLoadException)
{
}
catch (ArgumentException)
{
}
catch (MissingMethodException)
{
}
catch (InvalidCastException)
{
}
catch (TargetInvocationException)
{
}
// if we are here, that means we are unble to load the type specified
// in the config xml.. notify the same.
throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType,
EndPointConfigurationTypeName, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
}
/// <summary>
/// InitialSessionStateProvider is used by 3rd parties to provide shell configurtion
/// on the remote server.
/// </summary>
public abstract class PSSessionConfiguration : IDisposable
{
#region tracer
/// <summary>
/// Tracer for Server Remote session
/// </summary>
[TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession");
#endregion tracer
#region public interfaces
/// <summary>
/// Derived classes must override this to supply an InitialSesionState
/// to be used to construct a Runspace for the user
/// </summary>
/// <param name="senderInfo">
/// User Identity for which this information is requested
/// </param>
/// <returns></returns>
public abstract InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo);
/// <summary>
///
/// </summary>
/// <param name="sessionConfigurationData"></param>
/// <param name="senderInfo"></param>
/// <param name="configProviderId"></param>
/// <returns></returns>
public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData,
PSSenderInfo senderInfo, string configProviderId)
{
throw new NotImplementedException();
}
/// <summary>
/// Maximum size (in bytes) of a deserialized object received from a remote machine.
/// If null, then the size is unlimited. Default is 10MB.
/// </summary>
/// <param name="senderInfo">
/// User Identity for which this information is requested
/// </param>
/// <returns></returns>
public virtual Nullable<int> GetMaximumReceivedObjectSize(PSSenderInfo senderInfo)
{
return BaseTransportManager.MaximumReceivedObjectSize;
}
/// <summary>
/// Total data (in bytes) that can be received from a remote machine
/// targeted towards a command. If null, then the size is unlimited.
/// Default is 50MB.
/// </summary>
/// <param name="senderInfo">
/// User Identity for which this information is requested
/// </param>
/// <returns></returns>
public virtual Nullable<int> GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo)
{
return BaseTransportManager.MaximumReceivedDataSize;
}
/// <summary>
/// Derived classes can override this method to provide application private data
/// that is going to be sent to the client and exposed via
/// <see cref="System.Management.Automation.Runspaces.PSSession.ApplicationPrivateData"/>,
/// <see cref="System.Management.Automation.Runspaces.Runspace.GetApplicationPrivateData"/> and
/// <see cref="System.Management.Automation.Runspaces.RunspacePool.GetApplicationPrivateData"/>
/// </summary>
/// <param name="senderInfo">
/// User Identity for which this information is requested
/// </param>
/// <returns>Application private data or <c>null</c></returns>
public virtual PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
{
return null;
}
#endregion
#region IDisposable Overrides
/// <summary>
/// Disose this configuration object. This will be called when a Runspace/RunspacePool
/// created using InitialSessionState from this object is Closed.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
/// <param name="isDisposing"></param>
protected virtual void Dispose(bool isDisposing)
{
}
#endregion
#region GetInitialSessionState from 3rd party shell ids
/// <summary>
///
/// </summary>
/// <param name="shellId"></param>
/// <param name="initializationParameters">
/// Initialization Parameters xml passed by WSMan API. This data is read from the config
/// xml and is in the following format:
/// </param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">
/// 1. Non existent InitialSessionState provider for the shellID
/// </exception>
/*
<InitializationParameters>
<Param Name="PSVersion" Value="2.0" />
<Param Name="ApplicationBase" Value="<folder path>" />
...
</InitializationParameters>
*/
internal static ConfigurationDataFromXML LoadEndPointConfiguration(string shellId,
string initializationParameters)
{
ConfigurationDataFromXML configData = null;
if (!s_ssnStateProviders.ContainsKey(initializationParameters))
{
LoadRSConfigProvider(shellId, initializationParameters);
}
lock (s_syncObject)
{
if (!s_ssnStateProviders.TryGetValue(initializationParameters, out configData))
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NonExistentInitialSessionStateProvider, shellId);
}
}
return configData;
}
private static void LoadRSConfigProvider(string shellId, string initializationParameters)
{
ConfigurationDataFromXML configData = ConfigurationDataFromXML.Create(initializationParameters);
Type endPointConfigType = LoadAndAnalyzeAssembly(shellId,
configData.ApplicationBase,
configData.AssemblyName,
configData.EndPointConfigurationTypeName);
Dbg.Assert(endPointConfigType != null, "EndPointConfiguration type cannot be null");
configData.EndPointConfigurationType = endPointConfigType;
lock (s_syncObject)
{
if (!s_ssnStateProviders.ContainsKey(initializationParameters))
{
s_ssnStateProviders.Add(initializationParameters, configData);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="shellId">
/// shellId for which the assembly is getting loaded
/// </param>
/// <param name="applicationBase"></param>
/// <param name="assemblyName"></param>
/// <param name="typeToLoad">
/// type which is supplying the configuration.
/// </param>
/// <exception cref="InvalidOperationException">
/// </exception>
/// <returns>
/// Type instance representing the EndPointConfiguration to load.
/// This Type can be instantiated when needed.
/// </returns>
private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase,
string assemblyName, string typeToLoad)
{
if ((string.IsNullOrEmpty(assemblyName) && !string.IsNullOrEmpty(typeToLoad)) ||
(!string.IsNullOrEmpty(assemblyName) && string.IsNullOrEmpty(typeToLoad)))
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.TypeNeedsAssembly,
ConfigurationDataFromXML.ASSEMBLYTOKEN,
ConfigurationDataFromXML.SHELLCONFIGTYPETOKEN,
ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
Assembly assembly = null;
if (!string.IsNullOrEmpty(assemblyName))
{
PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellAssembly,
PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
assemblyName, shellId);
assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName);
if (null == assembly)
{
throw PSTraceSource.NewArgumentException("assemblyName", RemotingErrorIdStrings.UnableToLoadAssembly,
assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
}
// configuration xml specified an assembly and typetoload.
if (null != assembly)
{
try
{
PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellType,
PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
typeToLoad, shellId);
Type type = assembly.GetType(typeToLoad, true, true);
if (null == type)
{
throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType,
typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
return type;
}
catch (ReflectionTypeLoadException)
{
}
catch (TypeLoadException)
{
}
catch (ArgumentException)
{
}
catch (MissingMethodException)
{
}
catch (InvalidCastException)
{
}
catch (TargetInvocationException)
{
}
// if we are here, that means we are unble to load the type specified
// in the config xml.. notify the same.
throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType,
typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN);
}
// load the default PowerShell since plugin config
// did not specify a typename to load.
return typeof(DefaultRemotePowerShellConfiguration);
}
/// <summary>
/// Sets the application's current working directory to <paramref name="applicationBase"/> and
/// loads the assembly <paramref name="assemblyName"/>. Once the assembly is loaded, the application's
/// current working directory is set back to the orginal value.
/// </summary>
/// <param name="applicationBase"></param>
/// <param name="assemblyName"></param>
/// <returns></returns>
// TODO: Send the exception message back to the client.
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
private static Assembly LoadSsnStateProviderAssembly(string applicationBase, string assemblyName)
{
Dbg.Assert(!string.IsNullOrEmpty(assemblyName), "AssemblyName cannot be null.");
string originalDirectory = string.Empty;
if (!string.IsNullOrEmpty(applicationBase))
{
// changing current working directory allows CLR loader to load dependent assemblies
try
{
originalDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(applicationBase);
}
catch (ArgumentException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (PathTooLongException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (IOException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (System.Security.SecurityException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
catch (UnauthorizedAccessException e)
{
s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}",
applicationBase, e.Message);
}
}
// Even if there is erro changing current working directory..try to load the assembly
// This is to allow assembly loading from GAC
Assembly result = null;
try
{
try
{
result = Assembly.Load(new AssemblyName(assemblyName));
}
catch (FileLoadException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (BadImageFormatException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
if (null != result)
{
return result;
}
s_tracer.WriteLine("Loading assembly from path {0}", applicationBase);
try
{
String assemblyPath;
if (!Path.IsPathRooted(assemblyName))
{
if (!String.IsNullOrEmpty(applicationBase) && Directory.Exists(applicationBase))
{
assemblyPath = Path.Combine(applicationBase, assemblyName);
}
else
{
assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), assemblyName);
}
}
else
{
//Rooted path of dll is provided.
assemblyPath = assemblyName;
}
result = ClrFacade.LoadFrom(assemblyPath);
}
catch (FileLoadException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (BadImageFormatException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
catch (FileNotFoundException e)
{
s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message);
}
}
finally
{
if (!string.IsNullOrEmpty(applicationBase))
{
// set the application's directory back to the original directory
Directory.SetCurrentDirectory(originalDirectory);
}
}
return result;
}
// TODO: I think this should be moved to Utils..this way all versioning related
// logic will be in one place.
private static RegistryKey GetConfigurationProvidersRegistryKey()
{
try
{
RegistryKey monadRootKey = PSSnapInReader.GetMonadRootKey();
RegistryKey versionRoot = PSSnapInReader.GetVersionRootKey(monadRootKey, Utils.GetCurrentMajorVersion());
RegistryKey configProviderKey = versionRoot.OpenSubKey(configProvidersKeyName);
return configProviderKey;
}
catch (ArgumentException)
{
}
catch (System.Security.SecurityException)
{
}
return null;
}
/// <summary>
/// Read value from the property <paramref name="name"/> for registry <paramref name="registryKey"/>
/// as string.
/// </summary>
/// <param name="registryKey">
/// Registry key from which the value is read.
/// Caller should make sure this is not null.
/// </param>
/// <param name="name">
/// Name of the property.
/// Caller should make sure this is not null.
/// </param>
/// <param name="mandatory">
/// True, if the property should exist.
/// False, otherwise.
/// </param>
/// <returns>
/// Value of the property.
/// </returns>
/// <exception cref="ArgumentException">
/// </exception>
/// <exception cref="System.Security.SecurityException">
/// </exception>
private static string
ReadStringValue(RegistryKey registryKey, string name, bool mandatory)
{
Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the name parameter");
Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter");
object value = registryKey.GetValue(name);
if (value == null && mandatory == true)
{
s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}",
name, registryKey.Name);
throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name);
}
string s = value as string;
if (string.IsNullOrEmpty(s) && mandatory == true)
{
s_tracer.TraceError("Value is null or empty for mandatory property {0} in {1}",
name, registryKey.Name);
throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name);
}
return s;
}
private const string configProvidersKeyName = "PSConfigurationProviders";
private const string configProviderApplicationBaseKeyName = "ApplicationBase";
private const string configProviderAssemblyNameKeyName = "AssemblyName";
private static Dictionary<string, ConfigurationDataFromXML> s_ssnStateProviders =
new Dictionary<string, ConfigurationDataFromXML>(StringComparer.OrdinalIgnoreCase);
private static object s_syncObject = new object();
#endregion
}
/// <summary>
/// Provides Default InitialSessionState.
/// </summary>
internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfiguration
{
/// <summary>
///
/// </summary>
/// <param name="senderInfo"></param>
/// <returns></returns>
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
{
InitialSessionState result = InitialSessionState.CreateDefault2();
// TODO: Remove this after RDS moved to $using
if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; }
return result;
}
public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
{
if (sessionConfigurationData == null)
throw new ArgumentNullException("sessionConfigurationData");
if (senderInfo == null)
throw new ArgumentNullException("senderInfo");
if (configProviderId == null)
throw new ArgumentNullException("configProviderId");
InitialSessionState sessionState = InitialSessionState.CreateDefault2();
// now get all the modules in the specified path and import the same
if (sessionConfigurationData != null && sessionConfigurationData.ModulesToImportInternal != null)
{
foreach (var module in sessionConfigurationData.ModulesToImportInternal)
{
var moduleName = module as string;
if (moduleName != null)
{
moduleName = Environment.ExpandEnvironmentVariables(moduleName);
sessionState.ImportPSModule(new[] { moduleName });
}
else
{
var moduleSpec = module as ModuleSpecification;
if (moduleSpec != null)
{
var modulesToImport = new Collection<ModuleSpecification> { moduleSpec };
sessionState.ImportPSModule(modulesToImport);
}
}
}
}
// TODO: Remove this after RDS moved to $using
if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; }
return sessionState;
}
}
#region Declarative Initial Session Configuration
/// <summary>
/// Specifies type of initial session state to use. Valid values are Empty and Default.
/// </summary>
public enum SessionType
{
/// <summary>
/// Empty session state
/// </summary>
Empty,
/// <summary>
/// Restricted remote server
/// </summary>
RestrictedRemoteServer,
/// <summary>
/// Default session state
/// </summary>
Default
}
/// <summary>
/// Configuration type entry
/// </summary>
internal class ConfigTypeEntry
{
internal delegate bool TypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path);
internal string Key;
internal TypeValidationCallback ValidationCallback;
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="callback"></param>
internal ConfigTypeEntry(string key, TypeValidationCallback callback)
{
this.Key = key;
this.ValidationCallback = callback;
}
}
/// <summary>
/// Configuration file constants
/// </summary>
internal static class ConfigFileConstants
{
internal static readonly string AliasDefinitions = "AliasDefinitions";
internal static readonly string AliasDescriptionToken = "Description";
internal static readonly string AliasNameToken = "Name";
internal static readonly string AliasOptionsToken = "Options";
internal static readonly string AliasValueToken = "Value";
internal static readonly string AssembliesToLoad = "AssembliesToLoad";
internal static readonly string Author = "Author";
internal static readonly string CompanyName = "CompanyName";
internal static readonly string Copyright = "Copyright";
internal static readonly string Description = "Description";
internal static readonly string EnforceInputParameterValidation = "EnforceInputParameterValidation";
internal static readonly string EnvironmentVariables = "EnvironmentVariables";
internal static readonly string ExecutionPolicy = "ExecutionPolicy";
internal static readonly string FormatsToProcess = "FormatsToProcess";
internal static readonly string FunctionDefinitions = "FunctionDefinitions";
internal static readonly string FunctionNameToken = "Name";
internal static readonly string FunctionOptionsToken = "Options";
internal static readonly string FunctionValueToken = "ScriptBlock";
internal static readonly string GMSAAccount = "GroupManagedServiceAccount";
internal static readonly string Guid = "GUID";
internal static readonly string LanguageMode = "LanguageMode";
internal static readonly string ModulesToImport = "ModulesToImport";
internal static readonly string MountUserDrive = "MountUserDrive";
internal static readonly string PowerShellVersion = "PowerShellVersion";
internal static readonly string RequiredGroups = "RequiredGroups";
internal static readonly string RoleDefinitions = "RoleDefinitions";
internal static readonly string SchemaVersion = "SchemaVersion";
internal static readonly string ScriptsToProcess = "ScriptsToProcess";
internal static readonly string SessionType = "SessionType";
internal static readonly string RoleCapabilities = "RoleCapabilities";
internal static readonly string RunAsVirtualAccount = "RunAsVirtualAccount";
internal static readonly string RunAsVirtualAccountGroups = "RunAsVirtualAccountGroups";
internal static readonly string TranscriptDirectory = "TranscriptDirectory";
internal static readonly string TypesToProcess = "TypesToProcess";
internal static readonly string UserDriveMaxSize = "UserDriveMaximumSize";
internal static readonly string VariableDefinitions = "VariableDefinitions";
internal static readonly string VariableNameToken = "Name";
internal static readonly string VariableValueToken = "Value";
internal static readonly string VisibleAliases = "VisibleAliases";
internal static readonly string VisibleCmdlets = "VisibleCmdlets";
internal static readonly string VisibleFunctions = "VisibleFunctions";
internal static readonly string VisibleProviders = "VisibleProviders";
internal static readonly string VisibleExternalCommands = "VisibleExternalCommands";
internal static ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] {
new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(CompanyName, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Copyright, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Description, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(EnforceInputParameterValidation,new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(EnvironmentVariables, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)),
new ConfigTypeEntry(ExecutionPolicy, new ConfigTypeEntry.TypeValidationCallback(ExecutionPolicyValidationCallback)),
new ConfigTypeEntry(FormatsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(FunctionDefinitions, new ConfigTypeEntry.TypeValidationCallback(FunctionDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(GMSAAccount, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(Guid, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(LanguageMode, new ConfigTypeEntry.TypeValidationCallback(LanugageModeValidationCallback)),
new ConfigTypeEntry(ModulesToImport, new ConfigTypeEntry.TypeValidationCallback(StringOrHashtableArrayTypeValidationCallback)),
new ConfigTypeEntry(MountUserDrive, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(PowerShellVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(RequiredGroups, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)),
new ConfigTypeEntry(RoleCapabilities, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(RoleDefinitions, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValiationCallback)),
new ConfigTypeEntry(RunAsVirtualAccount, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)),
new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)),
new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)),
new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)),
new ConfigTypeEntry(VariableDefinitions, new ConfigTypeEntry.TypeValidationCallback(VariableDefinitionsTypeValidationCallback)),
new ConfigTypeEntry(VisibleAliases, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleCmdlets, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleFunctions, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleProviders, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
new ConfigTypeEntry(VisibleExternalCommands, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)),
};