-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathConfigurationNodeManager.cs
More file actions
1272 lines (1162 loc) · 56.1 KB
/
ConfigurationNodeManager.cs
File metadata and controls
1272 lines (1162 loc) · 56.1 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.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua.Security.Certificates;
using System.Security.Cryptography;
using System.Diagnostics;
#if !NET9_0_OR_GREATER
using System.Runtime.InteropServices;
#endif
namespace Opc.Ua.Server
{
/// <summary>
/// The Server Configuration Node Manager.
/// </summary>
public class ConfigurationNodeManager : DiagnosticsNodeManager, ICallAsyncNodeManager, IConfigurationNodeManager
{
/// <summary>
/// Initializes the configuration and diagnostics manager.
/// </summary>
public ConfigurationNodeManager(
IServerInternal server,
ApplicationConfiguration configuration)
: this(server, configuration, server.Telemetry.CreateLogger<ConfigurationNodeManager>())
{
}
/// <summary>
/// Initializes the configuration and diagnostics manager.
/// </summary>
public ConfigurationNodeManager(
IServerInternal server,
ApplicationConfiguration configuration,
ILogger logger)
: base(server, configuration, logger)
{
string rejectedStorePath = configuration.SecurityConfiguration.RejectedCertificateStore?
.StorePath;
if (!string.IsNullOrEmpty(rejectedStorePath))
{
m_rejectedStore = new CertificateStoreIdentifier(rejectedStorePath);
}
m_certificateGroups = [];
m_configuration = configuration;
// TODO: configure cert groups in configuration
var defaultApplicationGroup = new ServerCertificateGroup
{
NodeId = ObjectIds.ServerConfiguration_CertificateGroups_DefaultApplicationGroup,
BrowseName = BrowseNames.DefaultApplicationGroup,
CertificateTypes = [],
ApplicationCertificates = [],
IssuerStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath
),
TrustedStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.TrustedPeerCertificates.StorePath)
};
m_certificateGroups.Add(defaultApplicationGroup);
if (configuration.SecurityConfiguration.UserIssuerCertificates != null &&
configuration.SecurityConfiguration.TrustedUserCertificates != null)
{
var defaultUserGroup = new ServerCertificateGroup
{
NodeId = ObjectIds.ServerConfiguration_CertificateGroups_DefaultUserTokenGroup,
BrowseName = BrowseNames.DefaultUserTokenGroup,
CertificateTypes = [],
ApplicationCertificates = [],
IssuerStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.UserIssuerCertificates.StorePath
),
TrustedStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.TrustedUserCertificates.StorePath)
};
m_certificateGroups.Add(defaultUserGroup);
}
ServerCertificateGroup defaultHttpsGroup = null;
if (configuration.SecurityConfiguration.HttpsIssuerCertificates != null &&
configuration.SecurityConfiguration.TrustedHttpsCertificates != null)
{
defaultHttpsGroup = new ServerCertificateGroup
{
NodeId = ObjectIds.ServerConfiguration_CertificateGroups_DefaultHttpsGroup,
BrowseName = BrowseNames.DefaultHttpsGroup,
CertificateTypes = [],
ApplicationCertificates = [],
IssuerStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.HttpsIssuerCertificates.StorePath
),
TrustedStore = new CertificateStoreIdentifier(
configuration.SecurityConfiguration.TrustedHttpsCertificates.StorePath)
};
m_certificateGroups.Add(defaultHttpsGroup);
}
// For each certificate in ApplicationCertificates, add the certificate type to ServerConfiguration_CertificateGroups_DefaultApplicationGroup
// under the CertificateTypes field.
foreach (CertificateIdentifier cert in configuration.SecurityConfiguration
.ApplicationCertificates)
{
defaultApplicationGroup.CertificateTypes =
[
.. defaultApplicationGroup.CertificateTypes,
.. new NodeId[] { cert.CertificateType }
];
defaultApplicationGroup.ApplicationCertificates.Add(cert);
if (cert.CertificateType == ObjectTypeIds.HttpsCertificateType &&
defaultHttpsGroup != null)
{
defaultHttpsGroup.CertificateTypes =
[
.. defaultHttpsGroup.CertificateTypes,
.. new NodeId[] { cert.CertificateType }
];
defaultHttpsGroup.ApplicationCertificates.Add(cert);
}
}
}
/// <summary>
/// Replaces the generic node with a node specific to the model.
/// </summary>
protected override NodeState AddBehaviourToPredefinedNode(
ISystemContext context,
NodeState predefinedNode)
{
if (predefinedNode is BaseObjectState passiveNode)
{
NodeId typeId = passiveNode.TypeDefinitionId;
if (IsNodeIdInNamespace(typeId) && typeId.TryGetIdentifier(out uint numericId))
{
switch (numericId)
{
case ObjectTypes.ServerConfigurationType:
{
var activeNode = new ServerConfigurationState(passiveNode.Parent);
activeNode.GetCertificates = new GetCertificatesMethodState(activeNode);
activeNode.Create(context, passiveNode);
m_serverConfigurationNode = activeNode;
// replace the node in the parent.
if (passiveNode.Parent != null)
{
passiveNode.Parent.ReplaceChild(context, activeNode);
}
else
{
NodeState serverNode = Server.NodeManager.FindNodeInAddressSpaceAsync(ObjectIds.Server).AsTask().GetAwaiter().GetResult();
serverNode?.ReplaceChild(context, activeNode);
}
// remove the reference to server node because it is set as parent
activeNode.RemoveReference(
ReferenceTypeIds.HasComponent,
true,
ObjectIds.Server);
return activeNode;
}
case ObjectTypes.CertificateGroupFolderType:
{
var activeNode = new CertificateGroupFolderState(passiveNode.Parent);
activeNode.Create(context, passiveNode);
// delete unsupported groups
if (m_certificateGroups.All(group =>
activeNode.DefaultHttpsGroup == null ||
activeNode.DefaultHttpsGroup.BrowseName != group.BrowseName))
{
activeNode.DefaultHttpsGroup = null;
}
if (m_certificateGroups.All(group =>
activeNode.DefaultUserTokenGroup == null ||
activeNode.DefaultUserTokenGroup.BrowseName != group.BrowseName))
{
activeNode.DefaultUserTokenGroup = null;
}
if (m_certificateGroups.All(group =>
activeNode.DefaultApplicationGroup == null ||
activeNode.DefaultApplicationGroup.BrowseName != group.BrowseName))
{
activeNode.DefaultApplicationGroup = null;
}
// replace the node in the parent.
passiveNode.Parent?.ReplaceChild(context, activeNode);
return activeNode;
}
case ObjectTypes.CertificateGroupType:
{
ServerCertificateGroup result = m_certificateGroups
.FirstOrDefault(group =>
group.NodeId == passiveNode.NodeId);
if (result != null)
{
var activeNode = new CertificateGroupState(passiveNode.Parent);
activeNode.Create(context, passiveNode);
result.NodeId = activeNode.NodeId;
result.Node = activeNode;
// replace the node in the parent.
passiveNode.Parent?.ReplaceChild(context, activeNode);
return activeNode;
}
}
break;
}
}
}
return base.AddBehaviourToPredefinedNode(context, predefinedNode);
}
///<inheritdoc/>
public void CreateServerConfiguration(
ServerSystemContext systemContext,
ApplicationConfiguration configuration)
{
// setup server configuration node
m_serverConfigurationNode.ServerCapabilities.Value =
[
.. configuration.ServerConfiguration.ServerCapabilities
];
m_serverConfigurationNode.ServerCapabilities.ValueRank = ValueRanks.OneDimension;
m_serverConfigurationNode.ServerCapabilities.ArrayDimensions
= new ReadOnlyList<uint>([0]);
m_serverConfigurationNode.SupportedPrivateKeyFormats.Value =
[
.. configuration.ServerConfiguration.SupportedPrivateKeyFormats
];
m_serverConfigurationNode.SupportedPrivateKeyFormats.ValueRank = ValueRanks
.OneDimension;
m_serverConfigurationNode.SupportedPrivateKeyFormats.ArrayDimensions
= new ReadOnlyList<uint>([0]);
m_serverConfigurationNode.MaxTrustListSize.Value = (uint)configuration
.ServerConfiguration
.MaxTrustListSize;
m_serverConfigurationNode.MulticastDnsEnabled.Value = configuration.ServerConfiguration
.MultiCastDnsEnabled;
m_serverConfigurationNode.UpdateCertificate.OnCallAsync
= new UpdateCertificateMethodStateMethodAsyncCallHandler(
UpdateCertificateAsync);
m_serverConfigurationNode.CreateSigningRequest.OnCallAsync =
new CreateSigningRequestMethodStateMethodAsyncCallHandler(CreateSigningRequestAsync);
m_serverConfigurationNode.ApplyChanges.OnCallMethod2
= new GenericMethodCalledEventHandler2(ApplyChanges);
m_serverConfigurationNode.GetRejectedList.OnCall
= new GetRejectedListMethodStateMethodCallHandler(
GetRejectedList);
m_serverConfigurationNode.GetCertificates.OnCall
= new GetCertificatesMethodStateMethodCallHandler(
GetCertificates);
m_serverConfigurationNode.ClearChangeMasks(systemContext, true);
// setup certificate group trust list handlers
foreach (ServerCertificateGroup certGroup in m_certificateGroups)
{
certGroup.Node.CertificateTypes.Value = certGroup.CertificateTypes;
certGroup.Node.TrustList.Handle = new TrustList(
certGroup.Node.TrustList,
certGroup.TrustedStore,
certGroup.IssuerStore,
new TrustList.SecureAccess(HasApplicationSecureAdminAccess),
new TrustList.SecureAccess(HasApplicationSecureAdminAccess),
Server.Telemetry,
m_configuration.ServerConfiguration.MaxTrustListSize);
certGroup.Node.ClearChangeMasks(systemContext, true);
}
// find ServerNamespaces node and subscribe to StateChanged
if (FindPredefinedNode<NamespacesState>(ObjectIds.Server_Namespaces)
is NamespacesState serverNamespacesNode)
{
serverNamespacesNode.StateChanged += ServerNamespacesChanged;
}
}
///<inheritdoc/>
public NamespaceMetadataState GetNamespaceMetadataState(string namespaceUri)
{
if (namespaceUri == null)
{
return null;
}
if (m_namespaceMetadataStates.TryGetValue(
namespaceUri,
out NamespaceMetadataState value))
{
return value;
}
NamespaceMetadataState namespaceMetadataState = FindNamespaceMetadataState(
namespaceUri);
lock (Lock)
{
// remember the result for faster access.
m_namespaceMetadataStates[namespaceUri] = namespaceMetadataState;
}
return namespaceMetadataState;
}
/// <inheritdoc/>
public NamespaceMetadataState CreateNamespaceMetadataState(string namespaceUri)
{
NamespaceMetadataState namespaceMetadataState = FindNamespaceMetadataState(
namespaceUri);
if (namespaceMetadataState == null)
{
// find ServerNamespaces node
if (FindPredefinedNode<NamespacesState>(ObjectIds.Server_Namespaces)
is not NamespacesState serverNamespacesNode)
{
m_logger.LogError(
"Cannot create NamespaceMetadataState for namespace '{NamespaceUri}'.",
namespaceUri);
return null;
}
// create the NamespaceMetadata node
namespaceMetadataState = new NamespaceMetadataState(serverNamespacesNode)
{
BrowseName = new QualifiedName(namespaceUri, NamespaceIndex)
};
namespaceMetadataState.Create(
SystemContext,
default,
namespaceMetadataState.BrowseName,
default,
true);
namespaceMetadataState.DisplayName = LocalizedText.From(namespaceUri);
namespaceMetadataState.SymbolicName = namespaceUri;
namespaceMetadataState.NamespaceUri.Value = namespaceUri;
// add node as child of ServerNamespaces and in predefined nodes
serverNamespacesNode.AddChild(namespaceMetadataState);
serverNamespacesNode.ClearChangeMasks(Server.DefaultSystemContext, true);
AddPredefinedNode(SystemContext, namespaceMetadataState);
}
return namespaceMetadataState;
}
/// <inheritdoc/>
public void HasApplicationSecureAdminAccess(ISystemContext context)
{
HasApplicationSecureAdminAccess(context, null);
}
/// <inheritdoc/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1725:Parameter names should match base declaration", Justification = "<Pending>")]
public void HasApplicationSecureAdminAccess(
ISystemContext context,
CertificateStoreIdentifier trustedStore)
{
if (context is SessionSystemContext { OperationContext: OperationContext operationContext })
{
if (operationContext.ChannelContext?.EndpointDescription?.SecurityMode !=
MessageSecurityMode.SignAndEncrypt)
{
throw new ServiceResultException(
StatusCodes.BadUserAccessDenied,
"Access to this item is only allowed with MessageSecurityMode SignAndEncrypt.");
}
IUserIdentity identity = operationContext.UserIdentity;
// allow access to system configuration only with Role SecurityAdmin
if (identity == null ||
identity.TokenType == UserTokenType.Anonymous ||
!identity.GrantedRoleIds.Contains(ObjectIds.WellKnownRole_SecurityAdmin))
{
throw new ServiceResultException(
StatusCodes.BadUserAccessDenied,
"Security Admin Role required to access this item.");
}
}
}
private async ValueTask<UpdateCertificateMethodStateResult> UpdateCertificateAsync(
ISystemContext context,
MethodState method,
NodeId objectId,
NodeId certificateGroupId,
NodeId certificateTypeId,
byte[] certificate,
byte[][] issuerCertificates,
string privateKeyFormat,
byte[] privateKey,
CancellationToken ct)
{
bool applyChangesRequired = false;
HasApplicationSecureAdminAccess(context);
VariantCollection inputArguments =
[
certificateGroupId,
certificateTypeId,
certificate,
issuerCertificates,
privateKeyFormat,
privateKey
];
X509Certificate2 newCert = null;
X509Certificate2 certWithPrivateKey = null;
Server.ReportCertificateUpdateRequestedAuditEvent(
context,
objectId,
method,
inputArguments,
m_logger);
try
{
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
privateKeyFormat = privateKeyFormat?.ToUpperInvariant();
if (privateKeyFormat is not null and not "PEM" and not "PFX" and not "")
{
throw new ServiceResultException(
StatusCodes.BadNotSupported,
$"The private key format {privateKeyFormat} is not supported.");
}
ServerCertificateGroup certificateGroup = VerifyGroupAndTypeId(
certificateGroupId,
certificateTypeId);
certificateGroup.UpdateCertificate = null;
try
{
newCert = CertificateFactory.Create(certificate);
}
catch
{
throw new ServiceResultException(
StatusCodes.BadCertificateInvalid,
"Certificate data is invalid.");
}
// validate certificate type of new certificate
if (!CertificateIdentifier.ValidateCertificateType(newCert, certificateTypeId))
{
throw new ServiceResultException(
StatusCodes.BadCertificateInvalid,
"Certificate type of new certificate doesn't match the provided certificate type.");
}
// identify the existing certificate to be updated
// it should be of the same type and same subject name as the new certificate
CertificateIdentifier existingCertIdentifier =
(
certificateGroup.ApplicationCertificates.FirstOrDefault(cert =>
X509Utils.CompareDistinguishedName(cert.SubjectName, newCert.Subject) &&
cert.CertificateType == certificateTypeId)
?? certificateGroup.ApplicationCertificates.FirstOrDefault(cert =>
cert.Certificate != null &&
X509Utils.GetApplicationUrisFromCertificate(cert.Certificate)
.Any(uri => uri.Equals(m_configuration.ApplicationUri, StringComparison.Ordinal)) &&
cert.CertificateType == certificateTypeId))
?? throw new ServiceResultException(
StatusCodes.BadInvalidArgument,
"No existing certificate found for the specified certificate type and subject name.");
var newIssuerCollection = new X509Certificate2Collection();
try
{
// build issuer chain
if (issuerCertificates != null)
{
foreach (byte[] issuerRawCert in issuerCertificates)
{
newIssuerCollection.Add(CertificateFactory.Create(issuerRawCert));
}
}
}
catch
{
throw new ServiceResultException(
StatusCodes.BadCertificateInvalid,
"Issuer certificate data is invalid.");
}
// self signed
bool selfSigned = X509Utils.IsSelfSigned(newCert);
if (selfSigned && newIssuerCollection.Count != 0)
{
throw new ServiceResultException(
StatusCodes.BadCertificateInvalid,
"Issuer list not empty for self signed certificate.");
}
if (!selfSigned)
{
try
{
// verify cert with issuer chain
var certValidator = new CertificateValidator(Server.Telemetry);
var issuerStore = new CertificateTrustList();
var issuerCollection = new CertificateIdentifierCollection();
foreach (X509Certificate2 issuerCert in newIssuerCollection)
{
issuerCollection.Add(new CertificateIdentifier(issuerCert));
}
issuerStore.TrustedCertificates = issuerCollection;
certValidator.Update(issuerStore, issuerStore, null);
await certValidator.ValidateAsync(newCert, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
m_logger.LogError(
Utils.TraceMasks.Security,
ex,
"Failed to verify integrity of the new certificate {Certificate} and the issuer list.",
newCert.AsLogSafeString());
throw new ServiceResultException(
StatusCodes.BadSecurityChecksFailed,
"Failed to verify integrity of the new certificate and the issuer list.",
ex);
}
}
var updateCertificate = new UpdateCertificateData
{
IssuerCollection = newIssuerCollection,
SessionId = (context as ISessionSystemContext)?.SessionId ?? default
};
try
{
ICertificatePasswordProvider passwordProvider = m_configuration
.SecurityConfiguration
.CertificatePasswordProvider;
switch (privateKeyFormat)
{
case null:
case "":
for (int attempt = 0; ; attempt++)
{
X509Certificate2 exportableKey;
// use the new generated private key if one exists and matches the provided public key
if (certificateGroup.TemporaryApplicationCertificate != null &&
X509Utils.VerifyKeyPair(
newCert,
certificateGroup.TemporaryApplicationCertificate))
{
exportableKey = X509Utils.CreateCopyWithPrivateKey(
certificateGroup.TemporaryApplicationCertificate,
false);
}
else
{
certWithPrivateKey = await existingCertIdentifier
.LoadPrivateKeyExAsync(
passwordProvider,
m_configuration.ApplicationUri,
Server.Telemetry,
ct)
.ConfigureAwait(false);
if (certWithPrivateKey == null)
{
throw new ServiceResultException(
StatusCodes.BadSecurityChecksFailed,
"A private key was not found");
}
exportableKey = X509Utils.CreateCopyWithPrivateKey(
certWithPrivateKey,
false);
}
updateCertificate.CertificateWithPrivateKey =
CertificateFactory.CreateCertificateWithPrivateKey(
newCert,
exportableKey);
try
{
await UpdateCertificateInternalAsync(
certificateGroup,
existingCertIdentifier,
updateCertificate, ct).ConfigureAwait(false);
break;
}
catch (Exception ex) when (ShouldRetry(attempt, ex))
{
m_logger.LogDebug(
Utils.TraceMasks.Security,
ex,
"Failed to update certificate {Certificate}. Retrying...",
newCert.AsLogSafeString());
}
}
break;
case "PFX":
for (int attempt = 0; ; attempt++)
{
certWithPrivateKey = X509Utils.CreateCertificateFromPKCS12(
privateKey,
passwordProvider?.GetPassword(existingCertIdentifier),
#if !NET9_0_OR_GREATER
// https://github.com/OPCFoundation/UA-.NETStandard/commit/0b24d62b7c2bab2e5ed08e694103d49278e457af
// CopyWithPrivateKey apparently does not support ephimeralkeysets on windows
RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
#else // But it seems to work on .net 9 - and we prefer that over files
false);
#endif
updateCertificate.CertificateWithPrivateKey =
CertificateFactory.CreateCertificateWithPrivateKey(
newCert,
certWithPrivateKey);
try
{
await UpdateCertificateInternalAsync(
certificateGroup,
existingCertIdentifier,
updateCertificate, ct).ConfigureAwait(false);
break;
}
catch (Exception ex) when (ShouldRetry(attempt, ex))
{
m_logger.LogDebug(
Utils.TraceMasks.Security,
ex,
"Failed to update certificate {Certificate} with PFX private key. Retrying...",
newCert.AsLogSafeString());
}
}
break;
case "PEM":
for (int attempt = 0; ; attempt++)
{
updateCertificate.CertificateWithPrivateKey =
CertificateFactory.CreateCertificateWithPEMPrivateKey(
newCert,
privateKey,
passwordProvider?.GetPassword(existingCertIdentifier));
try
{
await UpdateCertificateInternalAsync(
certificateGroup,
existingCertIdentifier,
updateCertificate, ct).ConfigureAwait(false);
break;
}
catch (Exception ex) when (ShouldRetry(attempt, ex))
{
m_logger.LogDebug(
Utils.TraceMasks.Security,
ex,
"Failed to update certificate {Certificate} with PEM private key. Retrying...",
newCert.AsLogSafeString());
}
}
break;
}
}
catch (Exception ex) when (ex is not ServiceResultException)
{
throw new ServiceResultException(
StatusCodes.BadSecurityChecksFailed,
"Failed to verify integrity of the new certificate and the private key.", ex);
}
finally
{
// dispose temporary new private key as it is no longer needed
certificateGroup.TemporaryApplicationCertificate?.Dispose();
certificateGroup.TemporaryApplicationCertificate = null;
}
certificateGroup.UpdateCertificate = updateCertificate;
applyChangesRequired = true;
}
catch (Exception e)
{
// report the failure of UpdateCertificate via an audit event
Server.ReportCertificateUpdatedAuditEvent(
context,
objectId,
method,
inputArguments,
certificateGroupId,
certificateTypeId,
m_logger,
e);
// Raise audit certificate event
Server.ReportAuditCertificateEvent(newCert, e, m_logger);
throw;
}
return new UpdateCertificateMethodStateResult
{
ServiceResult = ServiceResult.Good,
ApplyChangesRequired = applyChangesRequired
};
static bool ShouldRetry(int attempt, Exception ex)
{
if (ex is ServiceResultException sre && sre.StatusCode == StatusCodes.BadConfigurationError)
{
return false;
}
const int maxAttempts = 3;
return attempt < maxAttempts;
}
// Handle the store update
async Task UpdateCertificateInternalAsync(
ServerCertificateGroup certificateGroup,
CertificateIdentifier existingCertIdentifier,
UpdateCertificateData updateCertificate,
CancellationToken ct)
{
try
{
using (ICertificateStore appStore = existingCertIdentifier.OpenStore(Server.Telemetry))
{
if (appStore == null)
{
throw ServiceResultException.ConfigurationError(
"Failed to open application certificate store.");
}
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Delete application certificate {Certificate}",
existingCertIdentifier.Certificate.AsLogSafeString());
await appStore.DeleteAsync(
existingCertIdentifier.Thumbprint,
ct)
.ConfigureAwait(false);
ICertificatePasswordProvider passwordProvider = m_configuration
.SecurityConfiguration
.CertificatePasswordProvider;
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Add new application certificate {Certificate}",
updateCertificate.CertificateWithPrivateKey.AsLogSafeString());
Debug.Assert(updateCertificate.CertificateWithPrivateKey.HasPrivateKey);
await appStore.AddAsync(
updateCertificate.CertificateWithPrivateKey,
passwordProvider?.GetPassword(existingCertIdentifier),
ct)
.ConfigureAwait(false);
// keep only track of cert without private key
X509Certificate2 certOnly = CertificateFactory.Create(
updateCertificate.CertificateWithPrivateKey.RawData);
updateCertificate.CertificateWithPrivateKey.Dispose();
updateCertificate.CertificateWithPrivateKey = certOnly;
// update certificate identifier with new certificate
await existingCertIdentifier.FindAsync(
m_configuration.ApplicationUri,
Server.Telemetry,
ct)
.ConfigureAwait(false);
}
ICertificateStore issuerStore = certificateGroup.IssuerStore.OpenStore(Server.Telemetry);
try
{
if (issuerStore == null)
{
throw ServiceResultException.ConfigurationError(
"Failed to open issuer certificate store.");
}
foreach (X509Certificate2 issuer in updateCertificate.IssuerCollection)
{
try
{
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Add new issuer certificate {Certificate}",
issuer.AsLogSafeString());
await issuerStore.AddAsync(issuer, ct: ct).ConfigureAwait(false);
}
catch (ArgumentException)
{
// ignore error if issuer cert already exists
}
}
}
finally
{
issuerStore?.Close();
}
Server.ReportCertificateUpdatedAuditEvent(
context,
objectId,
method,
inputArguments,
certificateGroupId,
certificateTypeId,
m_logger);
}
catch (Exception ex)
{
m_logger.LogError(
Utils.TraceMasks.Security,
ex,
"Failed to update certificate {Certificate}.",
newCert.AsLogSafeString());
throw new ServiceResultException(
StatusCodes.BadSecurityChecksFailed,
"Failed to update certificate.",
ex);
}
}
}
private async ValueTask<CreateSigningRequestMethodStateResult> CreateSigningRequestAsync(
ISystemContext context,
MethodState method,
NodeId objectId,
NodeId certificateGroupId,
NodeId certificateTypeId,
string subjectName,
bool regeneratePrivateKey,
byte[] nonce,
CancellationToken cancellationToken)
{
HasApplicationSecureAdminAccess(context);
ServerCertificateGroup certificateGroup = VerifyGroupAndTypeId(
certificateGroupId,
certificateTypeId);
// identify the existing certificate for which to CreateSigningRequest
// it should be of the same type
CertificateIdentifier existingCertIdentifier = certificateGroup.ApplicationCertificates
.FirstOrDefault(
cert => cert.CertificateType == certificateTypeId);
if (string.IsNullOrEmpty(subjectName))
{
subjectName = existingCertIdentifier.Certificate.Subject;
}
certificateGroup.TemporaryApplicationCertificate?.Dispose();
certificateGroup.TemporaryApplicationCertificate = null;
X509Certificate2 certWithPrivateKey;
if (regeneratePrivateKey)
{
IList<string> domainNames = X509Utils.GetDomainsFromCertificate(existingCertIdentifier.Certificate);
certWithPrivateKey = GenerateTemporaryApplicationCertificate(
certificateTypeId,
certificateGroup,
subjectName,
domainNames);
}
else
{
ICertificatePasswordProvider passwordProvider = m_configuration
.SecurityConfiguration
.CertificatePasswordProvider;
certWithPrivateKey = await existingCertIdentifier
.LoadPrivateKeyExAsync(passwordProvider,
m_configuration.ApplicationUri,
Server.Telemetry,
cancellationToken)
.ConfigureAwait(false);
if (certWithPrivateKey == null)
{
throw ServiceResultException.Create(StatusCodes.BadInternalError, "Failed to load private key");
}
}
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Create signing request {Certificate}",
certWithPrivateKey.AsLogSafeString());
byte[] certificateRequest = CertificateFactory.CreateSigningRequest(
certWithPrivateKey,
X509Utils.GetDomainsFromCertificate(certWithPrivateKey));
return new CreateSigningRequestMethodStateResult
{
ServiceResult = ServiceResult.Good,
CertificateRequest = certificateRequest
};
}
private X509Certificate2 GenerateTemporaryApplicationCertificate(
NodeId certificateTypeId,
ServerCertificateGroup certificateGroup,
string subjectName,
IList<string> domainNames)
{
X509Certificate2 certificate;
ICertificateBuilder certificateBuilder = CertificateFactory
.CreateCertificate(m_configuration.ApplicationUri, m_configuration.ApplicationName, subjectName, domainNames)
.SetNotBefore(DateTime.Today.AddDays(-1))
.SetNotAfter(DateTime.Today.AddDays(14));
if (certificateTypeId.IsNull ||
certificateTypeId == ObjectTypeIds.ApplicationCertificateType ||
certificateTypeId == ObjectTypeIds.RsaMinApplicationCertificateType ||
certificateTypeId == ObjectTypeIds.RsaSha256ApplicationCertificateType)
{
certificate = certificateBuilder.SetRSAKeySize(CertificateFactory.DefaultKeySize)
.CreateForRSA();
}
else
{
ECCurve? curve =
CryptoUtils.GetCurveFromCertificateTypeId(certificateTypeId)
?? throw new ServiceResultException(
StatusCodes.BadNotSupported,
"The Ecc certificate type is not supported.");
certificate = certificateBuilder.SetECCurve(curve.Value).CreateForECDsa();
}
certificateGroup.TemporaryApplicationCertificate = certificate;
return certificate;
}
private ServiceResult ApplyChanges(
ISystemContext context,
MethodState method,
NodeId objectId,
VariantCollection inputArguments,
VariantCollection outputArguments)
{
HasApplicationSecureAdminAccess(context);
bool disconnectSessions = false;
foreach (ServerCertificateGroup certificateGroup in m_certificateGroups)
{
try
{
UpdateCertificateData updateCertificate = certificateGroup.UpdateCertificate;
if (updateCertificate != null)
{
disconnectSessions = true;
m_logger.LogInformation(
Utils.TraceMasks.Security,
"Apply Changes for certificate {Certificate}",
updateCertificate.CertificateWithPrivateKey.AsLogSafeString());
}
}
finally
{
certificateGroup.UpdateCertificate = null;
}
}
if (disconnectSessions)
{
// When a Server Certificate or TrustList changes active SecureChannels
// are not immediately affected. This ensures the caller of ApplyChanges