forked from i8beef/SAML2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdentityProviderCollection.cs
More file actions
388 lines (342 loc) · 13.5 KB
/
Copy pathIdentityProviderCollection.cs
File metadata and controls
388 lines (342 loc) · 13.5 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using SAML2.Schema.Metadata;
using SAML2.Utils;
namespace SAML2.Config
{
/// <summary>
/// Identity Provider collection.
/// </summary>
public class IdentityProviderCollection : List<IdentityProvider>
{
/// <summary>
/// The file system watcher.
/// </summary>
private FileSystemWatcher _fileSystemWatcher;
/// <summary>
/// Contains Encoding instances of the the encodings that should by tried when a metadata file does not have its
/// encoding specified.
/// </summary>
private List<Encoding> _encodings;
/// <summary>
/// A list of the files that have currently been loaded. The filename is used as key, while last seen modification time is used as value.
/// </summary>
private Dictionary<string, DateTime> _fileInfo;
/// <summary>
/// This dictionary links a file name to the entity id of the metadata document in the file.
/// </summary>
private Dictionary<string, string> _fileToEntity;
/// <summary>
/// The locking object for assuring thread safe refresh.
/// </summary>
private object _lockSync = new object();
/// <summary>
/// The metadata file location to monitor.
/// </summary>
private string _metadataLocation;
/// <summary>
/// Initializes a new instance of the <see cref="IdentityProviderCollection"/> class.
/// </summary>
public IdentityProviderCollection()
{
_fileInfo = new Dictionary<string, DateTime>();
_fileToEntity = new Dictionary<string, string>();
}
/// <summary>
/// Gets or sets the encodings.
/// </summary>
public string Encodings { get; set; }
/// <summary>
/// Gets or sets the metadata location.
/// </summary>
public string MetadataLocation
{
get
{
var value = _metadataLocation;
if (!Path.IsPathRooted(value))
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, value);
}
return value;
}
set
{
_metadataLocation = value;
if (_fileSystemWatcher != null)
{
_fileSystemWatcher.Path = MetadataLocation;
}
}
}
/// <summary>
/// Start watching files.
/// </summary>
public void EnableFileWatcher()
{
_fileSystemWatcher = new FileSystemWatcher
{
Filter = "*.*",
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
Path = MetadataLocation,
EnableRaisingEvents = true
};
_fileSystemWatcher.Changed += FileSystemWatcher_Changed;
_fileSystemWatcher.Created += FileSystemWatcher_Changed;
_fileSystemWatcher.Deleted += FileSystemWatcher_Changed;
_fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
}
/// <summary>
/// Stops watching files.
/// </summary>
public void DisableFileWatcher()
{
_fileSystemWatcher.Dispose();
}
/// <summary>
/// Refreshes this instance from metadata location.
/// </summary>
public void Refresh()
{
if (string.IsNullOrEmpty(MetadataLocation))
{
return;
}
if (!Directory.Exists(MetadataLocation))
{
throw new DirectoryNotFoundException(string.Format(ErrorMessages.MetadataLocationNotFound, MetadataLocation));
}
// Start by removing information on files that are no long in the directory.
var keys = new List<string>(_fileInfo.Keys.Count);
keys.AddRange(_fileInfo.Keys);
foreach (string file in keys)
{
if (!File.Exists(file))
{
_fileInfo.Remove(file);
if (_fileToEntity.ContainsKey(file))
{
var endp = this.FirstOrDefault(x => x.Id == _fileToEntity[file]);
if (endp != null)
{
endp.Metadata = null;
}
_fileToEntity.Remove(file);
}
}
}
// Detect added classes
var files = Directory.GetFiles(MetadataLocation);
foreach (var file in files)
{
if (_fileInfo.ContainsKey(file) && _fileInfo[file] == File.GetLastWriteTime(file))
{
continue;
}
var metadataDocs = ParseFile(file);
if (metadataDocs != null)
{
foreach (var metadataDoc in metadataDocs)
{
var endp = this.FirstOrDefault(x => x.Id == metadataDoc.EntityId);
if (endp == null)
{
// If the endpoint does not exist, create it.
endp = new IdentityProvider();
Add(endp);
}
endp.Id = endp.Name = metadataDoc.EntityId;
endp.Metadata = metadataDoc;
if (_fileToEntity.ContainsKey(file))
{
_fileToEntity.Remove(file);
}
_fileToEntity.Add(file, metadataDoc.EntityId);
}
}
if (_fileInfo.ContainsKey(file))
{
_fileInfo[file] = File.GetLastWriteTime(file);
}
else
{
_fileInfo.Add(file, File.GetLastWriteTime(file));
}
}
// Remove any IDPs with no metadata
var itemsToRemove = this.Where(x => x.Metadata == null).ToList();
foreach (var idp in itemsToRemove)
{
Remove(idp);
}
}
/// <summary>
/// Parses the geneva server metadata.
/// </summary>
/// <param name="doc">The doc.</param>
/// <returns>The XML document.</returns>
private static XmlDocument ParseGenevaServerMetadata(XmlDocument doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
if (doc.DocumentElement == null)
{
throw new ArgumentException("DocumentElement cannot be null", "doc");
}
var other = new XmlDocument { PreserveWhitespace = true };
other.LoadXml(doc.OuterXml);
foreach (var node in other.DocumentElement.ChildNodes.Cast<XmlNode>().Where(node => node.Name != IdpSsoDescriptor.ElementName).ToList())
{
other.DocumentElement.RemoveChild(node);
}
return other;
}
/// <summary>
/// Handles the Renamed event of the FileSystemWatcher control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RenamedEventArgs"/> instance containing the event data.</param>
private void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
lock (_lockSync)
{
Refresh();
}
}
/// <summary>
/// Handles the Changed event of the FileSystemWatcher control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FileSystemEventArgs"/> instance containing the event data.</param>
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
lock (_lockSync)
{
Refresh();
}
}
/// <summary>
/// Returns a list of the encodings that should be tried when a metadata file does not contain a valid signature
/// or cannot be loaded by the XmlDocument class. Either returns a list specified by the administrator in the configuration file
/// or a default list.
/// </summary>
/// <returns>The list of encodings.</returns>
private List<Encoding> GetEncodings()
{
if (_encodings != null)
{
return _encodings;
}
_encodings = string.IsNullOrEmpty(Encodings)
? new List<Encoding> { Encoding.UTF8, Encoding.GetEncoding("iso-8859-1") }
: new List<Encoding>(Encodings.Split(' ').Select(Encoding.GetEncoding));
return _encodings;
}
/// <summary>
/// Loads a file into an XmlDocument. If the loading or the signature check fails, the method will retry using another encoding.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>The XML document.</returns>
private XmlDocument LoadFileAsXmlDocument(string filename)
{
var doc = new XmlDocument { PreserveWhitespace = true };
try
{
// First attempt a standard load, where the XML document is expected to declare its encoding by itself.
doc.Load(filename);
try
{
if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
{
// Bad, bad, bad... never use exceptions for control flow! Who wrote this?
// Throw an exception to get into quirksmode.
throw new InvalidOperationException("Invalid file signature");
}
}
catch (CryptographicException)
{
// Ignore cryptographic exception caused by Geneva server's inability to generate a
// .NET compliant xml signature
return ParseGenevaServerMetadata(doc);
}
return doc;
}
catch (XmlException)
{
// Enter quirksmode
foreach (var encoding in GetEncodings())
{
StreamReader reader = null;
try
{
reader = new StreamReader(filename, encoding);
doc.Load(reader);
if (XmlSignatureUtils.IsSigned(doc) && !XmlSignatureUtils.CheckSignature(doc))
{
continue;
}
}
catch (XmlException)
{
continue;
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return doc;
}
}
return null;
}
/// <summary>
/// Parses the metadata files found in the directory specified in the configuration.
/// </summary>
/// <param name="file">The file.</param>
/// <returns>The parsed <see cref="Saml20MetadataDocument"/>.</returns>
private IList<Saml20MetadataDocument> ParseFile(string file)
{
var doc = LoadFileAsXmlDocument(file);
try
{
foreach (var child in doc.ChildNodes.Cast<XmlNode>().Where(child => child.NamespaceURI == Saml20Constants.Metadata))
{
if (child.LocalName == EntityDescriptor.ElementName)
{
return new List<Saml20MetadataDocument> { new Saml20MetadataDocument(doc) };
}
// TODO Decide how to handle several entities in one metadata file.
if (child.LocalName == EntitiesDescriptor.ElementName)
{
var idpMetadata = new List<Saml20MetadataDocument>();
foreach (var entityDescriptor in child.ChildNodes.Cast<XmlNode>().Where(x => x.NamespaceURI == Saml20Constants.Metadata))
{
var childDoc = new XmlDocument();
childDoc.AppendChild(childDoc.ImportNode(entityDescriptor, true));
idpMetadata.Add(new Saml20MetadataDocument(childDoc));
}
return idpMetadata;
}
}
// No entity descriptor found.
throw new InvalidDataException();
}
catch (Exception e)
{
// Probably not a metadata file.
Logging.LoggerProvider.LoggerFor(GetType()).Error("Problem parsing metadata file", e);
return null;
}
}
}
}