forked from netwrix/pingcastle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataHelper.cs
288 lines (254 loc) · 9.75 KB
/
DataHelper.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
//
// 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Permissions;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using PingCastle.Data;
using PingCastle.Healthcheck;
using PingCastle.Rules;
namespace PingCastle.Data
{
public class DataHelper<T> where T : IPingCastleReport
{
// important: class to save xml string as UTF8 instead of UTF16
private sealed class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
public static string SaveAsXml(T data, string filename, bool EncryptReport)
{
try
{
if (EncryptReport)
{
Utf8StringWriter w = new Utf8StringWriter();
SaveAsXmlEncrypted(data, w, HealthCheckEncryption.GetRSAEncryptionKey());
string xml = w.ToString();
if (!string.IsNullOrEmpty(filename))
{
File.WriteAllText(filename, xml);
}
return xml;
}
else
{
return SaveAsXmlClearText(data, filename);
}
}
catch (Exception ex)
{
Trace.WriteLine("Error when saving " + filename + " error: " + ex.Message);
throw;
}
}
private static string SaveAsXmlClearText(T data, string filename)
{
string xml = GetXmlClearText(data);
if (!string.IsNullOrEmpty(filename))
{
File.WriteAllText(filename, xml);
}
return xml;
}
public static string GetXmlClearText(T data)
{
string xml = null;
using (Utf8StringWriter wr = new Utf8StringWriter())
{
var xmlDoc = GetXmlDocumentClearText(data);
xmlDoc.Save(wr);
xml = wr.ToString();
}
return xml;
}
public static XmlDocument GetXmlDocumentClearText(T data)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
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, data);
}
return xmlDoc;
}
public static void SaveAsXmlEncrypted(T data, TextWriter outStream, RSA rsaKey)
{
XmlDocument xmlDoc = GetXmlDocumentClearText(data);
XmlElement elementToEncrypt = xmlDoc.DocumentElement;
Rijndael sessionKey = null;
// Create a 256 bit Rijndael key.
sessionKey = new RijndaelManaged();
sessionKey.KeySize = 256;
EncryptedXml eXml = new EncryptedXml();
byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
EncryptedData edElement = new EncryptedData();
edElement.Type = EncryptedXml.XmlEncElementUrl;
edElement.Id = elementToEncrypt.Name;
edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
EncryptedKey ek = new EncryptedKey();
byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false);
ek.CipherData = new CipherData(encryptedKey);
ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
KeyInfoName kin = new KeyInfoName();
kin.Value = "rsaKey";
ek.KeyInfo.AddClause(kin);
edElement.CipherData.CipherValue = encryptedElement;
EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
xmlDoc.Save(outStream);
}
public static T LoadXml(string filename)
{
using (Stream fs = File.OpenRead(filename))
{
return LoadXml(fs, filename, HealthCheckEncryption.GetAllPrivateKeys());
}
}
public static T LoadXml(Stream report, string filenameForDebug, List<RSA> Keys)
{
XmlDocument xmlDoc = LoadXmlDocument(report, filenameForDebug, Keys);
return ConvertXmlDocumentToData(xmlDoc);
}
public static T ConvertXmlDocumentToData(XmlDocument xmlDoc)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
T data = (T) xs.Deserialize(new XmlNodeReader(xmlDoc));
if (typeof(T).IsAssignableFrom(typeof(HealthcheckData)))
CheckForHCDataUnknownModel((HealthcheckData)Convert.ChangeType(data, typeof(HealthcheckData)));
return data;
}
public static XmlDocument LoadXmlDocument(Stream report, string filenameForDebug, List<RSA> Keys)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
try
{
xmlDoc.Load(report);
}
catch (XmlException ex)
{
Trace.WriteLine("Invalid xml " + ex.Message);
Trace.WriteLine("Trying to recover");
StreamReader reader = new StreamReader(report);
string xml = reader.ReadToEnd();
try
{
xmlDoc.LoadXml(xml);
}
catch (XmlException ex2)
{
throw new PingCastleDataException(filenameForDebug, "Unable to parse the xml (" + ex2.Message + ")");
}
}
if (xmlDoc.DocumentElement.Name == "EncryptedData")
{
if (Keys == null || Keys.Count == 0)
throw new PingCastleDataException(filenameForDebug, "The report is encrypted and no decryption key is configured.");
decipher(filenameForDebug, xmlDoc, Keys);
}
return xmlDoc;
}
private static void CheckForHCDataUnknownModel(HealthcheckData data)
{
foreach (var rule in data.RiskRules)
{
// report was generated by an older version of PingCastle
if (rule.Model == RiskModelCategory.Unknown)
{
foreach (var r in RuleSet<HealthcheckData>.Rules)
{
if (r.RiskId == rule.RiskId)
{
rule.Model = r.Model;
break;
}
}
}
}
if (data.MaturityLevel == 0)
{
data.MaturityLevel = 5;
foreach (var rule in data.RiskRules)
{
var hcrule = RuleSet<HealthcheckData>.GetRuleFromID(rule.RiskId);
if (hcrule == null)
{
continue;
}
int level = hcrule.MaturityLevel;
if (level > 0 && level < data.MaturityLevel)
data.MaturityLevel = level;
}
}
}
static void decipher(string filename, XmlDocument xmlDoc, List<RSA> Keys)
{
// Create a new EncryptedXml object.
EncryptedXml exml = new EncryptedXml(xmlDoc);
// Add a key-name mapping.
// This method can only decrypt documents
// that present the specified key name.
int keyid = 0;
foreach (RSA Alg in Keys)
{
try
{
exml.ClearKeyNameMappings();
Trace.WriteLine("Trying to decrypt with keyid " + keyid++);
exml.AddKeyNameMapping("rsaKey", Alg);
// Decrypt the element.
exml.DecryptDocument();
return;
}
catch (Exception ex)
{
Trace.WriteLine("When decoding the document - trying next key: " + ex.Message);
}
}
Trace.WriteLine("The program tried to use " + keyid + " keys");
throw new PingCastleDataException(filename, "Unable to find a key in the configuration which can decrypt the document");
}
}
[Serializable]
public class PingCastleDataException : Exception
{
public string ReportName { get; set; }
public PingCastleDataException()
{
}
public PingCastleDataException(string reportName, string message) : base(message)
{
ReportName = reportName;
}
public PingCastleDataException(string reportName, string message, Exception innerException) : base(message, innerException)
{
ReportName = reportName;
}
protected PingCastleDataException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("Report", ReportName);
base.GetObjectData(info, context);
}
}
}