-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathTestEngineExtensionChecker.cs
More file actions
985 lines (863 loc) · 42.3 KB
/
TestEngineExtensionChecker.cs
File metadata and controls
985 lines (863 loc) · 42.3 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System.Collections;
using System.Globalization;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Resources;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;
using Microsoft.Extensions.Logging;
using Microsoft.PowerApps.TestEngine.Config;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using MethodBody = Mono.Cecil.Cil.MethodBody;
using ModuleDefinition = Mono.Cecil.ModuleDefinition;
using TypeDefinition = Mono.Cecil.TypeDefinition;
using TypeReference = Mono.Cecil.TypeReference;
namespace Microsoft.PowerApps.TestEngine.Modules
{
/// <summary>
/// Check that references, types and called methods are allowed or denied
/// The assembly to be checked is not loaded into the AppDomain is is loaded with definition only for checks
/// </summary>
public class TestEngineExtensionChecker
{
ILogger _logger;
public Func<string, byte[]> GetExtentionContents = (file) => File.ReadAllBytes(file);
public const string NAMESPACE_PREVIEW = "Preview";
public const string NAMESPACE_TEST_ENGINE = "TestEngine";
public const string NAMESPACE_DEPRECATED = "Deprecated";
public const string SELFREFERENCE_NAMESPACE = "<module>";
private static readonly HashSet<string> AllowedNamespaces = InitializeAllowedNamespaces();
private static HashSet<string> InitializeAllowedNamespaces()
{
var allowedNamespaces = new HashSet<string>();
var resourceManager = new ResourceManager(typeof(NamespaceResource));
var resourceSet = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
allowedNamespaces.Add(entry.Value.ToString());
}
return allowedNamespaces;
}
public TestEngineExtensionChecker()
{
}
public TestEngineExtensionChecker(ILogger logger)
{
_logger = logger;
}
public ILogger Logger
{
get
{
return _logger;
}
set
{
_logger = value;
}
}
public Func<bool> CheckCertificates = () => VerifyCertificates();
/// <summary>
/// Verify that the provided file is signed by a trusted X509 root certificate authentication provider and the certificate is still valid
/// </summary>
/// <param name="settings">The test settings that should be evaluated</param>
/// <param name="file">The .Net Assembly file to validate</param>
/// <returns><c>True</c> if the assembly can be verified, <c>False</c> if not</returns>
public virtual bool Verify(TestSettingExtensions settings, string file)
{
if (!CheckCertificates())
{
return true;
}
var cert = X509Certificate.CreateFromSignedFile(file);
var cert2 = new X509Certificate2(cert.GetRawCertData());
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
var valid = true;
chain.Build(cert2);
var sources = GetTrustedSources(settings);
var allowUntrustedRoot = false;
#if RELEASE
//dont allow untrusted
#else
if (settings.Parameters.ContainsKey("AllowUntrustedRoot"))
{
allowUntrustedRoot = bool.Parse(settings.Parameters["AllowUntrustedRoot"]);
}
#endif
foreach (var elem in chain.ChainElements)
{
foreach (var status in elem.ChainElementStatus)
{
if (status.Status == X509ChainStatusFlags.UntrustedRoot && allowUntrustedRoot)
{
continue;
}
valid = false;
}
}
// Check if the chain of certificates is valid
if (!valid)
{
return false;
}
// Check for valid trust sources
foreach (var elem in chain.ChainElements)
{
foreach (var source in sources)
{
if (!string.IsNullOrEmpty(source.Name) && elem.Certificate.IssuerName.Name.IndexOf($"CN={source.Name}") == -1)
{
continue;
}
if (!string.IsNullOrEmpty(source.Organization) && elem.Certificate.IssuerName.Name.IndexOf($"O={source.Organization}") == -1)
{
continue;
}
if (!string.IsNullOrEmpty(source.Location) && elem.Certificate.IssuerName.Name.IndexOf($"L={source.Location}") == -1)
{
continue;
}
if (!string.IsNullOrEmpty(source.State) && elem.Certificate.IssuerName.Name.IndexOf($"S={source.State}") == -1)
{
continue;
}
if (!string.IsNullOrEmpty(source.Country) && elem.Certificate.IssuerName.Name.IndexOf($"C={source.Country}") == -1)
{
continue;
}
if (!string.IsNullOrEmpty(source.Thumbprint) && elem.Certificate.Thumbprint != source.Thumbprint)
{
continue;
}
// Found a trusted source
return true;
}
}
return false;
}
private static bool VerifyCertificates()
{
#if RELEASE
return true;
#else
return false;
#endif
}
private List<TestEngineTrustSource> GetTrustedSources(TestSettingExtensions settings)
{
var sources = new List<TestEngineTrustSource>();
sources.Add(new TestEngineTrustSource()
{
Name = "Microsoft Root Certificate Authority",
Organization = "Microsoft Corporation",
Location = "Redmond",
State = "Washington",
Country = "US",
Thumbprint = "8F43288AD272F3103B6FB1428485EA3014C0BCFE"
});
if (settings.Parameters.ContainsKey("TrustedSource"))
{
var parts = settings.Parameters["TrustedSource"].Split(',');
var name = string.Empty;
var organization = string.Empty;
var location = string.Empty;
var state = string.Empty;
var country = string.Empty;
var thumbprint = string.Empty;
foreach (var part in parts)
{
var nameValue = part.Trim().Split('=');
switch (nameValue[0])
{
case "CN":
name = nameValue[1];
break;
case "O":
organization = nameValue[1];
break;
case "L":
location = nameValue[1];
break;
case "S":
state = nameValue[1];
break;
case "C":
country = nameValue[1];
break;
case "T":
thumbprint = nameValue[1];
break;
}
}
if (!string.IsNullOrEmpty(name))
{
sources.Add(new TestEngineTrustSource()
{
Name = name,
Organization = organization,
Location = location,
State = state,
Country = country,
Thumbprint = thumbprint
});
}
}
return sources;
}
/// <summary>
/// Validate that the provided provider file is allowed or should be denied based on the test settings
/// </summary>
/// <param name="settings">The test settings that should be evaluated</param>
/// <param name="file">The .Net Assembly file to validate</param>
/// <returns><c>True</c> if the assembly meets the test setting requirements, <c>False</c> if not</returns>
public virtual bool ValidateProvider(TestSettingExtensions settings, string file)
{
byte[] contents = GetExtentionContents(file);
return VerifyContainsValidNamespacePowerFxFunctions(settings, contents);
}
/// <summary>
/// Validate that the provided file is allowed or should be denied based on the test settings
/// </summary>
/// <param name="settings">The test settings that should be evaluated</param>
/// <param name="file">The .Net Assembly file to validate</param>
/// <returns><c>True</c> if the assembly meets the test setting requirements, <c>False</c> if not</returns>
public virtual bool Validate(TestSettingExtensions settings, string file)
{
var allowList = new HashSet<string>(settings.AllowNamespaces);
allowList.UnionWith(AllowedNamespaces);
var denyList = new HashSet<string>(settings.DenyNamespaces)
{
"Microsoft.PowerApps.TestEngine.Modules.",
};
byte[] contents = GetExtentionContents(file);
//ignore generic types
var found = LoadTypes(contents).Where(item => !item.StartsWith("!")).ToList();
var valid = true;
if (!VerifyContainsValidNamespacePowerFxFunctions(settings, contents))
{
Logger.LogInformation("Invalid Power FX Namespace");
valid = false;
return valid;
}
foreach (var item in found)
{
// Allow if what was found is shorter and starts with allow value or what was found is a subset of a more specific allow rule
var allowLongest = allowList.Where(a => item.StartsWith(a) || (item.Length < a.Length && a.StartsWith(item))).OrderByDescending(a => a.Length).FirstOrDefault();
var denyLongest = denyList.Where(d => item.StartsWith(d)).OrderByDescending(d => d.Length).FirstOrDefault();
var allow = !String.IsNullOrEmpty(allowLongest);
var deny = !String.IsNullOrEmpty(denyLongest);
if (allow && deny && denyLongest?.Length > allowLongest?.Length || !allow)
{
_logger.LogInformation("Deny usage of " + item);
_logger.LogInformation("Allow rule " + allowLongest);
_logger.LogInformation("Deny rule " + denyLongest);
valid = false;
break;
}
}
return valid;
}
/// <summary>
/// Validate that the function only contains PowerFx functions that belong to valid Power Fx namespaces
/// </summary>
/// <param name="settings"></param>
/// <param name="assembly"></param>
/// <returns></returns>
public bool VerifyContainsValidNamespacePowerFxFunctions(TestSettingExtensions settings, byte[] assembly)
{
var isValid = true;
#if RELEASE
// Add Deprecated namespaces in Release compile if it has not been added in deny list
if (!settings.DenyPowerFxNamespaces.Contains(NAMESPACE_DEPRECATED))
{
settings.DenyPowerFxNamespaces.Add(NAMESPACE_DEPRECATED);
}
#endif
using (var stream = new MemoryStream(assembly))
{
stream.Position = 0;
ModuleDefinition module = ModuleDefinition.ReadModule(stream);
// Detect if this assembly contains provider types so we can allow Preview for provider assemblies
var assemblyHasProvider = module.GetAllTypes().Any(t =>
t.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Providers.ITestWebProvider).FullName) ||
t.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Users.IUserManager).FullName) ||
t.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Config.IUserCertificateProvider).FullName)
);
// Check if PauseModule exists and inspect its IsPreviewNamespaceEnabled property
var pauseModule = module.Types.FirstOrDefault(t => t.Name == "PauseModule");
if (pauseModule != null)
{
// Check if the PauseModule has IsPreviewNamespaceEnabled property
var previewProperty = pauseModule.Properties.FirstOrDefault(p => p.Name == "IsPreviewNamespaceEnabled");
if (previewProperty != null)
{
// Do not modify the global settings here. Instead record that PauseModule exposes the preview toggle.
// The property's value will be determined at runtime based on YAML settings; use the flag to
// selectively allow the Preview namespace for providers only.
Logger?.LogInformation("Detected PauseModule.IsPreviewNamespaceEnabled; preview semantics will be applied per-type.");
}
}
// Get the source code of the assembly as will be used to check Power FX Namespaces
var code = DecompileModuleToCSharp(assembly);
foreach (TypeDefinition type in module.GetAllTypes())
{
// Provider checks are based on Namespaces string[] property
if (
type.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Providers.ITestWebProvider).FullName)
||
type.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Users.IUserManager).FullName)
||
type.Interfaces.Any(i => i.InterfaceType.FullName == typeof(Config.IUserCertificateProvider).FullName)
)
{
if (CheckPropertyArrayContainsValue(type, "Namespaces", out var values))
{
// For provider types, always allow Preview namespace (preview namespace checks apply to actions only)
var allowedForProvider = settings.AllowPowerFxNamespaces.ToList();
if (!allowedForProvider.Contains(NAMESPACE_PREVIEW))
{
allowedForProvider.Add(NAMESPACE_PREVIEW);
}
foreach (var name in values)
{
// Check against deny list using regular expressions
if (settings.DenyPowerFxNamespaces.Any(pattern => Regex.IsMatch(name, WildcardToRegex(pattern))))
{
Logger.LogInformation($"Deny Power FX Namespace {name} for {type.Name}");
return false;
}
// Check against deny wildcard and allow list using regular expressions
if (settings.DenyPowerFxNamespaces.Any(pattern => pattern == "*") &&
(!allowedForProvider.Any(pattern => Regex.IsMatch(name, WildcardToRegex(pattern))) &&
name != NAMESPACE_TEST_ENGINE))
{
Logger.LogInformation($"Deny Power FX Namespace {name} for {type.Name}");
return false;
}
// Check against allow list using regular expressions
if (!allowedForProvider.Any(pattern => Regex.IsMatch(name, WildcardToRegex(pattern))) &&
name != NAMESPACE_TEST_ENGINE)
{
Logger.LogInformation($"Not allow Power FX Namespace {name} for {type.Name}");
return false;
}
}
}
}
// Extension Module Check are based on constructor
if (type.BaseType != null && type.BaseType.Name == "ReflectionFunction")
{
// Special handling for PauseFunction - allow root namespace when PauseModule is present
if (type.Name == "PauseFunction" && pauseModule != null)
{
Logger?.LogInformation($"Allowing PauseFunction in root namespace due to PauseModule presence.");
continue; // Skip namespace validation for PauseFunction
}
var constructors = type.GetConstructors();
if (constructors.Count() == 0)
{
Logger.LogInformation($"No constructor defined for {type.Name}. Found {constructors.Count()} expected 1 or more");
return false;
}
var constructor = constructors.Where(c => c.HasBody).FirstOrDefault();
if (constructor == null)
{
Logger.LogInformation($"No constructor with a body");
}
if (!constructor.HasBody)
{
Logger.LogInformation($"No body defined for {type.Name}");
// Needs body for call to base constructor
return false;
}
var baseCall = constructor.Body.Instructions?.FirstOrDefault(i => i.OpCode == OpCodes.Call && i.Operand is MethodReference && ((MethodReference)i.Operand).Name == ".ctor");
if (baseCall == null)
{
Logger.LogInformation($"No base constructor defined for {type.Name}");
// Unable to find base constructor call
return false;
}
MethodReference baseConstructor = (MethodReference)baseCall.Operand;
if (baseConstructor.Parameters?.Count() < 2)
{
// Not enough parameters
Logger.LogInformation($"No not enough parameters for {type.Name}");
return false;
}
if (baseConstructor.Parameters[0].ParameterType.FullName != "Microsoft.PowerFx.Core.Utils.DPath")
{
// First argument should be Namespace
Logger.LogInformation($"No Power FX Namespace for {type.Name}");
return false;
}
// Use the decompiled code to get the values of the base constructor, specifically look for the namespace
var name = GetPowerFxNamespace(type.Name, code);
if (string.IsNullOrEmpty(name))
{
// No Power FX Namespace found
Logger.LogInformation($"No Power FX Namespace found for {type.Name}");
return false;
}
// For functions defined in assemblies that are providers, allow Preview namespace
var allowedForFunction = settings.AllowPowerFxNamespaces.ToList();
if (assemblyHasProvider && !allowedForFunction.Contains(NAMESPACE_PREVIEW))
{
allowedForFunction.Add(NAMESPACE_PREVIEW);
}
if (settings.DenyPowerFxNamespaces.Contains(name))
{
// Deny list match
Logger.LogInformation($"Deny Power FX Namespace {name} for {type.Name}");
return false;
}
if ((settings.DenyPowerFxNamespaces.Contains("*") && (
!allowedForFunction.Contains(name) ||
(!allowedForFunction.Contains(name) && name != NAMESPACE_TEST_ENGINE)
)
))
{
// Deny wildcard exists only. Could not find match in allow list and name was not reserved name TestEngine
Logger.LogInformation($"Deny Power FX Namespace {name} for {type.Name}");
return false;
}
if (!allowedForFunction.Contains(name) && name != NAMESPACE_TEST_ENGINE)
{
Logger.LogInformation($"Do not allow Power FX Namespace {name} for {type.Name}");
// Not in allow list or the Reserved TestEngine namespace
return false;
}
}
// Special validation for ReflectionAction types. Actions must not declare the Preview namespace
if (type.BaseType != null && type.BaseType.Name == "ReflectionAction")
{
// If PauseModule is present, allow certain actions to be declared in the root namespace (skip namespace validation)
if (pauseModule != null)
{
// Check configured allow-list of action class names/wildcards
var allowActions = settings.AllowActionsInRoot ?? new HashSet<string>();
var isAllowedAction = allowActions.Any(pattern => Regex.IsMatch(type.Name, WildcardToRegex(pattern)));
if (isAllowedAction)
{
Logger?.LogInformation($"Allowing action {type.Name} in root namespace due to PauseModule presence and AllowActionsInRoot setting.");
continue; // Skip namespace validation for this action
}
}
var constructors = type.GetConstructors();
if (constructors.Count() == 0)
{
Logger.LogInformation($"No constructor defined for {type.Name}. Found {constructors.Count()} expected 1 or more");
return false;
}
var constructor = constructors.Where(c => c.HasBody).FirstOrDefault();
if (constructor == null || !constructor.HasBody)
{
Logger.LogInformation($"No constructor body defined for {type.Name}");
return false;
}
var baseCall = constructor.Body.Instructions?.FirstOrDefault(i => i.OpCode == OpCodes.Call && i.Operand is MethodReference && ((MethodReference)i.Operand).Name == ".ctor");
if (baseCall == null)
{
Logger.LogInformation($"No base constructor defined for {type.Name}");
return false;
}
MethodReference baseConstructor = (MethodReference)baseCall.Operand;
if (baseConstructor.Parameters?.Count() < 2)
{
Logger.LogInformation($"No not enough parameters for {type.Name}");
return false;
}
if (baseConstructor.Parameters[0].ParameterType.FullName != "Microsoft.PowerFx.Core.Utils.DPath")
{
Logger.LogInformation($"No Power FX Namespace for {type.Name}");
return false;
}
// Extract namespace from decompiled source
var actionName = GetPowerFxNamespace(type.Name, code);
if (string.IsNullOrEmpty(actionName))
{
Logger.LogInformation($"No Power FX Namespace found for {type.Name}");
return false;
}
// Actions must not use the Preview namespace
if (string.Equals(actionName, NAMESPACE_PREVIEW, StringComparison.OrdinalIgnoreCase))
{
Logger.LogInformation($"Deny Preview Power FX Namespace {actionName} for action {type.Name}");
return false;
}
// Continue with the same allow/deny validation as functions
if (settings.DenyPowerFxNamespaces.Contains(actionName))
{
Logger.LogInformation($"Deny Power FX Namespace {actionName} for {type.Name}");
return false;
}
if ((settings.DenyPowerFxNamespaces.Contains("*") && (
!settings.AllowPowerFxNamespaces.Contains(actionName) ||
(!settings.AllowPowerFxNamespaces.Contains(actionName) && actionName != NAMESPACE_TEST_ENGINE)
)
))
{
Logger.LogInformation($"Deny Power FX Namespace {actionName} for {type.Name}");
return false;
}
if (!settings.AllowPowerFxNamespaces.Contains(actionName) && actionName != NAMESPACE_TEST_ENGINE)
{
Logger.LogInformation($"Do not allow Power FX Namespace {actionName} for {type.Name}");
return false;
}
}
}
}
return isValid;
}
// Helper method to convert wildcard patterns to regular expressions
private string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
}
private bool CheckPropertyArrayContainsValue(TypeDefinition typeDefinition, string propertyName, out string[] values)
{
values = null;
// Find the property by name
var property = typeDefinition.HasProperties ? typeDefinition.Properties.FirstOrDefault(p => p.Name == propertyName) : null;
if (property == null)
{
return false;
}
// Get the property type and check if it's an array
var propertyType = property.PropertyType as ArrayType;
if (propertyType == null)
{
return false;
}
// Assuming the property has a getter method
var getMethod = property.GetMethod;
if (getMethod == null)
{
return false;
}
// Load the assembly and get the method body
var methodBody = getMethod.Body;
if (methodBody == null)
{
return false;
}
// Iterate through the instructions to find the array initialization
foreach (var instruction in methodBody?.Instructions)
{
if (instruction.OpCode == OpCodes.Newarr)
{
// Call the method to get array values
var arrayValues = GetArrayValuesFromInstruction(methodBody, instruction);
values = arrayValues.OfType<string>().ToArray(); // Ensure values are strings
return values.Length > 0;
}
}
return false;
}
private object[] GetArrayValuesFromInstruction(MethodBody methodBody, Instruction newarrInstruction)
{
var values = new List<object>();
var instructions = methodBody?.Instructions;
int index = instructions?.IndexOf(newarrInstruction) ?? 0;
// Iterate through the instructions following the 'newarr' instruction
for (int i = index + 1; i < instructions?.Count; i++)
{
var instruction = instructions[i];
// Look for instructions that store values in the array
if (instruction.OpCode == OpCodes.Stelem_Ref ||
instruction.OpCode == OpCodes.Stelem_I4 ||
instruction.OpCode == OpCodes.Stelem_R4 ||
instruction.OpCode == OpCodes.Stelem_R8)
{
// The value to be stored is usually pushed onto the stack before the Stelem instruction
var valueInstruction = instructions[i - 1];
// Extract the value based on the opcode
switch (valueInstruction.OpCode.Code)
{
case Code.Ldc_I4:
values.Add((int)valueInstruction.Operand);
break;
case Code.Ldc_R4:
values.Add((float)valueInstruction.Operand);
break;
case Code.Ldc_R8:
values.Add((double)valueInstruction.Operand);
break;
case Code.Ldstr:
values.Add((string)valueInstruction.Operand);
break;
// Add more cases as needed for other types
}
}
// Stop if we reach another array initialization or method end
if (instruction.OpCode == OpCodes.Newarr || instruction.OpCode == OpCodes.Ret)
{
break;
}
}
return values.ToArray();
}
/// <summary>
/// Get the declared Power FX Namespace assigned to a Power FX Reflection function
/// </summary>
/// <param name="name">The name of the ReflectionFunction to find</param>
/// <param name="code">The decompiled source code to search</param>
/// <returns>The DPath Name that has been declared from the code</returns>
private string GetPowerFxNamespace(string name, string code)
{
/*
It is assumed that the code will be formatted like the following examples
public FooFunction()
: base(DPath.Root.Append(new DName("Foo")), "Foo", FormulaType.Blank) {
}
or
public OtherFunction(int start)
: base(DPath.Root.Append(new DName("Other")), "Foo", FormulaType.Blank) {
}
*/
var lines = code.Split('\n').ToList();
var match = lines.Where(l => l.Contains($"public {name}(")).FirstOrDefault();
if (match == null)
{
return String.Empty;
}
var index = lines.IndexOf(match);
// Search for a DName that is Appended to the Root path as functions should be in a Power FX Namespace not the Root
var baseDeclaration = "base(DPath.Root.Append(new DName(\"";
// Search for the DName
var declaration = lines[index + 1].IndexOf(baseDeclaration);
if (declaration >= 0)
{
// Found a match
var start = declaration + baseDeclaration.Length;
var end = lines[index + 1].IndexOf("\"", start);
// Extract the Power FX Namespace argument from the declaration
return lines[index + 1].Substring(declaration + baseDeclaration.Length, end - start);
}
return String.Empty;
}
private string DecompileModuleToCSharp(byte[] assembly)
{
var fileName = "module.dll";
using (var module = new MemoryStream(assembly))
using (var peFile = new PEFile(fileName, module))
using (var writer = new StringWriter())
{
var decompilerSettings = new DecompilerSettings()
{
ThrowOnAssemblyResolveErrors = false,
DecompileMemberBodies = true,
UsingDeclarations = true
};
decompilerSettings.CSharpFormattingOptions.ConstructorBraceStyle = ICSharpCode.Decompiler.CSharp.OutputVisitor.BraceStyle.EndOfLine;
var resolver = new UniversalAssemblyResolver(this.GetType().Assembly.Location, decompilerSettings.ThrowOnAssemblyResolveErrors,
peFile.DetectTargetFrameworkId(), peFile.DetectRuntimePack(),
decompilerSettings.LoadInMemory ? PEStreamOptions.PrefetchMetadata : PEStreamOptions.Default,
decompilerSettings.ApplyWindowsRuntimeProjections ? MetadataReaderOptions.ApplyWindowsRuntimeProjections : MetadataReaderOptions.None);
var decompiler = new CSharpDecompiler(peFile, resolver, decompilerSettings);
return decompiler.DecompileWholeModuleAsString();
}
}
/// <summary>
/// Load all the types from the assembly using Intermediate Language (IL) mode only
/// </summary>
/// <param name="assembly">The byte representation of the assembly</param>
/// <returns>The Dependencies, Types and Method calls found in the assembly</returns>
private List<string> LoadTypes(byte[] assembly)
{
List<string> found = new List<string>();
using (var stream = new MemoryStream(assembly))
{
stream.Position = 0;
ModuleDefinition module = ModuleDefinition.ReadModule(stream);
// Add each assembly reference
foreach (var reference in module.AssemblyReferences)
{
if (!found.Contains(reference.Name))
{
found.Add(reference.Name);
}
}
foreach (TypeDefinition type in module.GetAllTypes())
{
//ignoring self reference additional ignore checks for specialcases might be needed
if (!type.Name.ToLower().Equals(SELFREFERENCE_NAMESPACE))
{
AddType(type, found);
}
// Load each constructor parameter and types in the body
foreach (var constructor in type.GetConstructors())
{
if (constructor.HasParameters)
{
LoadParametersTypes(constructor.Parameters, found);
}
if (constructor.HasBody)
{
LoadMethodBodyTypes(constructor.Body, found);
}
}
// Load any fields
foreach (var field in type.Fields)
{
if (found.Contains(field.FieldType.FullName) && !field.FieldType.IsValueType)
{
found.Add(field.FieldType.FullName);
}
}
// ... properties with get/set body if they exist
foreach (var property in type.Properties)
{
if (found.Contains(property.PropertyType.FullName) && !property.PropertyType.IsValueType)
{
found.Add(property.PropertyType.FullName);
}
if (property.GetMethod != null)
{
if (property.GetMethod.HasBody)
{
LoadMethodBodyTypes(property.GetMethod.Body, found);
}
}
if (property.SetMethod != null)
{
if (property.SetMethod.HasBody)
{
LoadMethodBodyTypes(property.SetMethod.Body, found);
}
}
}
// and method parameters and types in the method body
foreach (var method in type.Methods)
{
if (method.HasParameters)
{
LoadParametersTypes(method.Parameters, found);
}
if (method.HasBody)
{
LoadMethodBodyTypes(method.Body, found);
}
}
}
return found;
}
}
private void LoadParametersTypes(Mono.Collections.Generic.Collection<ParameterDefinition> paramInfo, List<string> found)
{
foreach (var parameter in paramInfo)
{
AddType(parameter.ParameterType.GetElementType(), found);
}
}
private void AddType(TypeReference type, List<string> found)
{
if (!found.Contains(type.FullName) && !type.IsPrimitive)
{
found.Add(type.FullName);
}
}
/// <summary>
/// Add method body instructions to the found list
/// </summary>
/// <param name="body">The body instructions to be searched</param>
/// <param name="found">The list of matching code found</param>
private void LoadMethodBodyTypes(MethodBody body, List<String> found)
{
foreach (var variable in body.Variables)
{
AddType(variable.VariableType.GetElementType(), found);
}
foreach (var instruction in body.Instructions)
{
switch (instruction.OpCode.FlowControl)
{
case FlowControl.Call:
var methodInfo = (IMethodSignature)instruction.Operand;
AddType(methodInfo.ReturnType, found);
var name = methodInfo.ToString();
if (name.IndexOf(" ") > 0)
{
// Remove the return type from the call definition
name = name.Substring(name.IndexOf(" ") + 1);
var start = name.IndexOf("(");
var args = name.Substring(start + 1, name.Length - start - 2).Split(',');
if (args.Length >= 1 && !string.IsNullOrEmpty(args[0]))
{
name = name.Substring(0, start) + GetArgs(args, instruction);
}
}
if (!found.Contains(name))
{
found.Add(name);
}
break;
}
}
}
/// <summary>
/// Convert call arguments into values
/// </summary>
/// <param name="args">The arguments to be converted</param>
/// <param name="instruction">The call instruction that the arguments relate to</param>
/// <returns>The call text with primative values or argument types</returns>
private string GetArgs(string[] args, Instruction instruction)
{
StringBuilder result = new StringBuilder("(");
for (var i = 0; i < args.Length; i++)
{
var argValue = GetCallArgument(i, args.Length, instruction);
switch (args[i])
{
case "System.String":
if (argValue.OpCode.Code == Code.Ldstr)
{
result.Append("\"");
result.Append(argValue.Operand.ToString());
result.Append("\"");
}
else
{
result.Append(args[i]);
}
break;
default:
result.Append(args[i]);
break;
}
if (i != args.Length - 1)
{
result.Append(",");
}
}
result.Append(")");
return result.ToString();
}
/// <summary>
/// Get an argument for a method. They should be the nth intruction loaded before the method call
/// </summary>
/// <param name="index">The argument instruction to load</param>
/// <param name="argCount">The total number of arguments</param>
/// <param name="instruction">The call instruction</param>
/// <returns></returns>
private Instruction GetCallArgument(int index, int argCount, Instruction instruction)
{
Instruction current = instruction;
while (index < argCount)
{
current = current.Previous;
index++;
}
return current;
}
}
}