-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathApplicationInstance.cs
More file actions
1153 lines (1016 loc) · 44.2 KB
/
ApplicationInstance.cs
File metadata and controls
1153 lines (1016 loc) · 44.2 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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Security.Cryptography;
namespace Opc.Ua.Configuration
{
/// <inheritdoc/>
public class ApplicationInstance : IApplicationInstance
{
/// <summary>
/// Obsolete constructor
/// </summary>
[Obsolete("Use ApplicationInstance(ITelemetryContext) instead.")]
public ApplicationInstance()
: this((ITelemetryContext)null)
{
}
/// <summary>
/// Obsolete constructor
/// </summary>
[Obsolete("Use ApplicationInstance(ApplicationConfiguration, ITelemetryContext) instead.")]
public ApplicationInstance(ApplicationConfiguration applicationConfiguration)
: this(applicationConfiguration, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationInstance"/> class.
/// </summary>
public ApplicationInstance(ITelemetryContext telemetry)
{
m_telemetry = telemetry;
m_logger = telemetry.CreateLogger<ApplicationInstance>();
DisableCertificateAutoCreation = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationInstance"/> class.
/// </summary>
/// <param name="applicationConfiguration">The application configuration.</param>
/// <param name="telemetry">The telemetry context to use to create obvservability instruments</param>
public ApplicationInstance(
ApplicationConfiguration applicationConfiguration,
ITelemetryContext telemetry)
: this(telemetry)
{
ApplicationConfiguration = applicationConfiguration;
}
/// <inheritdoc/>
public string ApplicationName { get; set; }
/// <inheritdoc/>
public ApplicationType ApplicationType { get; set; }
/// <inheritdoc/>
public string ConfigSectionName { get; set; }
/// <inheritdoc/>
public Type ConfigurationType { get; set; }
/// <inheritdoc/>
public IServerBase Server { get; private set; }
/// <inheritdoc/>
public ApplicationConfiguration ApplicationConfiguration { get; set; }
/// <summary>
/// Get or set the message dialog.
/// </summary>
public static IApplicationMessageDlg MessageDlg { get; set; }
/// <inheritdoc/>
public ICertificatePasswordProvider CertificatePasswordProvider { get; set; }
/// <inheritdoc/>
public bool DisableCertificateAutoCreation { get; set; }
/// <inheritdoc/>
public async Task StartAsync(IServerBase server)
{
Server = server;
if (ApplicationConfiguration == null)
{
await LoadApplicationConfigurationAsync(false).ConfigureAwait(false);
}
await server.StartAsync(ApplicationConfiguration).ConfigureAwait(false);
}
/// <inheritdoc/>
public ValueTask StopAsync()
{
return Server.StopAsync();
}
/// <summary>
/// Stops the UA server.
/// </summary>
[Obsolete("Use StopAsync")]
public void Stop()
{
Server.Stop();
}
/// <inheritdoc/>
public async Task<ApplicationConfiguration> LoadApplicationConfigurationAsync(
Stream stream,
bool silent,
CancellationToken ct = default)
{
ApplicationConfiguration configuration = null;
try
{
configuration = await LoadAppConfigAsync(
silent,
stream,
ApplicationType,
ConfigurationType,
true,
CertificatePasswordProvider,
ct)
.ConfigureAwait(false);
}
catch (Exception) when (silent)
{
}
if (configuration == null)
{
throw ServiceResultException.ConfigurationError("Could not load configuration.");
}
ApplicationConfiguration = FixupAppConfig(configuration);
return configuration;
}
/// <inheritdoc/>
public async ValueTask<ApplicationConfiguration> LoadApplicationConfigurationAsync(
string filePath,
bool silent,
CancellationToken ct = default)
{
ApplicationConfiguration configuration = null;
try
{
configuration = await LoadAppConfigAsync(
silent,
filePath,
ApplicationType,
ConfigurationType,
true,
CertificatePasswordProvider,
ct)
.ConfigureAwait(false);
}
catch (Exception) when (silent)
{
}
if (configuration == null)
{
throw ServiceResultException.ConfigurationError("Could not load configuration file.");
}
ApplicationConfiguration = FixupAppConfig(configuration);
return configuration;
}
/// <inheritdoc/>
public ValueTask<ApplicationConfiguration> LoadApplicationConfigurationAsync(
bool silent,
CancellationToken ct = default)
{
string filePath = ApplicationConfiguration.GetFilePathFromAppConfig(ConfigSectionName, m_logger);
return LoadApplicationConfigurationAsync(filePath, silent, ct);
}
/// <summary>
/// Helper to replace localhost with the hostname
/// in the application uri and base addresses of the
/// configuration.
/// </summary>
public static ApplicationConfiguration FixupAppConfig(
ApplicationConfiguration configuration)
{
configuration.ApplicationUri = Utils.ReplaceLocalhost(configuration.ApplicationUri);
if (configuration.ServerConfiguration != null)
{
for (int i = 0; i < configuration.ServerConfiguration.BaseAddresses.Count; i++)
{
configuration.ServerConfiguration.BaseAddresses[i] = Utils.ReplaceLocalhost(
configuration.ServerConfiguration.BaseAddresses[i]);
}
}
return configuration;
}
/// <inheritdoc/>
public IApplicationConfigurationBuilderTypes Build(string applicationUri, string productUri)
{
// App Uri and cert subject
ApplicationConfiguration = new ApplicationConfiguration(m_telemetry)
{
ApplicationName = ApplicationName,
ApplicationType = ApplicationType,
ApplicationUri = applicationUri,
ProductUri = productUri,
TraceConfiguration = new TraceConfiguration { TraceMasks = Utils.TraceMasks.None },
TransportQuotas = new TransportQuotas()
};
// Trace off
#pragma warning disable CS0618 // Type or member is obsolete
ApplicationConfiguration.TraceConfiguration.ApplySettings();
#pragma warning restore CS0618 // Type or member is obsolete
return new ApplicationConfigurationBuilder(this);
}
/// <inheritdoc/>
public async ValueTask DeleteApplicationInstanceCertificateAsync(
string[] profileIds = null,
CancellationToken ct = default)
{
// TODO: delete only selected profiles
if (ApplicationConfiguration == null)
{
throw new ArgumentException("Missing configuration.");
}
foreach (CertificateIdentifier id in ApplicationConfiguration.SecurityConfiguration
.ApplicationCertificates)
{
await DeleteApplicationInstanceCertificateAsync(ApplicationConfiguration, id, ct)
.ConfigureAwait(false);
}
}
/// <inheritdoc/>
public async ValueTask<bool> CheckApplicationInstanceCertificatesAsync(
bool silent,
ushort? lifeTimeInMonths = null,
CancellationToken ct = default)
{
lifeTimeInMonths ??= CertificateFactory.DefaultLifeTime;
m_logger.LogInformation("Checking application instance certificate.");
if (ApplicationConfiguration == null)
{
await LoadApplicationConfigurationAsync(silent, ct).ConfigureAwait(false);
}
// find the existing certificates.
SecurityConfiguration securityConfiguration = ApplicationConfiguration
.SecurityConfiguration;
if (securityConfiguration.ApplicationCertificates.Count == 0)
{
throw ServiceResultException.ConfigurationError("Need at least one Application Certificate.");
}
// Note: The FindAsync method searches certificates in this order: thumbprint, subjectName, then applicationUri.
// When SubjectName or Thumbprint is specified, certificates may be loaded even if their ApplicationUri
// doesn't match ApplicationConfiguration.ApplicationUri, however each certificate is validated individually
// in CheckApplicationInstanceCertificateAsync (called via CheckOrCreateCertificateAsync) to ensure it contains
// the configuration's ApplicationUri.
bool result = true;
foreach (CertificateIdentifier certId in securityConfiguration.ApplicationCertificates)
{
ushort minimumKeySize = certId.GetMinKeySize(securityConfiguration);
bool nextResult = await CheckOrCreateCertificateAsync(
certId,
silent,
minimumKeySize,
lifeTimeInMonths.Value,
ct)
.ConfigureAwait(false);
result = result && nextResult;
}
return result;
}
/// <summary>
/// Checks, validates, and optionally creates an application certificate.
/// Loads the certificate, validates it against configured requirements (ApplicationUri, key size, domains),
/// and creates a new certificate if none exists and auto-creation is enabled.
/// Note: FindAsync searches certificates in order: thumbprint, subjectName, applicationUri.
/// The applicationUri parameter is only used if thumbprint and subjectName don't find a match.
/// </summary>
/// <exception cref="ServiceResultException"></exception>
private async Task<bool> CheckOrCreateCertificateAsync(
CertificateIdentifier id,
bool silent,
ushort minimumKeySize,
ushort lifeTimeInMonths,
CancellationToken ct = default)
{
ApplicationConfiguration configuration = ApplicationConfiguration;
if (id == null)
{
throw ServiceResultException.ConfigurationError(
"Configuration file does not specify a certificate.");
}
// reload the certificate from disk in the cache.
ICertificatePasswordProvider passwordProvider = configuration
.SecurityConfiguration
.CertificatePasswordProvider;
await id.LoadPrivateKeyExAsync(passwordProvider, configuration.ApplicationUri, m_telemetry, ct)
.ConfigureAwait(false);
// load the certificate
X509Certificate2 certificate = await id.FindAsync(
true,
configuration.ApplicationUri,
m_telemetry,
ct)
.ConfigureAwait(false);
// check that it is ok.
if (certificate != null)
{
m_logger.LogInformation("Check certificate: {Certificate}", certificate.AsLogSafeString());
bool certificateValid = await CheckApplicationInstanceCertificateAsync(
configuration,
id,
certificate,
silent,
minimumKeySize,
ct)
.ConfigureAwait(false);
if (!certificateValid)
{
throw ServiceResultException.ConfigurationError(
"The certificate with subject {0} in the configuration is invalid.\n" +
" Please update or delete the certificate from this location: {1}",
id.SubjectName,
Utils.ReplaceSpecialFolderNames(id.StorePath));
}
}
else
{
// check for missing private key.
certificate = await id.FindAsync(false, configuration.ApplicationUri, m_telemetry, ct)
.ConfigureAwait(false);
if (certificate != null)
{
throw ServiceResultException.ConfigurationError(
"Cannot access private key for certificate with thumbprint={0}",
certificate.Thumbprint);
}
// check for missing thumbprint.
if (!string.IsNullOrEmpty(id.Thumbprint))
{
if (!string.IsNullOrEmpty(id.SubjectName))
{
var id2 = new CertificateIdentifier
{
StoreType = id.StoreType,
StorePath = id.StorePath,
SubjectName = id.SubjectName
};
certificate = await id2.FindAsync(true, configuration.ApplicationUri, m_telemetry, ct)
.ConfigureAwait(false);
}
if (certificate != null)
{
var message = new StringBuilder();
message.AppendLine(
"Thumbprint was explicitly specified in the configuration.")
.AppendLine("Another certificate with the same subject name was found.")
.AppendLine("Use it instead?")
.AppendLine("Requested: {0}")
.AppendLine("Found: {1}");
if (!await ApproveMessageAsync(
Utils.Format(message.ToString(), id.SubjectName, certificate.Subject), silent)
.ConfigureAwait(false))
{
throw ServiceResultException.ConfigurationError(
"Thumbprint for {0} was explicitly specified in the configuration but\n" +
"another certificate with the same subject name {1} was found.",
id.SubjectName,
certificate.Subject);
}
}
else
{
throw ServiceResultException.ConfigurationError(
"Thumbprint was explicitly specified in the configuration. Cannot generate a new certificate.");
}
}
}
if (certificate == null)
{
if (!DisableCertificateAutoCreation)
{
certificate = await CreateApplicationInstanceCertificateAsync(
configuration,
id,
minimumKeySize,
lifeTimeInMonths,
ct)
.ConfigureAwait(false);
}
else
{
m_logger.LogWarning("Application Instance certificate auto creation is disabled.");
}
if (certificate == null)
{
throw ServiceResultException.ConfigurationError(
"There is no cert with subject {0} in the configuration.\n" +
"Please generate a cert for your application, then copy the new cert to this location: {1}",
id.SubjectName,
id.StorePath);
}
}
else if (configuration.SecurityConfiguration.AddAppCertToTrustedStore)
{
// ensure it is trusted.
await AddToTrustedStoreAsync(configuration, certificate, ct).ConfigureAwait(false);
}
return true;
}
/// <inheritdoc/>
public async Task AddOwnCertificateToTrustedStoreAsync(
X509Certificate2 certificate,
CancellationToken ct)
{
await AddToTrustedStoreAsync(ApplicationConfiguration, certificate, ct).ConfigureAwait(
false);
}
/// <summary>
/// Loads the configuration.
/// </summary>
internal async ValueTask<ApplicationConfiguration> LoadAppConfigAsync(
bool silent,
string filePath,
ApplicationType applicationType,
Type configurationType,
bool applyTraceSettings,
ICertificatePasswordProvider certificatePasswordProvider = null,
CancellationToken ct = default)
{
m_logger.LogInformation("Loading application configuration file. {FilePath}", filePath);
try
{
// load the configuration file.
return await ApplicationConfiguration
.LoadAsync(
new FileInfo(filePath),
applicationType,
configurationType,
applyTraceSettings,
m_telemetry,
certificatePasswordProvider,
ct)
.ConfigureAwait(false);
}
catch (Exception e)
{
m_logger.LogError(e, "Could not load configuration file. {FilePath}", filePath);
// warn user.
if (!silent)
{
if (MessageDlg != null)
{
MessageDlg.Message("Load Application Configuration: " + e.Message);
await MessageDlg.ShowAsync().ConfigureAwait(false);
}
throw;
}
return null;
}
}
/// <summary>
/// Loads the configuration.
/// </summary>
internal async ValueTask<ApplicationConfiguration> LoadAppConfigAsync(
bool silent,
Stream stream,
ApplicationType applicationType,
Type configurationType,
bool applyTraceSettings,
ICertificatePasswordProvider certificatePasswordProvider = null,
CancellationToken ct = default)
{
m_logger.LogInformation("Loading application from stream.");
try
{
// load the configuration file.
return await ApplicationConfiguration
.LoadAsync(
stream,
applicationType,
configurationType,
applyTraceSettings,
m_telemetry,
certificatePasswordProvider,
ct)
.ConfigureAwait(false);
}
catch (Exception e)
{
m_logger.LogError(e, "Could not load configuration from stream.");
// warn user.
if (!silent)
{
if (MessageDlg != null)
{
MessageDlg.Message("Load Application Configuration: " + e.Message);
await MessageDlg.ShowAsync().ConfigureAwait(false);
}
throw;
}
return null;
}
}
/// <summary>
/// Creates an application instance certificate if one does not already exist.
/// </summary>
private async Task<bool> CheckApplicationInstanceCertificateAsync(
ApplicationConfiguration configuration,
CertificateIdentifier id,
X509Certificate2 certificate,
bool silent,
ushort minimumKeySize,
CancellationToken ct)
{
if (certificate == null)
{
return false;
}
// set suppressible errors
HashSet<StatusCode> approvedCodes =
[
StatusCodes.BadCertificateUntrusted,
StatusCodes.BadCertificateTimeInvalid,
StatusCodes.BadCertificateIssuerTimeInvalid,
StatusCodes.BadCertificateHostNameInvalid,
StatusCodes.BadCertificateRevocationUnknown,
StatusCodes.BadCertificateIssuerRevocationUnknown
];
void OnCertificateValidation(object sender, CertificateValidationEventArgs e)
{
if (approvedCodes.Contains(e.Error.StatusCode))
{
m_logger.LogWarning(
"Application Certificate Validation suppressed {ErrorMessage}",
e.Error.StatusCode);
e.Accept = true;
}
}
m_logger.LogInformation(
"Check application instance certificate {Certificate}.",
certificate.AsLogSafeString());
try
{
// validate certificate.
configuration.CertificateValidator.CertificateValidation += OnCertificateValidation;
await configuration
.CertificateValidator.ValidateAsync(
certificate.HasPrivateKey
? CertificateFactory.Create(certificate.RawData)
: certificate,
ct)
.ConfigureAwait(false);
}
catch (Exception ex)
{
string message = Utils.Format(
"Error validating certificate. Exception: {0}. Use certificate anyway?",
ex.Message);
if (!await ApproveMessageAsync(message, silent).ConfigureAwait(false))
{
return false;
}
}
finally
{
configuration.CertificateValidator.CertificateValidation -= OnCertificateValidation;
}
// check key size
int keySize = X509Utils.GetPublicKeySize(certificate);
if (minimumKeySize > keySize)
{
string message = Utils.Format(
"The key size ({0}) in the certificate is less than the minimum provided ({1}). Use certificate anyway?",
keySize,
minimumKeySize);
if (!await ApproveMessageAsync(message, silent).ConfigureAwait(false))
{
return false;
}
}
// check domains.
if (configuration.ApplicationType != ApplicationType.Client &&
!await CheckDomainsInCertificateAsync(configuration, certificate, silent, ct)
.ConfigureAwait(false))
{
return false;
}
// Validate that the certificate contains the configuration's ApplicationUri
if (!X509Utils.CompareApplicationUriWithCertificate(
certificate,
configuration.ApplicationUri,
out IReadOnlyList<string> certificateUris))
{
if (certificateUris.Count == 0)
{
const string message =
"The Application URI could not be found in the certificate. Use certificate anyway?";
if (!await ApproveMessageAsync(message, silent).ConfigureAwait(false))
{
return false;
}
}
else
{
string message = Utils.Format(
"The certificate with subject '{0}' does not contain the ApplicationUri '{1}' " +
"from the configuration. Certificate contains: {2}. Use certificate anyway?",
certificate.Subject,
configuration.ApplicationUri,
string.Join(", ", certificateUris));
if (!await ApproveMessageAsync(message, silent).ConfigureAwait(false))
{
return false;
}
}
}
m_logger.LogInformation(
"Certificate {Certificate} validated for ApplicationUri: {ApplicationUri}",
certificate.AsLogSafeString(),
configuration.ApplicationUri);
// update configuration.
id.Certificate = certificate;
return true;
}
/// <summary>
/// Checks that the domains in the server addresses match the domains in the certificates.
/// </summary>
private async Task<bool> CheckDomainsInCertificateAsync(
ApplicationConfiguration configuration,
X509Certificate2 certificate,
bool silent,
CancellationToken ct)
{
m_logger.LogInformation("Check domains in certificate.");
bool valid = true;
IList<string> serverDomainNames = configuration.GetServerDomainNames();
IList<string> certificateDomainNames = X509Utils.GetDomainsFromCertificate(certificate);
m_logger.LogInformation("Server Domain names:");
foreach (string name in serverDomainNames)
{
m_logger.LogInformation(" {ServerDomainName}", name);
}
m_logger.LogInformation("Certificate Domain names:");
foreach (string name in certificateDomainNames)
{
m_logger.LogInformation(" {ClientDomainName}", name);
}
// get computer name.
string computerName = Utils.GetHostName();
// get IP addresses.
IPAddress[] addresses = null;
for (int ii = 0; ii < serverDomainNames.Count; ii++)
{
if (Utils.FindStringIgnoreCase(certificateDomainNames, serverDomainNames[ii]))
{
continue;
}
if (string.Equals(
serverDomainNames[ii],
"localhost",
StringComparison.OrdinalIgnoreCase))
{
if (Utils.FindStringIgnoreCase(certificateDomainNames, computerName))
{
continue;
}
// check for aliases.
bool found = false;
// get IP addresses only if necessary.
addresses ??= await Utils.GetHostAddressesAsync(computerName, ct).ConfigureAwait(
false);
// check for ip addresses.
for (int jj = 0; jj < addresses.Length; jj++)
{
if (Utils.FindStringIgnoreCase(certificateDomainNames, addresses[jj].ToString()))
{
found = true;
break;
}
}
if (found)
{
continue;
}
}
string message = Utils.Format(
"The server is configured to use domain '{0}' which does not appear in the certificate. Use certificate anyway?",
serverDomainNames[ii]);
valid = false;
if (await ApproveMessageAsync(message, silent).ConfigureAwait(false))
{
valid = true;
continue;
}
break;
}
return valid;
}
/// <summary>
/// Creates the application instance certificate.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="id">The certificate identifier.</param>
/// <param name="minimumKeySize">Minimum RSA key size to use when creating the certificate.</param>
/// <param name="lifeTimeInMonths">The lifetime in months.</param>
/// <param name="ct">Cancellation token to cancel operation with</param>
/// <returns>The new certificate</returns>
/// <exception cref="ServiceResultException"></exception>
private async Task<X509Certificate2> CreateApplicationInstanceCertificateAsync(
ApplicationConfiguration configuration,
CertificateIdentifier id,
ushort minimumKeySize,
ushort lifeTimeInMonths,
CancellationToken ct)
{
// delete any existing certificate.
await DeleteApplicationInstanceCertificateAsync(configuration, id, ct).ConfigureAwait(
false);
m_logger.LogInformation("Creating application instance certificate.");
// get the domains from the configuration file.
IList<string> serverDomainNames = configuration.GetServerDomainNames();
if (serverDomainNames.Count == 0)
{
serverDomainNames.Add(Utils.GetHostName());
}
// ensure the certificate store directory exists.
if (id.StoreType == CertificateStoreType.Directory)
{
Utils.GetAbsoluteDirectoryPath(id.StorePath, true, true, true);
}
Security.Certificates.ICertificateBuilder builder = CertificateFactory
.CreateCertificate(
configuration.ApplicationUri,
configuration.ApplicationName,
id.SubjectName,
serverDomainNames)
.SetLifeTime(lifeTimeInMonths);
if (id.CertificateType.IsNull ||
id.CertificateType == ObjectTypeIds.ApplicationCertificateType ||
id.CertificateType == ObjectTypeIds.RsaMinApplicationCertificateType ||
id.CertificateType == ObjectTypeIds.RsaSha256ApplicationCertificateType)
{
ushort keySize = minimumKeySize == 0
? CertificateFactory.DefaultKeySize
: minimumKeySize;
id.Certificate = builder.SetRSAKeySize(keySize).CreateForRSA();
m_logger.LogInformation(
"Certificate {Certificate} created for RSA with key size {KeySize} bits.",
id.Certificate.AsLogSafeString(),
keySize);
}
else
{
ECCurve? curve =
CryptoUtils.GetCurveFromCertificateTypeId(id.CertificateType)
?? throw new ServiceResultException(
StatusCodes.BadConfigurationError,
"The Ecc certificate type is not supported.");
id.Certificate = builder.SetECCurve(curve.Value).CreateForECDsa();
m_logger.LogInformation(
"Certificate {Certificate} created for {Curve}.",
id.Certificate.AsLogSafeString(),
curve.Value.Oid.FriendlyName);
}
ICertificatePasswordProvider passwordProvider = configuration
.SecurityConfiguration
.CertificatePasswordProvider;
await id
.Certificate.AddToStoreAsync(
id.StoreType,
id.StorePath,
passwordProvider?.GetPassword(id),
m_telemetry,
ct)
.ConfigureAwait(false);
// ensure the certificate is trusted.
if (configuration.SecurityConfiguration.AddAppCertToTrustedStore)
{
await AddToTrustedStoreAsync(configuration, id.Certificate, ct).ConfigureAwait(
false);
}
// reload the certificate from disk.
id.Certificate = await id.LoadPrivateKeyExAsync(
passwordProvider,
configuration.ApplicationUri,
m_telemetry,
ct)
.ConfigureAwait(false);
await configuration
.CertificateValidator.UpdateAsync(configuration.SecurityConfiguration, applicationUri: null, ct)
.ConfigureAwait(false);
m_logger.LogInformation(
"Certificate {Certificate} created for {ApplicationUri}.",
id.Certificate.AsLogSafeString(),
configuration.ApplicationUri);
// do not dispose temp cert, or X509Store certs become unusable
return id.Certificate;
}
/// <summary>
/// Deletes an existing application instance certificate.
/// </summary>
/// <param name="configuration">The configuration instance that stores the configurable information for a UA application.</param>
/// <param name="id">The certificate identifier.</param>
/// <param name="ct">Cancellation token to cancel operation with</param>
private async Task DeleteApplicationInstanceCertificateAsync(
ApplicationConfiguration configuration,
CertificateIdentifier id,
CancellationToken ct)
{
if (id == null)
{
return;
}
// delete certificate and private key.
X509Certificate2 certificate = await id.FindAsync(configuration.ApplicationUri, m_telemetry, ct)
.ConfigureAwait(false);
if (certificate != null)
{
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Deleting application instance certificate {Certificate} and private key.",
certificate.AsLogSafeString());
}
// delete trusted peer certificate.
if (configuration.SecurityConfiguration != null &&
configuration.SecurityConfiguration.TrustedPeerCertificates != null)
{
string thumbprint = id.Thumbprint;
if (certificate != null)
{
thumbprint = certificate.Thumbprint;
}
if (!string.IsNullOrEmpty(thumbprint))
{
ICertificateStore store = configuration.SecurityConfiguration
.TrustedPeerCertificates
.OpenStore(m_telemetry);
if (store != null)
{
try
{
bool deleted = await store.DeleteAsync(thumbprint, ct)
.ConfigureAwait(false);
if (deleted)
{
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Application Instance Certificate [{Thumbprint}] deleted from trusted store.",
thumbprint);
}
}
finally
{
store.Close();
}
}
}
}
// delete certificate and private key from owner store.
if (certificate != null)
{
using ICertificateStore store = id.OpenStore(m_telemetry);
bool deleted = await store.DeleteAsync(certificate.Thumbprint, ct)
.ConfigureAwait(false);
if (deleted)
{
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Application certificate {Certificate} and private key deleted.",