-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathAbstractLicenseValidator.cs
630 lines (551 loc) · 21 KB
/
AbstractLicenseValidator.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.ServiceModel;
using System.Threading;
using System.Xml;
using log4net;
using Rhino.Licensing.Discovery;
namespace Rhino.Licensing
{
/// <summary>
/// Base license validator.
/// </summary>
public abstract class AbstractLicenseValidator
{
/// <summary>
/// License validator logger
/// </summary>
protected static readonly ILog Log = LogManager.GetLogger(typeof(LicenseValidator));
/// <summary>
/// Standard Time servers
/// </summary>
protected static readonly string[] TimeServers =
{
"time.nist.gov",
"time-nw.nist.gov",
"time-a.nist.gov",
"time-b.nist.gov",
"time-a.timefreq.bldrdoc.gov",
"time-b.timefreq.bldrdoc.gov",
"time-c.timefreq.bldrdoc.gov",
"utcnist.colorado.edu",
"nist1.datum.com",
"nist1.dc.certifiedtime.com",
"nist1.nyc.certifiedtime.com",
"nist1.sjc.certifiedtime.com"
};
private readonly string licenseServerUrl;
private readonly Guid clientId;
private readonly string publicKey;
private readonly Timer nextLeaseTimer;
private bool disableFutureChecks;
private bool currentlyValidatingSubscriptionLicense;
private readonly DiscoveryHost discoveryHost;
private DiscoveryClient discoveryClient;
private Guid senderId;
/// <summary>
/// Fired when license data is invalidated
/// </summary>
public event Action<InvalidationType> LicenseInvalidated;
/// <summary>
/// Fired when license is expired
/// </summary>
public event Action<DateTime> LicenseExpired;
/// <summary>
/// Event that's raised when duplicate licenses are found
/// </summary>
public event EventHandler<DiscoveryHost.ClientDiscoveredEventArgs> MultipleLicensesWereDiscovered;
/// <summary>
/// Disable the <see cref="ExpirationDate"/> validation with the time servers
/// </summary>
public bool DisableTimeServersCheck
{
get; set;
}
/// <summary>
/// Gets the expiration date of the license
/// </summary>
public DateTime ExpirationDate
{
get; private set;
}
/// <summary>
/// Lease timeout
/// </summary>
public TimeSpan LeaseTimeout { get; set; }
/// <summary>
/// How to behave when using the same license multiple times
/// </summary>
public MultipleLicenseUsage MultipleLicenseUsageBehavior { get; set; }
/// <summary>
/// Gets or Sets the endpoint address of the subscription service
/// </summary>
public string SubscriptionEndpoint
{
get; set;
}
/// <summary>
/// Gets the Type of the license
/// </summary>
public LicenseType LicenseType
{
get; private set;
}
/// <summary>
/// Gets the Id of the license holder
/// </summary>
public Guid UserId
{
get; private set;
}
/// <summary>
/// Gets the name of the license holder
/// </summary>
public string Name
{
get; private set;
}
/// <summary>
/// Gets or Sets Floating license support
/// </summary>
public bool DisableFloatingLicenses
{
get; set;
}
/// <summary>
/// Whether the client discovery server is enabled. This detects duplicate licenses used on the same network.
/// </summary>
public bool DiscoveryEnabled { get; private set; }
/// <summary>
/// Gets extra license information
/// </summary>
public IDictionary<string, string> LicenseAttributes
{
get; private set;
}
/// <summary>
/// Gets or Sets the license content
/// </summary>
protected abstract string License
{
get; set;
}
/// <summary>
/// Creates a license validator with specfied public key.
/// </summary>
/// <param name="publicKey">public key</param>
/// <param name="enableDiscovery">Whether to enable the client discovery server to detect duplicate licenses used on the same network.</param>
protected AbstractLicenseValidator(string publicKey, bool enableDiscovery = true)
{
LeaseTimeout = TimeSpan.FromMinutes(5);
LicenseAttributes = new Dictionary<string, string>();
nextLeaseTimer = new Timer(LeaseLicenseAgain);
this.publicKey = publicKey;
DiscoveryEnabled = enableDiscovery;
if (DiscoveryEnabled)
{
senderId = Guid.NewGuid();
discoveryHost = new DiscoveryHost();
discoveryHost.ClientDiscovered += DiscoveryHostOnClientDiscovered;
discoveryHost.Start();
}
}
/// <summary>
/// Creates a license validator using the client information
/// and a service endpoint address to validate the license.
/// </summary>
protected AbstractLicenseValidator(string publicKey, string licenseServerUrl, Guid clientId)
: this(publicKey)
{
this.licenseServerUrl = licenseServerUrl;
this.clientId = clientId;
}
private void LeaseLicenseAgain(object state)
{
var client = discoveryClient;
if (client != null)
client.PublishMyPresence();
if (HasExistingLicense())
return;
RaiseLicenseInvalidated();
}
private void RaiseLicenseInvalidated()
{
var licenseInvalidated = LicenseInvalidated;
if (licenseInvalidated == null)
throw new InvalidOperationException("License was invalidated, but there is no one subscribe to the LicenseInvalidated event");
licenseInvalidated(LicenseType == LicenseType.Floating ? InvalidationType.CannotGetNewLicense :
InvalidationType.TimeExpired);
}
private void RaiseMultipleLicenseDiscovered(DiscoveryHost.ClientDiscoveredEventArgs args)
{
var onMultipleLicensesWereDiscovered = MultipleLicensesWereDiscovered;
if (onMultipleLicensesWereDiscovered != null)
{
onMultipleLicensesWereDiscovered(this, args);
}
}
private void DiscoveryHostOnClientDiscovered(object sender, DiscoveryHost.ClientDiscoveredEventArgs clientDiscoveredEventArgs)
{
if (senderId == clientDiscoveredEventArgs.SenderId) // we got our own notification, ignore it
return;
if (UserId != clientDiscoveredEventArgs.UserId) // another license, we don't care
return;
// same user id, different senders
switch (MultipleLicenseUsageBehavior)
{
case MultipleLicenseUsage.AllowForSameUser:
if (Environment.UserName == clientDiscoveredEventArgs.UserName)
return;
break;
}
RaiseLicenseInvalidated();
RaiseMultipleLicenseDiscovered(clientDiscoveredEventArgs);
}
/// <summary>
/// Validates loaded license
/// </summary>
public virtual void AssertValidLicense()
{
LicenseAttributes.Clear();
if (HasExistingLicense())
{
if (DiscoveryEnabled)
{
discoveryClient = new DiscoveryClient(senderId, UserId, Environment.MachineName, Environment.UserName);
discoveryClient.PublishMyPresence();
}
return;
}
Log.WarnFormat("Could not validate existing license\r\n{0}", License);
throw new LicenseNotFoundException();
}
private bool HasExistingLicense()
{
try
{
if (TryLoadingLicenseValuesFromValidatedXml() == false)
{
Log.WarnFormat("Failed validating license:\r\n{0}", License);
return false;
}
Log.InfoFormat("License expiration date is {0}", ExpirationDate);
bool result;
if (LicenseType == LicenseType.Subscription)
{
result = ValidateSubscription();
}
else
{
result = DateTime.UtcNow < ExpirationDate;
}
if (result &&
!DisableTimeServersCheck)
{
ValidateUsingNetworkTime();
}
if (!result)
{
if (LicenseExpired == null)
throw new LicenseExpiredException("Expiration Date : " + ExpirationDate);
DisableFutureChecks();
LicenseExpired(ExpirationDate);
}
return true;
}
catch (RhinoLicensingException)
{
throw;
}
catch (Exception)
{
return false;
}
}
private bool ValidateSubscription()
{
if ((ExpirationDate - DateTime.UtcNow).TotalDays > 4)
return true;
if (currentlyValidatingSubscriptionLicense)
return DateTime.UtcNow < ExpirationDate;
if (SubscriptionEndpoint == null)
throw new InvalidOperationException("Subscription endpoints are not supported for this license validator");
try
{
TryGettingNewLeaseSubscription();
}
catch (Exception e)
{
Log.Error("Could not re-lease subscription license", e);
}
return ValidateWithoutUsingSubscriptionLeasing();
}
private bool ValidateWithoutUsingSubscriptionLeasing()
{
currentlyValidatingSubscriptionLicense = true;
try
{
return HasExistingLicense();
}
finally
{
currentlyValidatingSubscriptionLicense = false;
}
}
private void TryGettingNewLeaseSubscription()
{
var service = ChannelFactory<ISubscriptionLicensingService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(SubscriptionEndpoint));
try
{
var newLicense = service.LeaseLicense(License);
TryOverwritingWithNewLicense(newLicense);
}
finally
{
var communicationObject = service as ICommunicationObject;
if (communicationObject != null)
{
try
{
communicationObject.Close(TimeSpan.FromMilliseconds(200));
}
catch
{
communicationObject.Abort();
}
}
}
}
/// <summary>
/// Loads the license file.
/// </summary>
/// <param name="newLicense"></param>
/// <returns></returns>
protected bool TryOverwritingWithNewLicense(string newLicense)
{
if (string.IsNullOrEmpty(newLicense))
return false;
try
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(newLicense);
}
catch (Exception e)
{
Log.Error("New license is not valid XML\r\n" + newLicense, e);
return false;
}
License = newLicense;
return true;
}
private void ValidateUsingNetworkTime()
{
if (!NetworkInterface.GetIsNetworkAvailable())
return;
var sntp = new SntpClient(GetTimeServers());
sntp.BeginGetDate(time =>
{
if (time > ExpirationDate)
RaiseLicenseInvalidated();
}
, () =>
{
/* ignored */
});
}
/// <summary>
/// Extension point to return different time servers
/// </summary>
/// <returns></returns>
protected virtual string[] GetTimeServers()
{
return TimeServers;
}
/// <summary>
/// Removes existing license from the machine.
/// </summary>
public virtual void RemoveExistingLicense()
{
}
/// <summary>
/// Loads license data from validated license file.
/// </summary>
/// <returns></returns>
public bool TryLoadingLicenseValuesFromValidatedXml()
{
try
{
var doc = new XmlDocument();
doc.LoadXml(License);
if (TryGetValidDocument(publicKey, doc) == false)
{
Log.WarnFormat("Could not validate xml signature of:\r\n{0}", License);
return false;
}
if (doc.FirstChild == null)
{
Log.WarnFormat("Could not find first child of:\r\n{0}", License);
return false;
}
if (doc.SelectSingleNode("/floating-license") != null)
{
var node = doc.SelectSingleNode("/floating-license/license-server-public-key/text()");
if (node == null)
{
Log.WarnFormat("Invalid license, floating license without license server public key:\r\n{0}", License);
throw new InvalidOperationException(
"Invalid license file format, floating license without license server public key");
}
return ValidateFloatingLicense(node.InnerText);
}
var result = ValidateXmlDocumentLicense(doc);
if (result && disableFutureChecks == false)
{
nextLeaseTimer.Change(LeaseTimeout, LeaseTimeout);
}
return result;
}
catch (RhinoLicensingException)
{
throw;
}
catch (Exception e)
{
Log.Error("Could not validate license", e);
return false;
}
}
private bool ValidateFloatingLicense(string publicKeyOfFloatingLicense)
{
if (DisableFloatingLicenses)
{
Log.Warn("Floating licenses have been disabled");
return false;
}
if (licenseServerUrl == null)
{
Log.Warn("Could not find license server url");
throw new InvalidOperationException("Floating license encountered, but licenseServerUrl was not set");
}
var success = false;
var licensingService = ChannelFactory<ILicensingService>.CreateChannel(new WSHttpBinding(), new EndpointAddress(licenseServerUrl));
try
{
var leasedLicense = licensingService.LeaseLicense(
Environment.MachineName,
Environment.UserName,
clientId);
((ICommunicationObject)licensingService).Close();
success = true;
if (leasedLicense == null)
{
Log.WarnFormat("Null response from license server: {0}", licenseServerUrl);
throw new FloatingLicenseNotAvailableException();
}
var doc = new XmlDocument();
doc.LoadXml(leasedLicense);
if (TryGetValidDocument(publicKeyOfFloatingLicense, doc) == false)
{
Log.WarnFormat("Could not get valid license from floating license server {0}", licenseServerUrl);
throw new FloatingLicenseNotAvailableException();
}
var validLicense = ValidateXmlDocumentLicense(doc);
if (validLicense)
{
//setup next lease
var time = (ExpirationDate.AddMinutes(-5) - DateTime.UtcNow);
Log.DebugFormat("Will lease license again at {0}", time);
if (disableFutureChecks == false)
nextLeaseTimer.Change(time, time);
}
return validLicense;
}
finally
{
if (success == false)
((ICommunicationObject)licensingService).Abort();
}
}
internal bool ValidateXmlDocumentLicense(XmlDocument doc)
{
var id = doc.SelectSingleNode("/license/@id");
if (id == null)
{
Log.WarnFormat("Could not find id attribute in license:\r\n{0}", License);
return false;
}
UserId = new Guid(id.Value);
var date = doc.SelectSingleNode("/license/@expiration");
if (date == null)
{
Log.WarnFormat("Could not find expiration in license:\r\n{0}", License);
return false;
}
ExpirationDate = DateTime.ParseExact(date.Value, "yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture);
var licenseType = doc.SelectSingleNode("/license/@type");
if (licenseType == null)
{
Log.WarnFormat("Could not find license type in {0}", licenseType);
return false;
}
LicenseType = (LicenseType)Enum.Parse(typeof(LicenseType), licenseType.Value);
var name = doc.SelectSingleNode("/license/name/text()");
if (name == null)
{
Log.WarnFormat("Could not find licensee's name in license:\r\n{0}", License);
return false;
}
Name = name.Value;
var license = doc.SelectSingleNode("/license");
foreach (XmlAttribute attrib in license.Attributes)
{
if (attrib.Name == "type" || attrib.Name == "expiration" || attrib.Name == "id")
continue;
LicenseAttributes[attrib.Name] = attrib.Value;
}
return true;
}
private bool TryGetValidDocument(string licensePublicKey, XmlDocument doc)
{
var rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(licensePublicKey);
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#");
var signedXml = new SignedXml(doc);
var sig = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr);
if (sig == null)
{
Log.WarnFormat("Could not find this signature node on license:\r\n{0}", License);
return false;
}
signedXml.LoadXml(sig);
return signedXml.CheckSignature(rsa);
}
/// <summary>
/// Disables further license checks for the session.
/// </summary>
public void DisableFutureChecks()
{
disableFutureChecks = true;
nextLeaseTimer.Dispose();
}
/// <summary>
/// Options for detecting multiple licenses
/// </summary>
public enum MultipleLicenseUsage
{
/// <summary>
/// Deny if multiple licenses are used
/// </summary>
Deny,
/// <summary>
/// Only allow if it is running for the same user
/// </summary>
AllowForSameUser
}
}
}