FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
PSScriptAnalyzer/Engine/ScriptAnalyzer.cs at main · PowerShell/PSScriptAnalyzer · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
PowerShell
/
PSScriptAnalyzer
Public
Notifications
You must be signed in to change notification settings
Fork
413
Star
2.1k
Code
Issues
401
Pull requests
22
Discussions
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
PSScriptAnalyzer
/
Engine
/
ScriptAnalyzer.cs
Copy path
More file actions
More file actions
Latest commit
History
History
History
2370 lines (2115 loc) · 102 KB
Breadcrumbs
PSScriptAnalyzer
/
Engine
/
ScriptAnalyzer.cs
Copy path
File metadata and controls
2370 lines (2115 loc) · 102 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
.
Text
.
RegularExpressions
;
using
Microsoft
.
Windows
.
PowerShell
.
ScriptAnalyzer
.
Generic
;
using
System
;
using
System
.
Collections
.
Generic
;
#if
!
CORECLR
using
System
.
ComponentModel
.
Composition
;
using
System
.
ComponentModel
.
Composition
.
Hosting
;
#endif
// !CORECLR
using
System
.
IO
;
using
System
.
Linq
;
using
System
.
Management
.
Automation
;
using
System
.
Management
.
Automation
.
Language
;
using
System
.
Management
.
Automation
.
Runspaces
;
using
System
.
Reflection
;
using
System
.
Globalization
;
using
System
.
Collections
.
Concurrent
;
using
System
.
Threading
.
Tasks
;
using
System
.
Collections
.
ObjectModel
;
using
System
.
Collections
;
using
System
.
Diagnostics
;
using
System
.
Text
;
using
Microsoft
.
Windows
.
PowerShell
.
ScriptAnalyzer
.
Extensions
;
namespace
Microsoft
.
Windows
.
PowerShell
.
ScriptAnalyzer
{
internal
enum
SuppressionPreference
{
Omit
=
0
,
Include
=
1
,
SuppressedOnly
=
2
,
}
public
sealed
class
ScriptAnalyzer
{
#region Private members
private
IOutputWriter
outputWriter
;
private
Dictionary
<
string
,
object
>
settings
;
private
readonly
Regex
s_aboutHelpRegex
=
new
Regex
(
"^about_.*help
\\
.txt$"
,
RegexOptions
.
IgnoreCase
|
RegexOptions
.
Compiled
)
;
#if
!
CORECLR
private
CompositionContainer
container
;
#endif
// !CORECLR
Dictionary
<
string
,
List
<
string
>
>
validationResults
=
new
Dictionary
<
string
,
List
<
string
>
>
(
)
;
string
[
]
includeRule
;
string
[
]
excludeRule
;
string
[
]
severity
;
List
<
Regex
>
includeRegexList
;
List
<
Regex
>
excludeRegexList
;
private
SuppressionPreference
_suppressionPreference
;
ModuleDependencyHandler
moduleHandler
;
#endregion
#region Singleton
private
static
object
syncRoot
=
new
Object
(
)
;
private
static
ScriptAnalyzer
instance
;
public
static
ScriptAnalyzer
Instance
{
get
{
if
(
instance
==
null
)
{
lock
(
syncRoot
)
{
if
(
instance
==
null
)
instance
=
new
ScriptAnalyzer
(
)
;
}
}
return
instance
;
}
}
#endregion
#region Properties
#if
CORECLR
public
IEnumerable
<
IScriptRule
>
ScriptRules
{
get
;
private
set
;
}
public
IEnumerable
<
ITokenRule
>
TokenRules
{
get
;
private
set
;
}
public
IEnumerable
<
ILogger
>
Loggers
{
get
;
private
set
;
}
public
IEnumerable
<
IDSCResourceRule
>
DSCResourceRules
{
get
;
private
set
;
}
#else
[
ImportMany
]
public
IEnumerable
<
IScriptRule
>
ScriptRules
{
get
;
private
set
;
}
[
ImportMany
]
public
IEnumerable
<
ITokenRule
>
TokenRules
{
get
;
private
set
;
}
[
ImportMany
]
public
IEnumerable
<
ILogger
>
Loggers
{
get
;
private
set
;
}
[
ImportMany
]
public
IEnumerable
<
IDSCResourceRule
>
DSCResourceRules
{
get
;
private
set
;
}
// Initializes via ImportMany
#endif
// !CORECLR
internal
List
<
ExternalRule
>
ExternalRules
{
get
;
set
;
}
public
ModuleDependencyHandler
ModuleHandler
{
get
{
return
moduleHandler
;
}
internal
set
{
moduleHandler
=
value
;
}
}
#endregion
#region Methods
/// <summary>
/// Initialize : Initializes default rules, loggers and helper.
/// </summary>
internal
void
Initialize
<
TCmdlet
>
(
TCmdlet
cmdlet
,
string
[
]
customizedRulePath
=
null
,
string
[
]
includeRuleNames
=
null
,
string
[
]
excludeRuleNames
=
null
,
string
[
]
severity
=
null
,
bool
includeDefaultRules
=
false
,
SuppressionPreference
suppressionPreference
=
SuppressionPreference
.
Omit
)
where
TCmdlet
:
PSCmdlet
,
IOutputWriter
{
if
(
cmdlet
==
null
)
{
throw
new
ArgumentNullException
(
"cmdlet"
)
;
}
this
.
Initialize
(
cmdlet
,
cmdlet
.
SessionState
.
Path
,
cmdlet
.
SessionState
.
InvokeCommand
,
customizedRulePath
,
includeRuleNames
,
excludeRuleNames
,
severity
,
includeDefaultRules
,
suppressionPreference
)
;
}
/// <summary>
/// Initialize : Initializes default rules, loggers and helper.
/// </summary>
public
void
Initialize
(
Runspace
runspace
,
IOutputWriter
outputWriter
,
string
[
]
customizedRulePath
=
null
,
string
[
]
includeRuleNames
=
null
,
string
[
]
excludeRuleNames
=
null
,
string
[
]
severity
=
null
,
bool
includeDefaultRules
=
false
,
bool
suppressedOnly
=
false
,
bool
includeSuppression
=
false
,
string
profile
=
null
)
{
if
(
runspace
==
null
)
{
throw
new
ArgumentNullException
(
"runspace"
)
;
}
//initialize helper
Helper
.
Instance
=
new
Helper
(
runspace
.
SessionStateProxy
.
InvokeCommand
)
;
Helper
.
Instance
.
Initialize
(
)
;
SuppressionPreference
suppressionPreference
=
suppressedOnly
?
SuppressionPreference
.
SuppressedOnly
:
includeSuppression
?
SuppressionPreference
.
Include
:
SuppressionPreference
.
Omit
;
this
.
Initialize
(
outputWriter
,
runspace
.
SessionStateProxy
.
Path
,
runspace
.
SessionStateProxy
.
InvokeCommand
,
customizedRulePath
,
includeRuleNames
,
excludeRuleNames
,
severity
,
includeDefaultRules
,
suppressionPreference
,
profile
)
;
}
/// <summary>
/// clean up this instance, resetting all properties
/// </summary>
public
void
CleanUp
(
)
{
includeRule
=
null
;
excludeRule
=
null
;
severity
=
null
;
includeRegexList
=
null
;
excludeRegexList
=
null
;
_suppressionPreference
=
SuppressionPreference
.
Omit
;
}
/// <summary>
/// Update includerules, excluderules, severity and rule arguments.
/// </summary>
/// <param name="settings">An object of type Settings</param>
public
void
UpdateSettings
(
Settings
settings
)
{
if
(
settings
==
null
)
{
throw
new
ArgumentNullException
(
nameof
(
settings
)
)
;
}
this
.
severity
=
(
!
settings
.
Severities
.
Any
(
)
)
?
null
:
settings
.
Severities
.
ToArray
(
)
;
this
.
includeRule
=
(
!
settings
.
IncludeRules
.
Any
(
)
)
?
null
:
settings
.
IncludeRules
.
ToArray
(
)
;
this
.
excludeRule
=
(
!
settings
.
ExcludeRules
.
Any
(
)
)
?
null
:
settings
.
ExcludeRules
.
ToArray
(
)
;
if
(
settings
.
RuleArguments
!=
null
)
{
Helper
.
Instance
.
SetRuleArguments
(
settings
.
RuleArguments
.
ToDictionary
(
kvp
=>
kvp
.
Key
,
kvp
=>
kvp
.
Value
as
object
,
StringComparer
.
OrdinalIgnoreCase
)
)
;
}
}
internal
bool
ParseProfile
(
object
profileObject
,
PathIntrinsics
path
,
IOutputWriter
writer
)
{
// profile was not given
if
(
profileObject
==
null
)
{
writer
.
WriteVerbose
(
"No settings hashtable or file to consume"
)
;
return
true
;
}
if
(
!
(
profileObject
is
string
||
profileObject
is
Hashtable
)
)
{
writer
.
WriteWarning
(
"Settings parameter should be a hashtable or a filepath"
)
;
return
false
;
}
List
<
string
>
includeRuleList
=
new
List
<
string
>
(
)
;
List
<
string
>
excludeRuleList
=
new
List
<
string
>
(
)
;
List
<
string
>
severityList
=
new
List
<
string
>
(
)
;
bool
hasError
=
false
;
Hashtable
hashTableProfile
=
profileObject
as
Hashtable
;
// checks whether we get a hashtable
if
(
hashTableProfile
!=
null
)
{
hasError
=
ParseProfileHashtable
(
hashTableProfile
,
path
,
writer
,
severityList
,
includeRuleList
,
excludeRuleList
)
;
}
else
{
// checks whether we get a string instead
string
profile
=
profileObject
as
string
;
if
(
!
String
.
IsNullOrWhiteSpace
(
profile
)
)
{
hasError
=
ParseProfileString
(
profile
,
path
,
writer
,
severityList
,
includeRuleList
,
excludeRuleList
)
;
}
}
if
(
hasError
)
{
return
false
;
}
this
.
severity
=
(
severityList
.
Count
==
0
)
?
null
:
severityList
.
ToArray
(
)
;
this
.
includeRule
=
(
includeRuleList
.
Count
==
0
)
?
null
:
includeRuleList
.
ToArray
(
)
;
this
.
excludeRule
=
(
excludeRuleList
.
Count
==
0
)
?
null
:
excludeRuleList
.
ToArray
(
)
;
if
(
settings
!=
null
&&
settings
.
ContainsKey
(
"Rules"
)
)
{
var
ruleArgs
=
settings
[
"Rules"
]
as
Dictionary
<
string
,
object
>
;
Helper
.
Instance
.
SetRuleArguments
(
ruleArgs
)
;
}
return
true
;
}
private
bool
AddProfileItem
(
string
key
,
List
<
string
>
values
,
List
<
string
>
severityList
,
List
<
string
>
includeRuleList
,
List
<
string
>
excludeRuleList
)
{
Debug
.
Assert
(
key
!=
null
)
;
Debug
.
Assert
(
values
!=
null
)
;
Debug
.
Assert
(
severityList
!=
null
)
;
Debug
.
Assert
(
includeRuleList
!=
null
)
;
Debug
.
Assert
(
excludeRuleList
!=
null
)
;
if
(
key
.
Equals
(
"severity"
,
StringComparison
.
OrdinalIgnoreCase
)
)
{
severityList
.
AddRange
(
values
)
;
return
true
;
}
if
(
key
.
Equals
(
"includerules"
,
StringComparison
.
OrdinalIgnoreCase
)
)
{
includeRuleList
.
AddRange
(
values
)
;
return
true
;
}
return
false
;
}
private
Dictionary
<
string
,
object
>
GetDictionaryFromHashTableAst
(
HashtableAst
hashTableAst
,
IOutputWriter
writer
,
string
profile
,
out
bool
hasError
)
{
hasError
=
false
;
var
output
=
new
Dictionary
<
string
,
object
>
(
StringComparer
.
OrdinalIgnoreCase
)
;
foreach
(
var
kvp
in
hashTableAst
.
KeyValuePairs
)
{
var
keyAst
=
kvp
.
Item1
as
StringConstantExpressionAst
;
if
(
keyAst
==
null
)
{
// first item (the key) should be a string
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongKeyFormat
,
kvp
.
Item1
.
Extent
.
StartLineNumber
,
kvp
.
Item1
.
Extent
.
StartColumnNumber
,
profile
)
)
,
Strings
.
ConfigurationKeyNotAString
,
ErrorCategory
.
InvalidData
,
profile
)
)
;
hasError
=
true
;
continue
;
}
var
key
=
keyAst
.
Value
;
// parse the item2 as array
PipelineAst
pipeAst
=
kvp
.
Item2
as
PipelineAst
;
List
<
string
>
rhsList
=
new
List
<
string
>
(
)
;
if
(
pipeAst
!=
null
)
{
ExpressionAst
pureExp
=
pipeAst
.
GetPureExpression
(
)
;
if
(
pureExp
is
StringConstantExpressionAst
)
{
rhsList
.
Add
(
(
pureExp
as
StringConstantExpressionAst
)
.
Value
)
;
}
else
if
(
pureExp
is
HashtableAst
)
{
output
[
key
]
=
GetDictionaryFromHashTableAst
(
pureExp
as
HashtableAst
,
writer
,
profile
,
out
hasError
)
;
continue
;
}
else
{
ArrayLiteralAst
arrayLitAst
=
pureExp
as
ArrayLiteralAst
;
if
(
arrayLitAst
==
null
&&
pureExp
is
ArrayExpressionAst
)
{
ArrayExpressionAst
arrayExp
=
pureExp
as
ArrayExpressionAst
;
// Statements property is never null
if
(
arrayExp
.
SubExpression
!=
null
)
{
StatementAst
stateAst
=
arrayExp
.
SubExpression
.
Statements
.
FirstOrDefault
(
)
;
if
(
stateAst
!=
null
&&
stateAst
is
PipelineAst
)
{
CommandBaseAst
cmdBaseAst
=
(
stateAst
as
PipelineAst
)
.
PipelineElements
.
FirstOrDefault
(
)
;
if
(
cmdBaseAst
!=
null
&&
cmdBaseAst
is
CommandExpressionAst
)
{
CommandExpressionAst
cmdExpAst
=
cmdBaseAst
as
CommandExpressionAst
;
if
(
cmdExpAst
.
Expression
is
StringConstantExpressionAst
)
{
rhsList
.
Add
(
(
cmdExpAst
.
Expression
as
StringConstantExpressionAst
)
.
Value
)
;
}
else
{
arrayLitAst
=
cmdExpAst
.
Expression
as
ArrayLiteralAst
;
}
}
}
}
}
if
(
arrayLitAst
!=
null
)
{
foreach
(
var
element
in
arrayLitAst
.
Elements
)
{
// all the values in the array needs to be string
if
(
!
(
element
is
StringConstantExpressionAst
)
)
{
outputWriter
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongValueFormat
,
element
.
Extent
.
StartLineNumber
,
element
.
Extent
.
StartColumnNumber
,
""
)
)
,
Strings
.
ConfigurationValueNotAString
,
ErrorCategory
.
InvalidData
,
null
)
)
;
hasError
=
true
;
continue
;
}
rhsList
.
Add
(
(
element
as
StringConstantExpressionAst
)
.
Value
)
;
}
}
}
}
if
(
rhsList
.
Count
==
0
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongValueFormat
,
kvp
.
Item2
.
Extent
.
StartLineNumber
,
kvp
.
Item2
.
Extent
.
StartColumnNumber
,
profile
)
)
,
Strings
.
ConfigurationValueWrongFormat
,
ErrorCategory
.
InvalidData
,
profile
)
)
;
hasError
=
true
;
continue
;
}
output
[
key
]
=
rhsList
;
}
return
output
;
}
/// <summary>
/// Recursively convert hashtable to dictionary
/// </summary>
/// <param name="hashtable"></param>
/// <returns>Dictionary that maps string to object</returns>
private
Dictionary
<
string
,
object
>
GetDictionaryFromHashtable
(
Hashtable
hashtable
,
IOutputWriter
writer
,
out
bool
hasError
)
{
var
dictionary
=
new
Dictionary
<
string
,
object
>
(
StringComparer
.
OrdinalIgnoreCase
)
;
hasError
=
false
;
foreach
(
var
obj
in
hashtable
.
Keys
)
{
string
key
=
obj
as
string
;
if
(
key
==
null
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
KeyNotString
,
key
)
)
,
Strings
.
ConfigurationKeyNotAString
,
ErrorCategory
.
InvalidData
,
hashtable
)
)
;
hasError
=
true
;
return
null
;
}
var
valueHashtableObj
=
hashtable
[
obj
]
;
if
(
valueHashtableObj
==
null
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongValueHashTable
,
valueHashtableObj
,
key
)
)
,
Strings
.
WrongConfigurationKey
,
ErrorCategory
.
InvalidData
,
hashtable
)
)
;
hasError
=
true
;
return
null
;
}
var
valueHashtable
=
valueHashtableObj
as
Hashtable
;
if
(
valueHashtable
==
null
)
{
dictionary
.
Add
(
key
,
valueHashtableObj
)
;
}
else
{
var
dict
=
GetDictionaryFromHashtable
(
valueHashtable
,
writer
,
out
hasError
)
;
if
(
dict
!=
null
)
{
dictionary
.
Add
(
key
,
dict
)
;
}
else
{
return
null
;
}
}
}
return
dictionary
;
}
private
bool
ParseProfileHashtable
(
Hashtable
profile
,
PathIntrinsics
path
,
IOutputWriter
writer
,
List
<
string
>
severityList
,
List
<
string
>
includeRuleList
,
List
<
string
>
excludeRuleList
)
{
bool
hasError
=
false
;
HashSet
<
string
>
validKeys
=
new
HashSet
<
string
>
(
StringComparer
.
OrdinalIgnoreCase
)
;
validKeys
.
Add
(
"severity"
)
;
validKeys
.
Add
(
"includerules"
)
;
validKeys
.
Add
(
"excluderules"
)
;
validKeys
.
Add
(
"rules"
)
;
settings
=
GetDictionaryFromHashtable
(
profile
,
writer
,
out
hasError
)
;
if
(
hasError
)
{
return
hasError
;
}
var
settingsKeys
=
new
string
[
settings
.
Keys
.
Count
]
;
settings
.
Keys
.
CopyTo
(
settingsKeys
,
0
)
;
foreach
(
var
settingKey
in
settingsKeys
)
{
object
value
=
settings
[
settingKey
]
;
if
(
settingKey
.
Equals
(
"severity"
,
StringComparison
.
OrdinalIgnoreCase
)
||
settingKey
.
Equals
(
"includerules"
,
StringComparison
.
OrdinalIgnoreCase
)
||
settingKey
.
Equals
(
"excluderules"
,
StringComparison
.
OrdinalIgnoreCase
)
)
{
// value must be either string or collections of string or array
if
(
value
==
null
||
!
(
value
is
string
||
value
is
IEnumerable
<
string
>
||
value
.
GetType
(
)
.
IsArray
)
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongValueHashTable
,
value
,
settingKey
)
)
,
Strings
.
WrongConfigurationKey
,
ErrorCategory
.
InvalidData
,
profile
)
)
;
hasError
=
true
;
break
;
}
var
values
=
new
List
<
string
>
(
)
;
if
(
value
is
string
)
{
values
.
Add
(
value
as
string
)
;
}
else
if
(
value
is
IEnumerable
<
string
>
)
{
values
.
Union
(
value
as
IEnumerable
<
string
>
)
;
}
else
if
(
value
.
GetType
(
)
.
IsArray
)
{
// for array case, sometimes we won't be able to cast it directly to IEnumerable<string>
foreach
(
var
val
in
value
as
IEnumerable
)
{
if
(
val
is
string
)
{
values
.
Add
(
val
as
string
)
;
}
else
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongValueHashTable
,
val
,
settingKey
)
)
,
Strings
.
WrongConfigurationKey
,
ErrorCategory
.
InvalidData
,
profile
)
)
;
hasError
=
true
;
break
;
}
}
}
AddProfileItem
(
settingKey
,
values
,
severityList
,
includeRuleList
,
excludeRuleList
)
;
settings
[
settingKey
]
=
values
;
}
else
if
(
settingKey
.
Equals
(
"excluderules"
,
StringComparison
.
OrdinalIgnoreCase
)
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
InvalidDataException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
WrongKeyHashTable
,
settingKey
)
)
,
Strings
.
WrongConfigurationKey
,
ErrorCategory
.
InvalidData
,
profile
)
)
;
hasError
=
true
;
}
}
return
hasError
;
}
private
bool
ParseProfileString
(
string
profile
,
PathIntrinsics
path
,
IOutputWriter
writer
,
List
<
string
>
severityList
,
List
<
string
>
includeRuleList
,
List
<
string
>
excludeRuleList
)
{
bool
hasError
=
false
;
try
{
profile
=
path
.
GetResolvedPSPathFromPSPath
(
profile
)
.
First
(
)
.
Path
;
}
catch
{
writer
.
WriteError
(
new
ErrorRecord
(
new
FileNotFoundException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
FileNotFound
,
profile
)
)
,
Strings
.
ConfigurationFileNotFound
,
ErrorCategory
.
ResourceUnavailable
,
profile
)
)
;
hasError
=
true
;
}
if
(
File
.
Exists
(
profile
)
)
{
Token
[
]
parserTokens
=
null
;
ParseError
[
]
parserErrors
=
null
;
Ast
profileAst
=
Parser
.
ParseFile
(
profile
,
out
parserTokens
,
out
parserErrors
)
;
IEnumerable
<
Ast
>
hashTableAsts
=
profileAst
.
FindAll
(
item
=>
item
is
HashtableAst
,
false
)
;
// no hashtable, raise warning
if
(
!
hashTableAsts
.
Any
(
)
)
{
writer
.
WriteError
(
new
ErrorRecord
(
new
ArgumentException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
InvalidProfile
,
profile
)
)
,
Strings
.
ConfigurationFileHasNoHashTable
,
ErrorCategory
.
ResourceUnavailable
,
profile
)
)
;
hasError
=
true
;
}
else
{
HashtableAst
hashTableAst
=
hashTableAsts
.
First
(
)
as
HashtableAst
;
try
{
var
hashtable
=
hashTableAst
.
SafeGetValue
(
)
as
Hashtable
;
hasError
=
ParseProfileHashtable
(
hashtable
,
path
,
writer
,
severityList
,
includeRuleList
,
excludeRuleList
)
;
}
catch
{
writer
.
WriteError
(
new
ErrorRecord
(
new
ArgumentException
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
InvalidProfile
,
profile
)
)
,
Strings
.
ConfigurationFileHasInvalidHashtable
,
ErrorCategory
.
ResourceUnavailable
,
profile
)
)
;
hasError
=
true
;
}
}
}
return
hasError
;
}
private
void
Initialize
(
IOutputWriter
outputWriter
,
PathIntrinsics
path
,
CommandInvocationIntrinsics
invokeCommand
,
string
[
]
customizedRulePath
,
string
[
]
includeRuleNames
,
string
[
]
excludeRuleNames
,
string
[
]
severity
,
bool
includeDefaultRules
=
false
,
SuppressionPreference
suppressionPreference
=
SuppressionPreference
.
Omit
,
string
profile
=
null
)
{
if
(
outputWriter
==
null
)
{
throw
new
ArgumentNullException
(
"outputWriter"
)
;
}
this
.
moduleHandler
=
null
;
this
.
outputWriter
=
outputWriter
;
#region Verifies rule extensions
List
<
string
>
paths
=
this
.
GetValidCustomRulePaths
(
customizedRulePath
,
path
)
;
#endregion
#if
CORECLR
// For Full CLR logger is loaded via Composition
// But for Core CLR we need to load it explicitly
this
.
Loggers
=
GetInterfaceImplementationsFromAssembly
<
ILogger
>
(
)
;
#endif
#region Initializes Rules
var
includeRuleList
=
new
List
<
string
>
(
)
;
var
excludeRuleList
=
new
List
<
string
>
(
)
;
var
severityList
=
new
List
<
string
>
(
)
;
if
(
profile
!=
null
)
{
ParseProfileString
(
profile
,
path
,
outputWriter
,
severityList
,
includeRuleList
,
excludeRuleList
)
;
}
if
(
includeRuleNames
!=
null
)
{
foreach
(
string
includeRuleName
in
includeRuleNames
.
Where
(
rule
=>
!
includeRuleList
.
Contains
(
rule
,
StringComparer
.
OrdinalIgnoreCase
)
)
)
{
includeRuleList
.
Add
(
includeRuleName
)
;
}
}
if
(
excludeRuleNames
!=
null
)
{
foreach
(
string
excludeRuleName
in
excludeRuleNames
.
Where
(
rule
=>
!
excludeRuleList
.
Contains
(
rule
,
StringComparer
.
OrdinalIgnoreCase
)
)
)
{
excludeRuleList
.
Add
(
excludeRuleName
)
;
}
}
if
(
severity
!=
null
)
{
foreach
(
string
sev
in
severity
.
Where
(
s
=>
!
severityList
.
Contains
(
s
,
StringComparer
.
OrdinalIgnoreCase
)
)
)
{
severityList
.
Add
(
sev
)
;
}
}
_suppressionPreference
=
suppressionPreference
;
this
.
includeRegexList
=
new
List
<
Regex
>
(
)
;
this
.
excludeRegexList
=
new
List
<
Regex
>
(
)
;
if
(
this
.
severity
==
null
)
{
this
.
severity
=
severityList
.
Count
==
0
?
null
:
severityList
.
ToArray
(
)
;
}
else
{
this
.
severity
=
this
.
severity
.
Union
(
severityList
)
.
ToArray
(
)
;
}
if
(
this
.
includeRule
==
null
)
{
this
.
includeRule
=
includeRuleList
.
Count
==
0
?
null
:
includeRuleList
.
ToArray
(
)
;
}
else
{
this
.
includeRule
=
this
.
includeRule
.
Union
(
includeRuleList
)
.
ToArray
(
)
;
}
if
(
this
.
excludeRule
==
null
)
{
this
.
excludeRule
=
excludeRuleList
.
Count
==
0
?
null
:
excludeRuleList
.
ToArray
(
)
;
}
else
{
this
.
excludeRule
=
this
.
excludeRule
.
Union
(
excludeRuleList
)
.
ToArray
(
)
;
}
//Check wild card input for the Include/ExcludeRules and create regex match patterns
if
(
this
.
includeRule
!=
null
)
{
foreach
(
string
rule
in
includeRule
)
{
Regex
includeRegex
=
new
Regex
(
String
.
Format
(
"^{0}$"
,
Regex
.
Escape
(
rule
)
.
Replace
(
@"\*"
,
".*"
)
)
,
RegexOptions
.
IgnoreCase
)
;
this
.
includeRegexList
.
Add
(
includeRegex
)
;
}
}
if
(
this
.
excludeRule
!=
null
)
{
foreach
(
string
rule
in
excludeRule
)
{
Regex
excludeRegex
=
new
Regex
(
String
.
Format
(
"^{0}$"
,
Regex
.
Escape
(
rule
)
.
Replace
(
@"\*"
,
".*"
)
)
,
RegexOptions
.
IgnoreCase
)
;
this
.
excludeRegexList
.
Add
(
excludeRegex
)
;
}
}
try
{
this
.
LoadRules
(
this
.
validationResults
,
invokeCommand
,
includeDefaultRules
)
;
this
.
ConfigureScriptRules
(
)
;
}
catch
(
Exception
ex
)
{
this
.
outputWriter
.
ThrowTerminatingError
(
new
ErrorRecord
(
ex
,
ex
.
HResult
.
ToString
(
"X"
,
CultureInfo
.
CurrentCulture
)
,
ErrorCategory
.
NotSpecified
,
this
)
)
;
}
#endregion
#region Verify rules
// Safely get one non-duplicated list of rules
IEnumerable
<
IRule
>
rules
=
Enumerable
.
Union
<
IRule
>
(
Enumerable
.
Union
<
IRule
>
(
this
.
ScriptRules
??
Enumerable
.
Empty
<
IRule
>
(
)
,
this
.
TokenRules
??
Enumerable
.
Empty
<
IRule
>
(
)
)
,
this
.
ExternalRules
??
Enumerable
.
Empty
<
IExternalRule
>
(
)
)
;
// Ensure that rules were actually loaded
if
(
rules
==
null
||
rules
.
Any
(
)
==
false
)
{
string
errorMessage
=
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
RulesNotFound
)
;
this
.
outputWriter
.
ThrowTerminatingError
(
new
ErrorRecord
(
new
Exception
(
errorMessage
)
,
errorMessage
,
ErrorCategory
.
ObjectNotFound
,
this
)
)
;
}
#endregion
}
private
List
<
string
>
GetValidCustomRulePaths
(
string
[
]
customizedRulePath
,
PathIntrinsics
path
)
{
List
<
string
>
paths
=
new
List
<
string
>
(
)
;
if
(
customizedRulePath
!=
null
)
{
paths
.
AddRange
(
customizedRulePath
.
ToList
(
)
)
;
}
if
(
paths
.
Count
>
0
)
{
this
.
validationResults
=
this
.
CheckRuleExtension
(
paths
.
ToArray
(
)
,
path
)
;
foreach
(
string
extension
in
this
.
validationResults
[
"InvalidPaths"
]
)
{
this
.
outputWriter
.
WriteWarning
(
string
.
Format
(
CultureInfo
.
CurrentCulture
,
Strings
.
MissingRuleExtension
,
extension
)
)
;
}
}
else
{
this
.
validationResults
=
new
Dictionary
<
string
,
List
<
string
>
>
(
)
;
this
.
validationResults
.
Add
(
"InvalidPaths"
,
new
List
<
string
>
(
)
)
;
this
.
validationResults
.
Add
(
"ValidModPaths"
,
new
List
<
string
>
(
)
)
;
this
.
validationResults
.
Add
(
"ValidDllPaths"
,
new
List
<
string
>
(
)
)
;
}
return
paths
;
}
private
IEnumerable
<
T
>
GetInterfaceImplementationsFromAssembly
<
T
>
(
)
where
T
:
class
{
string
dirName
=
Path
.
GetDirectoryName
(
typeof
(
ScriptAnalyzer
)
.
GetTypeInfo
(
)
.
Assembly
.
Location
)
;
var
dllPaths
=
Directory
.
EnumerateFiles
(
dirName
,
"*.dll"
,
SearchOption
.
TopDirectoryOnly
)
;
var
objects
=
new
List
<
T
>
(
)
;
foreach
(
var
dllPath
in
dllPaths
)
{
outputWriter
.
WriteVerbose
(
string
.
Format
(
"Found Assembly: {0}"
,
dllPath
)
)
;
var
objectsFromOneFile
=
GetInterfaceImplementationsFromAssembly
<
T
>
(
dllPath
)
;
objects
.
AddRange
(
objectsFromOneFile
)
;
}
return
objects
;
}
private
IEnumerable
<
T
>
GetInterfaceImplementationsFromAssembly
<
T
>
(
string
ruleDllPath
)
where
T
:
class
{
string
fileName
=
Path
.
GetFileNameWithoutExtension
(
ruleDllPath
)
;
var
assemblyName
=
new
AssemblyName
(
fileName
)
;
outputWriter
.
WriteVerbose
(
string
.
Format
(
"Loading Assembly:{0}"
,
assemblyName
.
FullName
)
)
;
Assembly
dll
=
Assembly
.
Load
(
assemblyName
)
;
if
(
dll
==
null
)
{
outputWriter
.
WriteVerbose
(
string
.
Format
(
"Cannot load {0}"
,
ruleDllPath
)
)
;
return
Enumerable
.
Empty
<
T
>
(
)
;
}
var
rules
=
new
List
<
T
>
(
)
;
foreach
(
Type
type
in
dll
.
ExportedTypes
)
{
if
(
type
.
IsInterface
||
type
.
IsAbstract
||
!
typeof
(
T
)
.
IsAssignableFrom
(
type
)
)
{
continue
;
}
var
rule
=
Activator
.
CreateInstance
(
type
)
as
T
;
if
(
rule
==
null
)
{
outputWriter
.
WriteVerbose
(
string
.
Format
(
"Cannot cast instance of type {0} to {1}"
,
type
.
Name
,
typeof
(
T
)
.
GetTypeInfo
(
)
.
Name
)
)
;
continue
;
}
rules
.
Add
(
rule
)
;
}
return
rules
;
}
private
void
LoadRules
(
Dictionary
<
string
,
List
<
string
>
>
result
,
CommandInvocationIntrinsics
invokeCommand
,
bool
loadBuiltInRules
)
{
List
<
string
>
paths
=
new
List
<
string
>
(
)
;
// Clear external rules for each invoke.
this
.
ScriptRules
=
null
;
this
.
TokenRules
=
null
;
this
.
ExternalRules
=
null
;
#if
CORECLR
this
.
ScriptRules
=
GetInterfaceImplementationsFromAssembly
<
IScriptRule
>
(
)
;
this
.
TokenRules
=
GetInterfaceImplementationsFromAssembly
<
ITokenRule
>
(
)
;
this
.
DSCResourceRules
=
GetInterfaceImplementationsFromAssembly
<
IDSCResourceRule
>
(
)
;
#else
// An aggregate catalog that combines multiple catalogs.
using
(
AggregateCatalog
catalog
=
new
AggregateCatalog
(
)
)
{
// Adds all the parts found in the same directory.
string
dirName
=
Path
.
GetDirectoryName
(
Assembly
.
GetExecutingAssembly
(
)
.
Location
)
;
catalog
.
Catalogs
.
Add
(
new
SafeDirectoryCatalog
(
dirName
,
this
.
outputWriter
)
)
;
// Adds user specified directory
paths
=
result
.
ContainsKey
(
"ValidDllPaths"
)
?
result
[
"ValidDllPaths"
]
:
result
[
"ValidPaths"
]
;
foreach
(
string
path
in
paths
)
{
if
(
String
.
Equals
(
Path
.
GetExtension
(
path
)
,
".dll"
,
StringComparison
.
OrdinalIgnoreCase
)
)
{
catalog
.
Catalogs
.
Add
(
new
AssemblyCatalog
(
path
)
)
;
}
else
{
catalog
.
Catalogs
.
Add
(
new
SafeDirectoryCatalog
(
path
,
this
.
outputWriter
)
)
;
}
}
// Creates the CompositionContainer with the parts in the catalog.
container
=
new
CompositionContainer
(
catalog
)
;
// Fills the imports of this object.
try
{
container
.
ComposeParts
(
this
)
;
}
catch
(
CompositionException
compositionException
)
{
this
.
outputWriter
.
WriteWarning
(
compositionException
.
ToString
(
)
)
;
}
}
#endif
// CORECLR
if
(
!
loadBuiltInRules
)
{
this
.
ScriptRules
=
null
;
}
// Gets external rules.
if
(
result
.
ContainsKey
(
"ValidModPaths"
)
&&
result
[
"ValidModPaths"
]
.
Count
>
0
)
{
ExternalRules
=
GetExternalRule
(
result
[
"ValidModPaths"
]
.
ToArray
(
)
)
;
}
}
// Configure rules derived from ConfigurableScriptRule class
private
void
ConfigureScriptRules
(
)
{
if
(
ScriptRules
==
null
)
{
return
;
}
foreach
(
var
scriptRule
in
ScriptRules
)
{
var
configurableScriptRule
=
scriptRule
as
ConfigurableRule
;
if
(
configurableScriptRule
==
null
)
{
continue
;
}
var
paramValueMap
=
Helper
.
Instance
.
GetRuleArguments
(
scriptRule
.
GetName
(
)
)
;
if
(
paramValueMap
==
null
)
{
continue
;
}
configurableScriptRule
.
ConfigureRule
(
paramValueMap
)
;
}
}
internal
string
[
]
GetValidModulePaths
(
)
{
List
<
string
>
validModulePaths
=
null
;
if
(
!
this
.
validationResults
.
TryGetValue
(
"ValidModPaths"
,
out
validModulePaths
)
)
{
validModulePaths
=
new
List
<
string
>
(
)
;
}
return
validModulePaths
.
ToArray
(
)
;
}
public
IEnumerable
<
IRule
>
GetRule
(
string
[
]
moduleNames
,
string
[
]
ruleNames
)
{
IEnumerable
<
IRule
>
results
=
null
;
IEnumerable
<
IExternalRule
>
externalRules
=
null
;
// Combines C# rules.
IEnumerable
<
IRule
>
rules
=
Enumerable
.
Empty
<
IRule
>
(
)
;
if
(
null
!=
ScriptRules
)
{
rules
=
ScriptRules
.
Union
<
IRule
>
(
TokenRules
)
.
Union
<
IRule
>
(
DSCResourceRules
)
;
}
// Gets PowerShell Rules.
if
(
moduleNames
!=
null
)
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL