-
Notifications
You must be signed in to change notification settings - Fork 292
/
Tasks.cs
1524 lines (1439 loc) · 72 KB
/
Tasks.cs
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) Ping Castle. All rights reserved.
// https://www.pingcastle.com
//
// Licensed under the Non-Profit OSL. See LICENSE file in the project root for full license information.
//
using PingCastle.Data;
using PingCastle.Exports;
using PingCastle.Healthcheck;
using PingCastle.misc;
using PingCastle.Report;
using PingCastle.Rules;
using PingCastle.Scanners;
using PingCastle.Cloud.Credentials;
using PingCastle.Cloud.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using TinyJson;
using System.Xml.Serialization;
using System.Xml;
using System.Net.Http;
namespace PingCastle
{
public class Tasks
{
public ADHealthCheckingLicense License { get; set; }
public NetworkCredential Credential = null;
public List<string> NodesToInvestigate = new List<string>();
public PingCastleReportDataExportLevel ExportLevel = PingCastleReportDataExportLevel.Normal;
Dictionary<string, string> xmlreports = new Dictionary<string, string>();
Dictionary<string, string> htmlreports = new Dictionary<string, string>();
Dictionary<string, DateTime> dateReports = new Dictionary<string, DateTime>();
Dictionary<string, string> aadjsonreport = new Dictionary<string, string>();
Dictionary<string, string> aadhtmlreport = new Dictionary<string, string>();
private RuntimeSettings Settings;
public Tasks(RuntimeSettings settings)
{
Settings = settings;
}
internal static void EnableLogFile()
{
Trace.AutoFlush = true;
TextWriterTraceListener listener = new TextWriterTraceListener("trace.log");
Trace.Listeners.Add(listener);
PingCastle.Cloud.Common.HttpClientHelper.EnableLoging(new PingCastle.Cloud.Logs.SazGenerator());
}
public bool GenerateKeyTask()
{
return StartTask("Generate Key",
() =>
{
HealthCheckEncryption.GenerateRSAKey();
});
}
public bool GenerateAzureADKeyTask()
{
return StartTask("Generate AzureAD Key",
() =>
{
Console.WriteLine("Go to portal.azure.com");
Console.WriteLine("Open Azure Active Directory");
Console.WriteLine("Go to App registrations");
Console.WriteLine("Select new registration and create an app.");
Console.WriteLine("Go to Certificates & secrets and select certificates");
Console.WriteLine("upload the .cer file generated");
Console.WriteLine("");
Console.WriteLine("Go to Roles adn administrators");
Console.WriteLine("Select the role Global Reader");
Console.WriteLine("Click on Add assignments and add the previously created account");
Console.WriteLine("Make sure the App registration is listed on Assignments before leaving");
var tenant = "pingcastle.com";
PingCastle.Cloud.Credentials.CertificateBuilder.GenerateAzureADCertificate(tenant, "vletoux", DateTime.Now.AddYears(2));
return;
//CertificateBuilder.GenerateAzureADCertificate("pingcatle.c
});
}
public bool ScannerTask()
{
return StartTask("Scanner",
() =>
{
PropertyInfo pi = Settings.Scanner.GetProperty("Name");
IScanner scanner = PingCastleFactory.LoadScanner(Settings.Scanner);
string name = pi.GetValue(scanner, null) as string;
DisplayAdvancement("Running scanner " + name);
scanner.Initialize(Settings);
if (scanner.QueryForAdditionalParameterInInteractiveMode() != DisplayState.Run)
return;
string file = "ad_scanner_" + name + "_" + Settings.Server + ".txt";
scanner.Export(file);
DisplayAdvancement("Results saved to " + new FileInfo(file).FullName);
}
);
}
public bool CartoTask()
{
return CartoTask(false);
}
public bool CartoTask(bool PerformHealthCheckGenerateDemoReports = false)
{
List<HealthcheckAnalyzer.ReachableDomainInfo> domains = null;
StartTask("Exploration",
() =>
{
HealthcheckAnalyzer hcroot = new HealthcheckAnalyzer();
hcroot.limitHoneyPot = string.IsNullOrEmpty(License.Edition);
domains = hcroot.GetAllReachableDomains(Settings.Port, Settings.Credential);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("List of domains that will be queried");
Console.ResetColor();
foreach (var domain in domains)
{
Console.WriteLine(domain.domain);
}
});
var consolidation = new PingCastleReportCollection<HealthcheckData>();
StartTask("Examining all domains in parallele (this can take a few minutes)",
() =>
{
BlockingQueue<string> queue = new BlockingQueue<string>(30);
int numberOfThread = 100;
Thread[] threads = new Thread[numberOfThread];
try
{
ThreadStart threadFunction = () =>
{
for (; ; )
{
string domain = null;
if (!queue.Dequeue(out domain)) break;
try
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] " + "Starting the analysis of " + domain);
HealthcheckAnalyzer hc = new HealthcheckAnalyzer();
hc.limitHoneyPot = string.IsNullOrEmpty(License.Edition);
var data = hc.GenerateCartoReport(domain, Settings.Port, Settings.Credential, Settings.AnalyzeReachableDomains);
consolidation.Add(data);
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] " + "Analysis of " + domain + " completed with success");
}
catch (Exception ex)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] " + "Analysis of " + domain + " failed");
Trace.WriteLine("Exception while analysing domain " + domain + " : " + ex.Message);
Trace.WriteLine(ex.StackTrace);
}
}
};
// Consumers
for (int i = 0; i < numberOfThread; i++)
{
threads[i] = new Thread(threadFunction);
threads[i].Start();
}
foreach (var domain in domains)
{
queue.Enqueue(domain.domain);
}
queue.Quit();
Trace.WriteLine("examining domains file completed. Waiting for worker thread to complete");
for (int i = 0; i < numberOfThread; i++)
{
threads[i].Join();
}
Trace.WriteLine("Done examining domains");
}
catch (Exception ex)
{
Trace.WriteLine("Exception while analysing domain in carto: " + ex.Message);
Trace.WriteLine(ex.StackTrace);
}
finally
{
queue.Quit();
for (int i = 0; i < numberOfThread; i++)
{
if (threads[i] != null)
if (threads[i].ThreadState == System.Threading.ThreadState.Running)
threads[i].Abort();
}
}
});
if (PerformHealthCheckGenerateDemoReports)
{
Console.WriteLine("Performing demo report transformation");
Trace.WriteLine("Performing demo report transformation");
consolidation = PingCastleReportHelper<HealthcheckData>.TransformReportsToDemo(consolidation);
}
if (!StartTask("Healthcheck consolidation",
() =>
{
consolidation.EnrichInformation();
ReportHealthCheckMapBuilder nodeAnalyzer = new ReportHealthCheckMapBuilder(consolidation, License);
nodeAnalyzer.Log = Console.WriteLine;
nodeAnalyzer.CenterDomainForSimpliedGraph = Settings.CenterDomainForSimpliedGraph;
nodeAnalyzer.GenerateReportFile("ad_carto_full_node_map.html");
nodeAnalyzer.FullNodeMap = false;
nodeAnalyzer.CenterDomainForSimpliedGraph = Settings.CenterDomainForSimpliedGraph;
nodeAnalyzer.GenerateReportFile("ad_carto_simple_node_map.html");
}
)) return false;
return true;
}
public bool AnalysisTask<T>() where T : IPingCastleReport
{
if (!string.IsNullOrEmpty(Settings.apiEndpoint) && !string.IsNullOrEmpty(Settings.apiKey))
{
var ret = RetrieveSettingsViaAPI();
if (!ret)
return false;
}
string[] servers = Settings.Server.Split(',');
foreach (string server in servers)
{
AnalysisTask<T>(server);
}
return true;
}
public bool CompleteTasks()
{
if (!string.IsNullOrEmpty(Settings.sendXmlTo))
SendEmail(Settings.sendXmlTo, true, false);
if (!string.IsNullOrEmpty(Settings.sendHtmlTo))
SendEmail(Settings.sendHtmlTo, false, true);
if (!string.IsNullOrEmpty(Settings.sendAllTo))
SendEmail(Settings.sendAllTo, true, true);
if (!string.IsNullOrEmpty(Settings.sharepointdirectory))
{
// TODO: remove this functionality (unused ?) or add AAD support
foreach (string domain in xmlreports.Keys)
{
UploadToWebsite(HealthcheckData.GetMachineReadableFileName(domain, dateReports.ContainsKey(domain) ? dateReports[domain] : DateTime.Now), xmlreports[domain]);
}
}
if (!String.IsNullOrEmpty(Settings.apiKey) && !String.IsNullOrEmpty(Settings.apiEndpoint))
SendViaAPI(xmlreports, aadjsonreport);
return true;
}
public bool GenerateFakeReport()
{
return StartTask("Generate fake reports",
() =>
{
var fakegenerator = new FakeHealthCheckDataGenerator();
var hcconso = fakegenerator.GenerateData();
foreach (var pingCastleReport in hcconso)
{
var enduserReportGenerator = new ReportHealthCheckSingle();
enduserReportGenerator.GenerateReportFile(pingCastleReport, License, pingCastleReport.GetHumanReadableFileName());
DisplayAdvancement("Export level is " + ExportLevel);
if (ExportLevel != PingCastleReportDataExportLevel.Full)
{
DisplayAdvancement("Personal data will NOT be included in the .xml file (add --level Full to add it. Ex: PingCastle.exe --interactive --level Full)");
}
pingCastleReport.SetExportLevel(ExportLevel);
DataHelper<HealthcheckData>.SaveAsXml(pingCastleReport, pingCastleReport.GetMachineReadableFileName(), Settings.EncryptReport);
}
var reportConso = new ReportHealthCheckConsolidation();
reportConso.GenerateReportFile(hcconso, License, "ad_hc_summary.html");
ReportHealthCheckMapBuilder nodeAnalyzer = new ReportHealthCheckMapBuilder(hcconso, License);
nodeAnalyzer.Log = Console.WriteLine;
nodeAnalyzer.GenerateReportFile("ad_hc_summary_full_node_map.html");
nodeAnalyzer.FullNodeMap = false;
nodeAnalyzer.CenterDomainForSimpliedGraph = Settings.CenterDomainForSimpliedGraph;
nodeAnalyzer.GenerateReportFile("ad_hc_summary_simple_node_map.html");
var mapReport = new ReportNetworkMap();
mapReport.GenerateReportFile(hcconso, License, "ad_hc_hilbert_map.html");
}
);
}
public class ExportedRule
{
public string Type { get; set; }
public RiskRuleCategory Category { get; set; }
public string Description { get; set; }
public string Documentation { get; set; }
public int MaturityLevel { get; set; }
public RiskModelCategory Model { get; set; }
public string Rationale { get; set; }
public string ReportLocation { get; set; }
public string RiskId { get; set; }
//public List<RuleComputationAttribute> RuleComputation { get; set; }
public string Solution { get; set; }
public string TechnicalExplanation { get; set; }
public string Title { get; set; }
}
public bool GenerateRuleList()
{
return StartTask("Export rules",
() =>
{
var rules = new List<ExportedRule>();
foreach (var r in PingCastle.Rules.RuleSet<HealthcheckData>.Rules)
{
rules.Add(new ExportedRule()
{
Type = "Active Directory",
Category = r.Category,
Description = r.Description,
Documentation = r.Documentation,
MaturityLevel = r.MaturityLevel,
Model = r.Model,
Rationale = r.Rationale,
ReportLocation = r.ReportLocation,
RiskId = r.RiskId,
//RuleComputation = r.RuleComputation,
Solution = r.Solution,
TechnicalExplanation = r.TechnicalExplanation,
Title = r.Title,
});
}
foreach (var r in PingCastle.Rules.RuleSet<HealthCheckCloudData>.Rules)
{
rules.Add(new ExportedRule()
{
Type = "Azure AD",
Category = r.Category,
Description = r.Description,
Documentation = r.Documentation,
MaturityLevel = r.MaturityLevel,
Model = r.Model,
Rationale = r.Rationale,
ReportLocation = r.ReportLocation,
RiskId = r.RiskId,
//RuleComputation = r.RuleComputation,
Solution = r.Solution,
TechnicalExplanation = r.TechnicalExplanation,
Title = r.Title,
});
}
var xs = new XmlSerializer(typeof(List<ExportedRule>));
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
var nav = xmlDoc.CreateNavigator();
using (XmlWriter wr = nav.AppendChild())
using (var wr2 = new SafeXmlWriter(wr))
{
xs.Serialize(wr2, rules);
}
xmlDoc.Save("PingCastleRules.xml");
}
);
}
public bool AnalysisCheckTask<T>(string server)
{
return true;
}
public bool AnalysisTask<T>(string server) where T : IPingCastleReport
{
Trace.WriteLine("Working on " + server);
if (server == "*" && Settings.InteractiveMode)
{
Trace.WriteLine("Setting reachable domains to on because interactive + server = *");
Settings.AnalyzeReachableDomains = true;
}
if (server.Contains("*"))
{
List<string> domains = GetListOfDomainToExploreFromGenericName(server);
int i = 1;
foreach (var domain in domains)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("");
string display = "Starting the report for " + domain + " (" + i++ + "/" + domains.Count + ")";
Console.WriteLine(display);
Console.WriteLine(new String('=', display.Length));
Console.ResetColor();
PerformTheAnalysis(domain);
}
}
else
{
var data = PerformTheAnalysis(server);
var hcData = data as HealthcheckData;
// do additional exploration based on trust results ?
Trace.WriteLine("do additional exploration based on trust results ?");
if (hcData != null && (Settings.ExploreTerminalDomains || Settings.ExploreForestTrust))
{
Trace.WriteLine("ExploreTerminalDomains is " + Settings.ExploreTerminalDomains);
Trace.WriteLine("ExploreForestTrust is " + Settings.ExploreForestTrust);
if (hcData.Trusts != null)
{
List<string> domainToExamine = new List<string>();
foreach (var trust in hcData.Trusts)
{
Trace.WriteLine("Examining " + trust.TrustPartner + " for additional exploration");
string attributes = TrustAnalyzer.GetTrustAttribute(trust.TrustAttributes);
string direction = TrustAnalyzer.GetTrustDirection(trust.TrustDirection);
if (direction.Contains("Inbound") || direction.Contains("Disabled"))
continue;
if (attributes.Contains("Intra-Forest"))
continue;
// explore forest trust only if explore forest trust is set
if (attributes.Contains("Forest Trust"))
{
if (Settings.ExploreForestTrust)
{
if (!ShouldTheDomainBeNotExplored(trust.TrustPartner))
domainToExamine.Add(trust.TrustPartner);
else
Trace.WriteLine("Domain " + trust.TrustPartner + " not to explore (direct domain)");
if (trust.KnownDomains != null)
{
foreach (var di in trust.KnownDomains)
{
if (!ShouldTheDomainBeNotExplored(di.DnsName))
domainToExamine.Add(di.DnsName);
Trace.WriteLine("Domain " + di.DnsName + " not to explore (known domain)");
}
}
}
}
else
{
if (Settings.ExploreTerminalDomains)
{
if (!ShouldTheDomainBeNotExplored(trust.TrustPartner))
domainToExamine.Add(trust.TrustPartner);
else
Trace.WriteLine("Domain " + trust.TrustPartner + "not to explore (terminal domain)");
}
}
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("List of domains that will be queried");
Trace.WriteLine("List of domains that will be queried");
Console.ResetColor();
foreach (var domain in domainToExamine)
{
Console.WriteLine(domain);
Trace.WriteLine(domain);
}
Trace.WriteLine("End selection");
foreach (string domain in domainToExamine)
{
PerformTheAnalysis(domain);
}
}
}
Trace.WriteLine("done additional exploration");
return hcData != null;
}
return true;
}
private List<string> GetListOfDomainToExploreFromGenericName(string server)
{
List<string> domains = new List<string>();
StartTask("Exploration",
() =>
{
HealthcheckAnalyzer hcroot = new HealthcheckAnalyzer();
hcroot.limitHoneyPot = string.IsNullOrEmpty(License.Edition);
var reachableDomains = hcroot.GetAllReachableDomains(Settings.Port, Settings.Credential);
List<HealthcheckAnalyzer.ReachableDomainInfo> domainsfiltered = new List<HealthcheckAnalyzer.ReachableDomainInfo>();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("List of domains that will be queried");
Console.ResetColor();
foreach (var reachableDomain in reachableDomains)
{
if (compareStringWithWildcard(server, reachableDomain.domain) && !ShouldTheDomainBeNotExplored(reachableDomain.domain))
{
domains.Add(reachableDomain.domain);
Console.WriteLine(reachableDomain.domain);
}
}
});
return domains;
}
public static bool compareStringWithWildcard(string stringWithWildcard, string toCompare)
{
string regex = "^" + Regex.Escape(stringWithWildcard)
.Replace(@"\*", ".*")
.Replace(@"\?", ".")
+ "$";
return Regex.Match(toCompare, regex, RegexOptions.IgnoreCase).Success;
}
bool ShouldTheDomainBeNotExplored(string domainToCheck)
{
if (Settings.DomainToNotExplore == null)
return false;
foreach (string domain in Settings.DomainToNotExplore)
{
if (domainToCheck.Equals(domain, StringComparison.InvariantCultureIgnoreCase))
{
Trace.WriteLine("Domain " + domainToCheck + " is filtered");
return true;
}
}
return false;
}
HealthcheckData PerformTheAnalysis(string server)
{
HealthcheckData pingCastleReport = null;
bool status = StartTask("Perform analysis for " + server,
() =>
{
var analyzer = new HealthcheckAnalyzer();
analyzer.limitHoneyPot = string.IsNullOrEmpty(License.Edition);
pingCastleReport = analyzer.PerformAnalyze(new PingCastleAnalyzerParameters()
{
Server = server,
Port = Settings.Port,
Credential = Settings.Credential,
PerformExtendedTrustDiscovery = Settings.AnalyzeReachableDomains,
AdditionalNamesForDelegationAnalysis = NodesToInvestigate,
});
string domain = pingCastleReport.Domain.DomainName;
DisplayAdvancement("Generating html report");
var enduserReportGenerator = new ReportHealthCheckSingle();
htmlreports[domain] = enduserReportGenerator.GenerateReportFile(pingCastleReport, License, pingCastleReport.GetHumanReadableFileName());
DisplayAdvancement("Generating xml file for consolidation report" + (Settings.EncryptReport ? " (encrypted)" : ""));
DisplayAdvancement("Export level is " + ExportLevel);
if (ExportLevel != PingCastleReportDataExportLevel.Full)
{
DisplayAdvancement("Personal data will NOT be included in the .xml file (add --level Full to add it. Ex: PingCastle.exe --interactive --level Full)");
}
pingCastleReport.SetExportLevel(ExportLevel);
xmlreports[domain] = DataHelper<HealthcheckData>.SaveAsXml(pingCastleReport, pingCastleReport.GetMachineReadableFileName(), Settings.EncryptReport);
dateReports[domain] = pingCastleReport.GenerationDate;
DisplayAdvancement("Done");
});
return pingCastleReport;
}
public bool ConsolidationTask<T>() where T : IPingCastleReport
{
return StartTask("PingCastle report consolidation (" + typeof(T).Name + ")",
() =>
{
var consolidation = PingCastleReportHelper<T>.LoadXmls(Settings.InputDirectory, Settings.FilterReportDate);
if (consolidation.Count == 0)
{
WriteInRed("No report has been found. Please generate one with PingCastle and try again. The task will stop.");
return;
}
if (typeof(T) == typeof(HealthcheckData))
{
var hcconso = consolidation as PingCastleReportCollection<HealthcheckData>;
var report = new ReportHealthCheckConsolidation();
report.GenerateReportFile(hcconso, License, "ad_hc_summary.html");
ReportHealthCheckMapBuilder nodeAnalyzer = new ReportHealthCheckMapBuilder(hcconso, License);
nodeAnalyzer.Log = Console.WriteLine;
nodeAnalyzer.GenerateReportFile("ad_hc_summary_full_node_map.html");
nodeAnalyzer.FullNodeMap = false;
nodeAnalyzer.CenterDomainForSimpliedGraph = Settings.CenterDomainForSimpliedGraph;
nodeAnalyzer.GenerateReportFile("ad_hc_summary_simple_node_map.html");
var mapReport = new ReportNetworkMap();
mapReport.GenerateReportFile(hcconso, License, "ad_hc_hilbert_map.html");
}
}
);
}
public bool HealthCheckRulesTask()
{
return StartTask("PingCastle Health Check rules",
() =>
{
var rulesBuilder = new ReportHealthCheckRules();
rulesBuilder.GenerateReportFile("ad_hc_rules_list.html");
}
);
}
public bool RegenerateHtmlTask()
{
return StartTask("Regenerate html report",
() =>
{
var fi = new FileInfo(Settings.InputFile);
if (fi.Name.EndsWith(".json.gz", StringComparison.CurrentCultureIgnoreCase))
{
HealthCheckCloudData report;
using (var sr = File.OpenRead(Settings.InputFile))
{
if (fi.Name.EndsWith(".gz", StringComparison.OrdinalIgnoreCase))
{
using (var gz = new GZipStream(sr, CompressionMode.Decompress))
{
report = HealthCheckCloudData.LoadFromStream(gz);
}
}
else
{
report = HealthCheckCloudData.LoadFromStream(sr);
}
report.CheckIntegrity();
var reportGenerator = new ReportCloud();
reportGenerator.GenerateReportFile(report, License, "pingcastlecloud_" + report.TenantName + ".html");
}
}
else if (fi.Name.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase))
{
var healthcheckData = DataHelper<HealthcheckData>.LoadXml(Settings.InputFile);
if (healthcheckData.Level != PingCastleReportDataExportLevel.Full)
{
DisplayAdvancement("The xml report does not contain personal data. Current reporting level is: " + healthcheckData.Level);
}
var endUserReportGenerator = new ReportHealthCheckSingle();
endUserReportGenerator.GenerateReportFile(healthcheckData, License, healthcheckData.GetHumanReadableFileName());
}
}
);
}
public bool ReloadXmlReport()
{
return StartTask("Reload report",
() =>
{
string newfile = Settings.InputFile.Replace(".xml", "_reloaded.xml");
string xml = null;
string domainFQDN = null;
var fi = new FileInfo(Settings.InputFile);
if (fi.Name.StartsWith("ad_hc_"))
{
HealthcheckData healthcheckData = DataHelper<HealthcheckData>.LoadXml(Settings.InputFile);
if (healthcheckData.Level != PingCastleReportDataExportLevel.Full)
{
DisplayAdvancement("The xml report does not contain personal data. Current reporting level is: " + healthcheckData.Level);
}
domainFQDN = healthcheckData.DomainFQDN;
DisplayAdvancement("Regenerating xml " + (Settings.EncryptReport ? " (encrypted)" : ""));
healthcheckData.Level = ExportLevel;
xml = DataHelper<HealthcheckData>.SaveAsXml(healthcheckData, newfile, Settings.EncryptReport);
// email sending will be handled by completedtasks
xmlreports[domainFQDN] = xml;
dateReports[domainFQDN] = healthcheckData.GenerationDate;
}
else
{
DisplayAdvancement("file ignored because it does not start with ad_hc_");
}
}
);
}
public bool AnalyzeTask()
{
return StartTask("Analyze",
() =>
{
var analyze = new PingCastle.Cloud.Analyzer.Analyzer(Settings.AzureCredential);
var report = analyze.Analyze().GetAwaiter().GetResult();
report.SetIntegrity();
using (var sr = File.OpenWrite("pingcastlecloud_" + report.TenantName + ".json.gz"))
using (var gz = new GZipStream(sr, CompressionMode.Compress))
using (var sw = new StreamWriter(gz))
{
sw.Write(report.ToJsonString());
}
aadjsonreport[report.TenantName] = "pingcastlecloud_" + report.TenantName + ".json.gz";
var reportGenerator = new ReportCloud();
reportGenerator.GenerateReportFile(report, License, "pingcastlecloud_" + report.TenantName + ".html");
aadhtmlreport[report.TenantName] = "pingcastlecloud_" + report.TenantName + ".html";
});
}
public bool UploadAllReportInCurrentDirectory()
{
return StartTask("Upload report",
() =>
{
if (String.IsNullOrEmpty(Settings.apiKey) || String.IsNullOrEmpty(Settings.apiEndpoint))
throw new PingCastleException("API end point not available");
var files = new List<string>(Directory.GetFiles(Directory.GetCurrentDirectory(), "*ad_*.xml", SearchOption.AllDirectories));
files.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), "pingcastlecloud_*.json.gz", SearchOption.AllDirectories));
files.Sort();
DisplayAdvancement(files.Count + " files to import (only ad_*.xml files and pingcastlecloud_*.json.gz files are uploaded)");
var reports = new List<KeyValuePair<string, string>>();
var aadreports = new List<KeyValuePair<string, string>>();
int i = 1;
foreach (string file in files)
{
if (i % 50 == 0)
{
DisplayAdvancement("Uploading file up to #" + i);
SendViaAPI(reports, aadreports);
reports.Clear();
}
if (!file.EndsWith(".json.gz", StringComparison.OrdinalIgnoreCase))
{
string filename = Path.GetFileNameWithoutExtension(file);
reports.Add(new KeyValuePair<string, string>(filename, File.ReadAllText(file)));
}
else
{
aadreports.Add(new KeyValuePair<string, string>(file, file));
}
i++;
}
if (reports.Count > 0 || aadreports.Count > 0)
SendViaAPI(reports, aadreports);
}
);
}
public bool GenerateDemoReportTask()
{
return StartTask("Generating demo reports",
() =>
{
string path = Path.Combine(Settings.InputDirectory, "demo");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var consolidation = PingCastleReportHelper<HealthcheckData>.LoadXmls(Settings.InputDirectory, Settings.FilterReportDate);
if (consolidation.Count == 0)
{
WriteInRed("No report has been found. Please generate one with PingCastle and the Health Check mode. The program will stop.");
return;
}
consolidation = PingCastleReportHelper<HealthcheckData>.TransformReportsToDemo(consolidation);
foreach (HealthcheckData data in consolidation)
{
string domain = data.DomainFQDN;
var endUserReportGenerator = new ReportHealthCheckSingle();
string html = endUserReportGenerator.GenerateReportFile(data, License, Path.Combine(path, data.GetHumanReadableFileName()));
data.SetExportLevel(ExportLevel);
string xml = DataHelper<HealthcheckData>.SaveAsXml(data, Path.Combine(path, data.GetMachineReadableFileName()), Settings.EncryptReport);
}
}
);
}
// return JWT token
void SendViaAPIGetJwtToken(WebClient client)
{
ServicePointManager.Expect100Continue = false;
client.UseDefaultCredentials = true;
client.Proxy = WebRequest.DefaultWebProxy;
if (client.Proxy == null)
{
Trace.WriteLine("No proxy");
}
else
{
Trace.WriteLine("with proxy");
Trace.WriteLine("Using proxy:" + client.Proxy.GetProxy(new Uri(Settings.apiEndpoint)));
Trace.WriteLine("Is bypassed:" + client.Proxy.IsBypassed(new Uri(Settings.apiEndpoint)));
}
Version version = Assembly.GetExecutingAssembly().GetName().Version;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add(HttpRequestHeader.UserAgent, "PingCastle " + version.ToString(4));
//client.Headers.Add("Authorization", token);
string token;
byte[] answer = null;
try
{
//https://docs.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=netcore-3.1
// try enable TLS1.1
try
{
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(768 | (int)System.Net.ServicePointManager.SecurityProtocol);
}
catch
{
}
// try enable TLS1.2
try
{
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(3072 | (int)System.Net.ServicePointManager.SecurityProtocol);
}
catch
{
}
// try enable TLS1.3
try
{
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(12288 | (int)System.Net.ServicePointManager.SecurityProtocol);
}
catch
{
}
string location = Dns.GetHostEntry(Environment.MachineName).HostName;
Trace.WriteLine("location: " + location);
Trace.WriteLine("apikey: " + Settings.apiKey);
byte[] data = Encoding.Default.GetBytes("{\"apikey\": \"" + ReportHelper.EscapeJsonString(Settings.apiKey) + "\",\"location\": \"" + ReportHelper.EscapeJsonString(location) + "\"}");
answer = client.UploadData(Settings.apiEndpoint + "api/Agent/Login", "POST", data);
token = Encoding.Default.GetString(answer);
Trace.WriteLine("token: " + token);
client.Headers.Add(HttpRequestHeader.Authorization, token);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.SecureChannelFailure)
{
WriteInRed("If you require TLS 1.2 or 1.3 for API, be sure you have installed the Windows patch to support TLS 1.2 or 1.3");
WriteInRed("See kb3140245 and KB4019276 for TLS 1.2");
WriteInRed("Be sure also that .NET has been patched to handle the TLS version");
}
if (ex.Response != null)
{
var responseStream = ex.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
throw new UnauthorizedAccessException(responseText);
}
}
}
throw new UnauthorizedAccessException(ex.Message);
}
}
string SendViaAPIUploadOneReport(WebClient client, string filename, string xml)
{
byte[] answer = null;
Version version = Assembly.GetExecutingAssembly().GetName().Version;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add(HttpRequestHeader.UserAgent, "PingCastle " + version.ToString(4));
try
{
Trace.WriteLine("using filename:" + filename);
var request = "{\"xmlReport\": \"" + ReportHelper.EscapeJsonString(xml) + "\",\"filename\":\"" + ReportHelper.EscapeJsonString(filename) + "\"}";
byte[] data = Encoding.ASCII.GetBytes(request);
answer = client.UploadData(Settings.apiEndpoint + "api/Agent/SendReport", "POST", data);
var o = Encoding.Default.GetString(answer);
Trace.WriteLine("answer:" + o);
return o;
}
catch (WebException ex)
{
Trace.WriteLine("Status: " + ex.Status);
Trace.WriteLine("Message: " + ex.Message);
if (ex.Response != null)
{
var responseStream = ex.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
if (string.IsNullOrEmpty(responseText))
responseText = ex.Message;
throw new PingCastleException(responseText);
}
}
}
else
{
Trace.WriteLine("WebException response null");
}
throw;
}
}
string SendViaAPIUploadOneAADReport(WebClient client, string filename, Stream filecontent)
{
byte[] answer = null;
Version version = Assembly.GetExecutingAssembly().GetName().Version;
client.Headers.Add(HttpRequestHeader.UserAgent, "PingCastle " + version.ToString(4));
//client.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data;
try
{
Trace.WriteLine("using filename:" + filename);
/*byte[] data;
using (var multipartcontent = new MultipartFormDataContent())
{
multipartcontent.Headers.ContentType.MediaType = "multipart/form-data";
multipartcontent.Add(new StreamContent(filecontent), "file", filename);
data = multipartcontent.ReadAsByteArrayAsync().GetAwaiter().GetResult();
}
answer = client.UploadData(Settings.apiEndpoint + "api/Agent/SendAADReport", "POST", data);*/
answer = client.UploadFile(Settings.apiEndpoint + "api/Agent/SendAADReport", filename);
var o = Encoding.Default.GetString(answer);
Trace.WriteLine("answer:" + o);
return o;
}
catch (WebException ex)
{
Trace.WriteLine("Status: " + ex.Status);
Trace.WriteLine("Message: " + ex.Message);
if (ex.Response != null)
{
var responseStream = ex.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
if (string.IsNullOrEmpty(responseText))
responseText = ex.Message;
throw new PingCastleException(responseText);
}
}
}
else
{
Trace.WriteLine("WebException response null");
}
throw;
}
}
public class CustomComputationRule
{
public string ComputationType { get; set; }
public int Score { get; set; }
public int Threshold { get; set; }
public int Order { get; set; }
}
public class CustomRule
{
public string RiskID { get; set; }
public int? MaturityLevel { get; set; }
public List<CustomComputationRule> Computation { get; set; }
}
public class AgentSettings
{
public string License { get; set; }
public string ExportLevel { get; set; }
public List<CustomRule> CustomRules { get; set; }
}
private void ProcessSettings(WebClient client)
{
Version version = Assembly.GetExecutingAssembly().GetName().Version;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add(HttpRequestHeader.UserAgent, "PingCastle " + version.ToString(4));
try
{
string answer = client.DownloadString(Settings.apiEndpoint + "api/Agent/GetSettings");
Trace.WriteLine("answer:" + answer);
DisplayAdvancement("OK");
// TinyJson is extracted from https://github.com/zanders3/json
// MIT License
var deserializedResult = JSONParser.FromJson<AgentSettings>(answer);
// could also use this serializer, but starting .Net 4 only (not .net 3)
//var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//var deserializedResult = serializer.Deserialize<AgentSettings>(answer);
if (deserializedResult.License != null)
{
try