-
Notifications
You must be signed in to change notification settings - Fork 409
Expand file tree
/
Copy pathUseConstrainedLanguageMode.cs
More file actions
1101 lines (981 loc) · 48.1 KB
/
Copy pathUseConstrainedLanguageMode.cs
File metadata and controls
1101 lines (981 loc) · 48.1 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.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System.Management.Automation;
#if !CORECLR
using System.ComponentModel.Composition;
#endif
using System.Globalization;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
/// <summary>
/// UseConstrainedLanguageMode: Checks for patterns that indicate Constrained Language Mode should be considered.
/// </summary>
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif
public class UseConstrainedLanguageMode : ConfigurableRule
{
// Allowed COM objects in Constrained Language Mode
private static readonly HashSet<string> AllowedComObjects = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Scripting.Dictionary",
"Scripting.FileSystemObject",
"VBScript.RegExp"
};
// Allowed types in Constrained Language Mode (type accelerators and common types)
private static readonly HashSet<string> AllowedTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"adsi", "adsisearcher", "Alias", "AllowEmptyCollection", "AllowEmptyString",
"AllowNull", "ArgumentCompleter", "ArgumentCompletions", "array", "bigint",
"bool", "byte", "char", "cimclass", "cimconverter", "ciminstance", "CimSession",
"cimtype", "CmdletBinding", "cultureinfo", "datetime", "decimal", "double",
"DscLocalConfigurationManager", "DscProperty", "DscResource", "ExperimentAction",
"Experimental", "ExperimentalFeature", "float", "guid", "hashtable", "int",
"int16", "int32", "int64", "ipaddress", "IPEndpoint", "long", "mailaddress",
"Microsoft.PowerShell.Commands.ModuleSpecification", "NoRunspaceAffinity",
"NullString", "Object", "ObjectSecurity", "ordered", "OutputType", "Parameter",
"PhysicalAddress", "pscredential", "pscustomobject", "PSDefaultValue",
"pslistmodifier", "psobject", "psprimitivedictionary", "PSTypeNameAttribute",
"regex", "sbyte", "securestring", "semver", "short", "single", "string",
"SupportsWildcards", "switch", "timespan", "uint", "uint16", "uint32", "uint64",
"ulong", "uri", "ushort", "ValidateCount", "ValidateDrive", "ValidateLength",
"ValidateNotNull", "ValidateNotNullOrEmpty", "ValidateNotNullOrWhiteSpace",
"ValidatePattern", "ValidateRange", "ValidateScript", "ValidateSet",
"ValidateTrustedData", "ValidateUserDrive", "version", "void", "WildcardPattern",
"wmi", "wmiclass", "wmisearcher", "X500DistinguishedName", "X509Certificate", "xml",
// Full type names for common allowed types
"System.Object", "System.String", "System.Int32", "System.Boolean", "System.Byte",
"System.Collections.Hashtable", "System.DateTime", "System.Version", "System.Uri",
"System.Guid", "System.TimeSpan", "System.Management.Automation.PSCredential",
"System.Management.Automation.PSObject", "System.Security.SecureString",
"System.Text.RegularExpressions.Regex", "System.Xml.XmlDocument",
"System.Collections.ArrayList", "System.Collections.Generic.List",
"System.Net.IPAddress", "System.Net.Mail.MailAddress"
};
/// <summary>
/// Cache for typed variable assignments per scope to avoid O(N*M) performance issues.
/// Key: Scope AST (FunctionDefinitionAst or ScriptBlockAst)
/// Value: Dictionary mapping variable names to their type names
/// </summary>
private Dictionary<Ast, Dictionary<string, string>> _typedVariableCache;
/// <summary>
/// When True, ignores the presence of script signature blocks and runs all CLM checks
/// regardless of whether a script appears to be signed.
/// When False (default), scripts that contain a PowerShell signature block (for example,
/// one starting with '# SIG # Begin signature block') are treated as having elevated
/// permissions for this rule and only critical checks (dot-sourcing, parameter types,
/// manifests) are performed. No cryptographic validation or trust evaluation of the
/// signature is performed.
/// </summary>
[ConfigurableRuleProperty(defaultValue: false)]
public bool IgnoreSignatures { get; set; }
public UseConstrainedLanguageMode()
{
// This rule is disabled by default - users must explicitly enable it
Enable = false;
// IgnoreSignatures defaults to false (respects signatures)
IgnoreSignatures = false;
}
/// <summary>
/// Checks if a type name is allowed in Constrained Language Mode
/// </summary>
private bool IsTypeAllowed(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return true; // Can't determine, so don't flag
}
// Handle array types (e.g., string[], System.String[], int[][])
// Strip array brackets and check the base type
string baseTypeName = typeName;
// Handle multi-dimensional or jagged arrays by removing all brackets
while (baseTypeName.EndsWith("[]", StringComparison.Ordinal))
{
baseTypeName = baseTypeName.Substring(0, baseTypeName.Length - 2);
}
// Check exact match first
if (AllowedTypes.Contains(baseTypeName))
{
return true;
}
// Check simple name (last part after last dot)
if (baseTypeName.Contains('.'))
{
var simpleTypeName = baseTypeName.Substring(baseTypeName.LastIndexOf('.') + 1);
if (AllowedTypes.Contains(simpleTypeName))
{
return true;
}
}
return false;
}
/// <summary>
/// Analyzes the script to check for patterns that may require Constrained Language Mode.
/// </summary>
public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null)
{
throw new ArgumentNullException(nameof(ast));
}
// Initialize cache for this analysis to avoid O(N*M) performance issues
_typedVariableCache = new Dictionary<Ast, Dictionary<string, string>>();
var diagnosticRecords = new List<DiagnosticRecord>();
// Check if the file is signed (via signature block detection)
bool isFileSigned = IgnoreSignatures ? false : IsScriptSigned(fileName);
// Note: If IgnoreSignatures is true, isFileSigned will always be false,
// causing all CLM checks to run regardless of actual signature status
// Check if this is a module manifest (.psd1 file)
bool isModuleManifest = fileName != null && fileName.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase);
if (isModuleManifest)
{
// Perform PSD1-specific checks
// These checks are ALWAYS enforced, even for signed scripts
CheckModuleManifest(ast, fileName, diagnosticRecords);
}
// For signed scripts, only check specific patterns that are still restricted
// (unless IgnoreSignatures is true, then this block is skipped)
if (isFileSigned)
{
// Even signed scripts have these restrictions in CLM:
// 1. Check for dot-sourcing (still restricted in CLM even for signed scripts)
CheckDotSourcing(ast, fileName, diagnosticRecords);
// 2. Check for type constraints on parameters (still need to be validated)
CheckParameterTypeConstraints(ast, fileName, diagnosticRecords);
return diagnosticRecords;
}
// For unsigned scripts (or when IgnoreSignatures is true), perform all CLM checks
CheckAllClmRestrictions(ast, fileName, diagnosticRecords);
return diagnosticRecords;
}
/// <summary>
/// Checks if a PowerShell script file appears to be digitally signed.
/// Note: This performs a simple text check for the signature block marker.
/// It does NOT validate signature authenticity, certificate trust, or file integrity.
/// For production use, PowerShell's execution policy and Get-AuthenticodeSignature
/// should be used to properly validate signatures.
/// </summary>
private bool IsScriptSigned(string fileName)
{
if (string.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName))
{
return false;
}
// Only check .ps1, .psm1, and .psd1 files
string extension = System.IO.Path.GetExtension(fileName);
if (!extension.Equals(".ps1", StringComparison.OrdinalIgnoreCase) &&
!extension.Equals(".psm1", StringComparison.OrdinalIgnoreCase) &&
!extension.Equals(".psd1", StringComparison.OrdinalIgnoreCase))
{
return false;
}
try
{
// Read the file content
string content = System.IO.File.ReadAllText(fileName);
// Check for signature block marker
// A signed PowerShell script contains a signature block that starts with:
// # SIG # Begin signature block
//
// IMPORTANT: This is a simple text check only. It does NOT validate:
// - Signature authenticity
// - Certificate validity or trust
// - File integrity (hash matching)
// - Certificate expiration
//
// This check assumes that if a signature block is present, the script
// was intended to be signed. Actual signature validation is performed
// by PowerShell at execution time based on execution policy.
return content.IndexOf("# SIG # Begin signature block", StringComparison.OrdinalIgnoreCase) >= 0;
}
catch
{
// If we can't read the file, assume it's not signed
return false;
}
}
/// <summary>
/// Performs all CLM restriction checks (for unsigned scripts).
/// </summary>
private void CheckAllClmRestrictions(Ast ast, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
var addTypeCommands = ast.FindAll(testAst =>
testAst is CommandAst cmdAst &&
cmdAst.GetCommandName() != null &&
cmdAst.GetCommandName().Equals("Add-Type", StringComparison.OrdinalIgnoreCase),
true);
foreach (CommandAst cmd in addTypeCommands)
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.UseConstrainedLanguageModeAddTypeError),
cmd.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
// Check for New-Object with COM objects and TypeName (only specific ones are allowed in CLM)
var newObjectCommands = ast.FindAll(testAst =>
testAst is CommandAst cmdAst &&
cmdAst.GetCommandName() != null &&
cmdAst.GetCommandName().Equals("New-Object", StringComparison.OrdinalIgnoreCase),
true);
foreach (CommandAst cmd in newObjectCommands)
{
// Use StaticParameterBinder to reliably get parameter values
var bindingResult = StaticParameterBinder.BindCommand(cmd, true);
// Check for -ComObject parameter
if (bindingResult.BoundParameters.ContainsKey("ComObject"))
{
string comObjectValue = null;
// Try to get the value from the AST directly first
if (bindingResult.BoundParameters["ComObject"].Value is StringConstantExpressionAst strAst)
{
comObjectValue = strAst.Value;
}
else
{
// Fall back to ConstantValue
comObjectValue = bindingResult.BoundParameters["ComObject"].ConstantValue as string;
}
// Only flag if COM object name was found AND it's not in the allowed list
if (!string.IsNullOrWhiteSpace(comObjectValue) && !AllowedComObjects.Contains(comObjectValue))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeComObjectError,
comObjectValue),
cmd.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
// Check for -TypeName parameter
if (bindingResult.BoundParameters.ContainsKey("TypeName"))
{
var typeNameValue = bindingResult.BoundParameters["TypeName"].ConstantValue as string;
// If ConstantValue is null, try to extract from the AST Value
if (typeNameValue == null && bindingResult.BoundParameters["TypeName"].Value is StringConstantExpressionAst typeStrAst)
{
typeNameValue = typeStrAst.Value;
}
// Only flag if type name was found AND it's not in the allowed list
if (!string.IsNullOrWhiteSpace(typeNameValue) && !IsTypeAllowed(typeNameValue))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeNewObjectError,
typeNameValue),
cmd.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
// Check for XAML usage (not allowed in Constrained Language Mode)
var xamlPatterns = ast.FindAll(testAst =>
testAst is StringConstantExpressionAst strAst &&
strAst.Value.Contains("<") && strAst.Value.Contains("xmlns"),
true);
foreach (StringConstantExpressionAst xamlAst in xamlPatterns)
{
if (xamlAst.Value.Contains("http://schemas.microsoft.com/winfx"))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.UseConstrainedLanguageModeXamlError),
xamlAst.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
// Check for dot-sourcing (also called separately for signed scripts)
CheckDotSourcing(ast, fileName, diagnosticRecords);
// Check for Invoke-Expression usage (restricted in Constrained Language Mode)
var invokeExpressionCommands = ast.FindAll(testAst =>
testAst is CommandAst cmdAst &&
cmdAst.GetCommandName() != null &&
cmdAst.GetCommandName().Equals("Invoke-Expression", StringComparison.OrdinalIgnoreCase),
true);
foreach (CommandAst cmd in invokeExpressionCommands)
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.UseConstrainedLanguageModeInvokeExpressionError),
cmd.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
// Check for class definitions (not allowed in Constrained Language Mode)
var classDefinitions = ast.FindAll(testAst =>
testAst is TypeDefinitionAst typeAst && typeAst.IsClass,
true);
foreach (TypeDefinitionAst classDef in classDefinitions)
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeClassError,
classDef.Name),
classDef.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
// Check for parameter type constraints (also called separately for signed scripts)
CheckParameterTypeConstraints(ast, fileName, diagnosticRecords);
// Check for disallowed type constraints on variables (e.g., [System.Net.WebClient]$client)
var typeConstraints = ast.FindAll(testAst =>
testAst is TypeConstraintAst typeConstraint &&
!(typeConstraint.Parent is ParameterAst), // Exclude parameters - handled above
true);
foreach (TypeConstraintAst typeConstraint in typeConstraints)
{
var typeName = typeConstraint.TypeName.FullName;
if (!IsTypeAllowed(typeName))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeConstrainedTypeError,
typeName),
typeConstraint.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
// Check for disallowed type expressions and casts (e.g., [System.Net.WebClient]::new() or $x -as [Type])
var typeExpressions = ast.FindAll(testAst => testAst is TypeExpressionAst, true);
foreach (TypeExpressionAst typeExpr in typeExpressions)
{
var typeName = typeExpr.TypeName.FullName;
if (!IsTypeAllowed(typeName))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeTypeExpressionError,
typeName),
typeExpr.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
// Check for convert expressions (e.g., $x = [System.Net.WebClient]$value)
var convertExpressions = ast.FindAll(testAst => testAst is ConvertExpressionAst, true);
foreach (ConvertExpressionAst convertExpr in convertExpressions)
{
var typeName = convertExpr.Type.TypeName.FullName;
// Special case: [PSCustomObject]@{} is not allowed in CLM
// Even though PSCustomObject is an allowed type for parameters,
// the type cast syntax with hashtable literal is blocked in CLM
if (typeName.Equals("PSCustomObject", StringComparison.OrdinalIgnoreCase) &&
convertExpr.Child is HashtableAst)
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModePSCustomObjectError),
convertExpr.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
continue; // Already flagged, skip general type check
}
if (!IsTypeAllowed(typeName))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeConvertExpressionError,
typeName),
convertExpr.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
// Check for member invocations on disallowed types
// This includes method calls and property access on variables with type constraints
var memberInvocations = ast.FindAll(testAst =>
testAst is InvokeMemberExpressionAst || testAst is MemberExpressionAst, true);
foreach (Ast memberAst in memberInvocations)
{
// Skip static member access - already handled by TypeExpressionAst check
if (memberAst is InvokeMemberExpressionAst invokeAst && invokeAst.Static)
{
continue;
}
if (memberAst is MemberExpressionAst memAst && memAst.Static)
{
continue;
}
// Get the expression being invoked on (e.g., the variable in $var.Method())
ExpressionAst targetExpr = memberAst is InvokeMemberExpressionAst invExpr
? invExpr.Expression
: ((MemberExpressionAst)memberAst).Expression;
// Check if the target has a type constraint
string constrainedType = GetTypeConstraintFromExpression(targetExpr);
if (!string.IsNullOrWhiteSpace(constrainedType) && !IsTypeAllowed(constrainedType))
{
string memberName = memberAst is InvokeMemberExpressionAst inv
? (inv.Member as StringConstantExpressionAst)?.Value ?? "<unknown>"
: ((memberAst as MemberExpressionAst).Member as StringConstantExpressionAst)?.Value ?? "<unknown>";
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeMemberAccessError,
constrainedType,
memberName),
memberAst.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
/// <summary>
/// Checks for dot-sourcing patterns which are restricted in CLM even for signed scripts.
/// </summary>
private void CheckDotSourcing(Ast ast, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
// Dot-sourcing is detected by looking for commands where the extent text starts with a dot
// Example: . $PSScriptRoot\Helper.ps1
// Example: . .\script.ps1
// PowerShell doesn't have a specific DotSourceExpressionAst, so we check the command extent
var commands = ast.FindAll(testAst => testAst is CommandAst, true);
foreach (CommandAst cmdAst in commands)
{
// Check if the command extent starts with a dot followed by whitespace
// This indicates dot-sourcing
string extentText = cmdAst.Extent.Text.TrimStart();
if (extentText.StartsWith(".") && extentText.Length > 1 && char.IsWhiteSpace(extentText[1]))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture, Strings.UseConstrainedLanguageModeDotSourceError),
cmdAst.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
/// <summary>
/// Checks parameter type constraints which need validation even for signed scripts.
/// </summary>
private void CheckParameterTypeConstraints(Ast ast, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
// Find all parameter definitions
var parameters = ast.FindAll(testAst => testAst is ParameterAst, true);
foreach (ParameterAst param in parameters)
{
// Check for type constraints on parameters
var typeConstraints = param.Attributes.OfType<TypeConstraintAst>();
foreach (var typeConstraint in typeConstraints)
{
var typeName = typeConstraint.TypeName.FullName;
if (!IsTypeAllowed(typeName))
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeConstrainedTypeError,
typeName),
typeConstraint.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
}
/// <summary>
/// Attempts to determine if an expression has a type constraint.
/// Returns the type name if found, otherwise null.
/// </summary>
private string GetTypeConstraintFromExpression(ExpressionAst expr)
{
if (expr == null)
{
return null;
}
// Check if this is a convert expression with a type (e.g., [Type]$var)
if (expr is ConvertExpressionAst convertExpr)
{
return convertExpr.Type.TypeName.FullName;
}
// Check if this is a variable expression
if (expr is VariableExpressionAst varExpr)
{
// Walk up the AST to find if this variable has a type constraint in a parameter
var parameterAst = FindParameterForVariable(varExpr);
if (parameterAst != null)
{
// Get the first type constraint attribute
var typeConstraint = parameterAst.Attributes
.OfType<TypeConstraintAst>()
.FirstOrDefault();
if (typeConstraint != null)
{
return typeConstraint.TypeName.FullName;
}
}
// Check if the variable was declared with a type constraint elsewhere
// Look for assignment statements with type constraints
var assignmentWithType = FindTypedAssignment(varExpr);
if (assignmentWithType != null)
{
return assignmentWithType;
}
}
// Check if this is a member expression that might have a known return type
// For now, we'll be conservative and only check direct type constraints
return null;
}
/// <summary>
/// Finds the parameter AST for a given variable expression, if it exists.
/// </summary>
private ParameterAst FindParameterForVariable(VariableExpressionAst varExpr)
{
if (varExpr == null)
{
return null;
}
var varName = varExpr.VariablePath.UserPath;
// Walk up to find the containing function or script block
Ast current = varExpr.Parent;
while (current != null)
{
if (current is FunctionDefinitionAst funcAst)
{
// Check parameters in the param block
var paramBlock = funcAst.Body?.ParamBlock;
if (paramBlock?.Parameters != null)
{
foreach (var param in paramBlock.Parameters)
{
if (string.Equals(param.Name.VariablePath.UserPath, varName, StringComparison.OrdinalIgnoreCase))
{
return param;
}
}
}
// Check function parameters (for functions with parameters outside param block)
if (funcAst.Parameters != null)
{
foreach (var param in funcAst.Parameters)
{
if (string.Equals(param.Name.VariablePath.UserPath, varName, StringComparison.OrdinalIgnoreCase))
{
return param;
}
}
}
break; // Don't check outer function scopes
}
if (current is ScriptBlockAst scriptAst)
{
var paramBlock = scriptAst.ParamBlock;
if (paramBlock?.Parameters != null)
{
foreach (var param in paramBlock.Parameters)
{
if (string.Equals(param.Name.VariablePath.UserPath, varName, StringComparison.OrdinalIgnoreCase))
{
return param;
}
}
}
break; // Don't check outer script block scopes
}
current = current.Parent;
}
return null;
}
/// <summary>
/// Builds and caches typed variable assignments for a given scope.
/// This is called once per scope to avoid O(N*M) performance issues.
/// </summary>
private Dictionary<string, string> GetOrBuildTypedVariableCache(Ast scope)
{
if (scope == null)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
// Check if we already have cached results for this scope
if (_typedVariableCache.TryGetValue(scope, out var cachedResults))
{
return cachedResults;
}
// Build the cache for this scope
var typedVariables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// Find all assignment statements in this scope
var assignments = scope.FindAll(testAst => testAst is AssignmentStatementAst, true);
foreach (AssignmentStatementAst assignment in assignments)
{
// Check if the left side is a convert expression with a variable
if (assignment.Left is ConvertExpressionAst convertExpr &&
convertExpr.Child is VariableExpressionAst assignedVar)
{
var varName = assignedVar.VariablePath.UserPath;
var typeName = convertExpr.Type.TypeName.FullName;
// Store in cache (first assignment wins)
if (!typedVariables.ContainsKey(varName))
{
typedVariables[varName] = typeName;
}
}
}
// Cache the results
_typedVariableCache[scope] = typedVariables;
return typedVariables;
}
/// <summary>
/// Looks for a typed assignment to a variable using cached results.
/// </summary>
private string FindTypedAssignment(VariableExpressionAst varExpr)
{
if (varExpr == null)
{
return null;
}
var varName = varExpr.VariablePath.UserPath;
// Walk up to find the containing function or script block
Ast searchScope = varExpr.Parent;
while (searchScope != null &&
!(searchScope is FunctionDefinitionAst) &&
!(searchScope is ScriptBlockAst))
{
searchScope = searchScope.Parent;
}
if (searchScope == null)
{
return null;
}
// Use cached results instead of re-scanning the entire scope
var typedVariables = GetOrBuildTypedVariableCache(searchScope);
if (typedVariables.TryGetValue(varName, out string typeName))
{
return typeName;
}
return null;
}
/// <summary>
/// Checks module manifest (.psd1) files for CLM compatibility issues.
/// </summary>
private void CheckModuleManifest(Ast ast, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
// Find the hashtable in the manifest
var hashtableAst = ast.Find(x => x is HashtableAst, false) as HashtableAst;
if (hashtableAst == null)
{
return;
}
// Check for wildcard exports in FunctionsToExport, CmdletsToExport, AliasesToExport
CheckWildcardExports(hashtableAst, fileName, diagnosticRecords);
// Check for .ps1 files in RootModule, NestedModules, and ScriptsToProcess
CheckScriptModules(hashtableAst, fileName, diagnosticRecords);
}
/// <summary>
/// Checks for wildcard ('*') in export fields which are not allowed in CLM.
/// </summary>
private void CheckWildcardExports(HashtableAst hashtableAst, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
//AliasesToExport and VariablesToExport can use wildcards in CLM, but it is not recommended for performance reasons.
string[] exportFields = { "FunctionsToExport", "CmdletsToExport"};
foreach (var kvp in hashtableAst.KeyValuePairs)
{
if (kvp.Item1 is StringConstantExpressionAst keyAst)
{
string keyName = keyAst.Value;
if (exportFields.Contains(keyName, StringComparer.OrdinalIgnoreCase))
{
// Check if the value contains a wildcard
bool hasWildcard = false;
IScriptExtent wildcardExtent = null;
// The value in a hashtable is a StatementAst, need to extract the expression
var valueExpr = GetExpressionFromStatement(kvp.Item2);
if (valueExpr is StringConstantExpressionAst stringValue)
{
if (stringValue.Value == "*")
{
hasWildcard = true;
wildcardExtent = stringValue.Extent;
}
}
else if (valueExpr is ArrayLiteralAst arrayValue)
{
foreach (var element in arrayValue.Elements)
{
if (element is StringConstantExpressionAst strElement && strElement.Value == "*")
{
hasWildcard = true;
wildcardExtent = strElement.Extent;
break;
}
}
}
else if (valueExpr is ArrayExpressionAst arrayExpr)
{
// Array expressions like @('a', 'b') have a SubExpression inside
if (arrayExpr.SubExpression?.Statements != null)
{
foreach (var stmt in arrayExpr.SubExpression.Statements)
{
var expr = GetExpressionFromStatement(stmt);
if (expr is ArrayLiteralAst arrayLiteral)
{
foreach (var element in arrayLiteral.Elements)
{
if (element is StringConstantExpressionAst strElement && strElement.Value == "*")
{
hasWildcard = true;
wildcardExtent = strElement.Extent;
break;
}
}
}
else if (expr is StringConstantExpressionAst strElement && strElement.Value == "*")
{
// Handle single-item array expressions like @('*')
hasWildcard = true;
wildcardExtent = strElement.Extent;
break;
}
if (hasWildcard) break;
}
}
}
if (hasWildcard && wildcardExtent != null)
{
diagnosticRecords.Add(
new DiagnosticRecord(
String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeWildcardExportError,
keyName),
wildcardExtent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
}
}
/// <summary>
/// Checks for .ps1 files in RootModule, NestedModules, and ScriptsToProcess which are not recommended for CLM.
/// </summary>
private void CheckScriptModules(HashtableAst hashtableAst, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
string[] moduleFields = { "RootModule", "NestedModules", "ScriptsToProcess" };
foreach (var kvp in hashtableAst.KeyValuePairs)
{
if (kvp.Item1 is StringConstantExpressionAst keyAst)
{
string keyName = keyAst.Value;
if (moduleFields.Contains(keyName, StringComparer.OrdinalIgnoreCase))
{
var valueExpr = GetExpressionFromStatement(kvp.Item2);
CheckForPs1Files(valueExpr, keyName, fileName, diagnosticRecords);
}
}
}
}
/// <summary>
/// Extracts an ExpressionAst from a StatementAst (typically from hashtable values).
/// </summary>
private ExpressionAst GetExpressionFromStatement(StatementAst statement)
{
if (statement is PipelineAst pipeline && pipeline.PipelineElements.Count == 1)
{
if (pipeline.PipelineElements[0] is CommandExpressionAst commandExpr)
{
return commandExpr.Expression;
}
}
return null;
}
/// <summary>
/// Helper method to get the appropriate error message for .ps1 file usage in module manifests.
/// </summary>
private string GetPs1FileErrorMessage(string fieldName, string scriptFileName)
{
if (fieldName.Equals("ScriptsToProcess", StringComparison.OrdinalIgnoreCase))
{
return String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeScriptsToProcessError,
scriptFileName);
}
else
{
return String.Format(CultureInfo.CurrentCulture,
Strings.UseConstrainedLanguageModeScriptModuleError,
fieldName,
scriptFileName);
}
}
/// <summary>
/// Helper method to check if an expression contains .ps1 file references.
/// </summary>
private void CheckForPs1Files(ExpressionAst valueAst, string fieldName, string fileName, List<DiagnosticRecord> diagnosticRecords)
{
if (valueAst is StringConstantExpressionAst stringValue)
{
if (stringValue.Value != null && stringValue.Value.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
diagnosticRecords.Add(
new DiagnosticRecord(
GetPs1FileErrorMessage(fieldName, stringValue.Value),
stringValue.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
else if (valueAst is ArrayLiteralAst arrayValue)
{
foreach (var element in arrayValue.Elements)
{
if (element is StringConstantExpressionAst strElement &&
strElement.Value != null &&
strElement.Value.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
diagnosticRecords.Add(
new DiagnosticRecord(
GetPs1FileErrorMessage(fieldName, strElement.Value),
strElement.Extent,
GetName(),
GetDiagnosticSeverity(),
fileName
));
}
}
}
else if (valueAst is ArrayExpressionAst arrayExpr)
{
// Array expressions like @('a', 'b') have a SubExpression inside
if (arrayExpr.SubExpression?.Statements != null)
{