-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathUaTcpSecureChannel.cs
1741 lines (1556 loc) · 85.2 KB
/
UaTcpSecureChannel.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
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) Converter Systems LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Microsoft.Extensions.Logging;
using Microsoft.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace Workstation.ServiceModel.Ua.Channels
{
/// <summary>
/// A secure channel for communicating with OPC UA servers using the UA TCP transport profile.
/// </summary>
public class UaTcpSecureChannel : UaTcpTransportChannel, IRequestChannel, IEncodingContext
{
/// <summary>
/// The default timeout for requests.
/// </summary>
public const uint DefaultTimeoutHint = 15 * 1000; // 15 seconds
/// <summary>
/// the default diagnostic flags for requests.
/// </summary>
public const uint DefaultDiagnosticsHint = (uint)DiagnosticFlags.None;
private const int _sequenceHeaderSize = 8;
private const int _tokenRequestedLifetime = 60 * 60 * 1000; // 60 minutes
private static readonly SecureRandom _rng = new SecureRandom();
private static readonly RecyclableMemoryStreamManager _streamManager = new RecyclableMemoryStreamManager();
private readonly CancellationTokenSource _channelCts;
private readonly ILogger? _logger;
private readonly SemaphoreSlim _sendingSemaphore = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _receivingSemaphore = new SemaphoreSlim(1, 1);
private readonly ActionBlock<ServiceOperation> _pendingRequests;
private readonly ConcurrentDictionary<uint, ServiceOperation> _pendingCompletions;
private readonly X509CertificateParser _certificateParser = new X509CertificateParser();
private int _handle;
private int _sequenceNumber;
private uint _currentClientTokenId;
private uint _currentServerTokenId;
private byte[]? _clientSigningKey;
private byte[]? _clientEncryptingKey;
private byte[]? _clientInitializationVector;
private byte[]? _serverSigningKey;
private byte[]? _serverEncryptingKey;
private byte[]? _serverInitializationVector;
private byte[]? _encryptionBuffer;
private Task? _receiveResponsesTask;
private int _asymLocalKeySize;
private int _asymRemoteKeySize;
private int _asymLocalPlainTextBlockSize;
private int _asymLocalCipherTextBlockSize;
private int _asymLocalSignatureSize;
private int _asymRemotePlainTextBlockSize;
private int _asymRemoteCipherTextBlockSize;
private int _asymRemoteSignatureSize;
private bool _asymIsSigned;
private bool _asymIsEncrypted;
private int _symEncryptionBlockSize;
private int _symEncryptionKeySize;
private int _symSignatureSize;
private bool _symIsSigned;
private bool _symIsEncrypted;
private int _symSignatureKeySize;
private int _nonceSize;
private byte[]? _sendBuffer;
private byte[]? _receiveBuffer;
private IBufferedCipher? _asymEncryptor;
private IBufferedCipher? _asymDecryptor;
private IBufferedCipher? _symEncryptor;
private IBufferedCipher? _symDecryptor;
private ISigner? _asymSigner;
private ISigner? _asymVerifier;
private IMac? _symSigner;
private IMac? _symVerifier;
private DateTime _tokenRenewalTime = DateTime.MaxValue;
private IDigest? _thumbprintDigest;
/// <summary>
/// Initializes a new instance of the <see cref="UaTcpSecureChannel"/> class.
/// </summary>
/// <param name="localDescription">The local description.</param>
/// <param name="certificateStore">The local certificate store.</param>
/// <param name="remoteEndpoint">The remote endpoint</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="options">The secure channel options.</param>
public UaTcpSecureChannel(
ApplicationDescription localDescription,
ICertificateStore? certificateStore,
EndpointDescription remoteEndpoint,
ILoggerFactory? loggerFactory = null,
UaTcpSecureChannelOptions? options = null)
: base(remoteEndpoint, loggerFactory, options)
{
LocalDescription = localDescription ?? throw new ArgumentNullException(nameof(localDescription));
CertificateStore = certificateStore;
TimeoutHint = options?.TimeoutHint ?? DefaultTimeoutHint;
DiagnosticsHint = options?.DiagnosticsHint ?? DefaultDiagnosticsHint;
_logger = loggerFactory?.CreateLogger<UaTcpSecureChannel>();
AuthenticationToken = null;
NamespaceUris = new List<string> { "http://opcfoundation.org/UA/" };
ServerUris = new List<string>();
_channelCts = new CancellationTokenSource();
_pendingRequests = new ActionBlock<ServiceOperation>(t => SendRequestActionAsync(t), new ExecutionDataflowBlockOptions { CancellationToken = _channelCts.Token });
_pendingCompletions = new ConcurrentDictionary<uint, ServiceOperation>();
}
/// <summary>
/// Gets the local description.
/// </summary>
public ApplicationDescription LocalDescription { get; }
/// <summary>
/// Gets the certificate store.
/// </summary>
public ICertificateStore? CertificateStore { get; }
/// <summary>
/// Gets the default number of milliseconds that may elapse before an operation is cancelled by the service.
/// </summary>
public uint TimeoutHint { get; }
/// <summary>
/// Gets the default diagnostics flags to be requested by the service.
/// </summary>
public uint DiagnosticsHint { get; }
/// <summary>
/// Gets the local certificate.
/// </summary>
protected byte[]? LocalCertificate { get; private set; }
/// <summary>
/// Gets the remote certificate.
/// </summary>
protected byte[]? RemoteCertificate => RemoteEndpoint?.ServerCertificate;
/// <summary>
/// Gets the local private key.
/// </summary>
protected RsaKeyParameters? LocalPrivateKey { get; private set; }
/// <summary>
/// Gets the remote public key.
/// </summary>
protected RsaKeyParameters? RemotePublicKey { get; private set; }
/// <summary>
/// Gets the local nonce.
/// </summary>
protected byte[]? LocalNonce { get; private set; }
/// <summary>
/// Gets or sets the channel id.
/// </summary>
public uint ChannelId { get; protected set; }
/// <summary>
/// Gets or sets the token id.
/// </summary>
public uint TokenId { get; protected set; }
/// <summary>
/// Gets or sets the authentication token.
/// </summary>
public NodeId? AuthenticationToken { get; protected set; }
/// <summary>
/// Gets or sets the namespace uris.
/// </summary>
public IReadOnlyList<string> NamespaceUris { get; protected set; }
/// <summary>
/// Gets or sets the server uris.
/// </summary>
public IReadOnlyList<string> ServerUris { get; protected set; }
public int MaxStringLength => 65535;
public int MaxArrayLength => 65535;
public int MaxByteStringLength => 65535;
/// <summary>
/// Sends a <see cref="T:Workstation.ServiceModel.Ua.IServiceRequest"/> to the server.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public virtual async Task<IServiceResponse> RequestAsync(IServiceRequest request, CancellationToken token = default)
{
ThrowIfClosedOrNotOpening();
TimestampHeader(request);
var operation = new ServiceOperation(request);
// TimestampHeader takes care that the RequestHeader property will not be null
using (var timeoutCts = new CancellationTokenSource((int)request.RequestHeader!.TimeoutHint))
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, _channelCts.Token, token))
using (var registration = linkedCts.Token.Register(o => ((ServiceOperation)o!).TrySetException(new ServiceResultException(StatusCodes.BadRequestTimeout)), operation, false))
{
if (_pendingRequests.Post(operation))
{
return await operation.Task.ConfigureAwait(false);
}
throw new ServiceResultException(StatusCodes.BadSecureChannelClosed);
}
}
/// <inheritdoc/>
protected override async Task OnOpeningAsync(CancellationToken token)
{
await base.OnOpeningAsync(token).ConfigureAwait(false);
if (RemoteCertificate != null)
{
var cert = _certificateParser.ReadCertificate(RemoteCertificate);
if (cert != null)
{
if (CertificateStore != null)
{
var result = await CertificateStore.ValidateRemoteCertificateAsync(cert, _logger);
if (!result)
{
throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "Remote certificate is untrusted.");
}
}
RemotePublicKey = cert.GetPublicKey() as RsaKeyParameters;
}
}
if (RemoteEndpoint.SecurityMode == MessageSecurityMode.SignAndEncrypt)
{
if (LocalCertificate == null && CertificateStore != null)
{
var tuple = await CertificateStore.GetLocalCertificateAsync(LocalDescription, _logger);
LocalCertificate = tuple.Certificate?.GetEncoded();
LocalPrivateKey = tuple.Key;
}
if (LocalPrivateKey == null)
{
throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "LocalPrivateKey is null.");
}
if (RemotePublicKey == null)
{
throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "RemotePublicKey is null.");
}
switch (RemoteEndpoint.SecurityPolicyUri)
{
case SecurityPolicyUris.Basic128Rsa15:
_asymSigner = SignerUtilities.GetSigner("SHA-1withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-1withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha1Digest());
_symVerifier = new HMac(new Sha1Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 11, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 11, 1);
_symSignatureSize = 20;
_symSignatureKeySize = 16;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 16;
_nonceSize = 16;
break;
case SecurityPolicyUris.Basic256:
_asymSigner = SignerUtilities.GetSigner("SHA-1withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-1withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha1Digest());
_symVerifier = new HMac(new Sha1Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 20;
_symSignatureKeySize = 24;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
case SecurityPolicyUris.Basic256Sha256:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 16;
_nonceSize = 32;
break;
case SecurityPolicyUris.Aes256_Sha256_RsaPss:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 66, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 66, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
default:
throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected);
}
_asymIsSigned = _asymIsEncrypted = true;
_symIsSigned = true;
_symIsEncrypted = true;
_asymLocalSignatureSize = _asymLocalKeySize / 8;
_asymLocalCipherTextBlockSize = Math.Max(_asymLocalKeySize / 8, 1);
_asymRemoteSignatureSize = _asymRemoteKeySize / 8;
_asymRemoteCipherTextBlockSize = Math.Max(_asymRemoteKeySize / 8, 1);
_clientSigningKey = new byte[_symSignatureKeySize];
_clientEncryptingKey = new byte[_symEncryptionKeySize];
_clientInitializationVector = new byte[_symEncryptionBlockSize];
_serverSigningKey = new byte[_symSignatureKeySize];
_serverEncryptingKey = new byte[_symEncryptionKeySize];
_serverInitializationVector = new byte[_symEncryptionBlockSize];
_encryptionBuffer = new byte[LocalSendBufferSize];
_thumbprintDigest = DigestUtilities.GetDigest("SHA-1");
}
else if (RemoteEndpoint.SecurityMode == MessageSecurityMode.Sign)
{
if (LocalCertificate == null && CertificateStore != null)
{
var tuple = await CertificateStore.GetLocalCertificateAsync(LocalDescription, _logger);
LocalCertificate = tuple.Certificate?.GetEncoded();
LocalPrivateKey = tuple.Key;
}
if (LocalPrivateKey == null)
{
throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "LocalPrivateKey is null.");
}
if (RemotePublicKey == null)
{
throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "RemotePublicKey is null.");
}
switch (RemoteEndpoint.SecurityPolicyUri)
{
case SecurityPolicyUris.Basic128Rsa15:
_asymSigner = SignerUtilities.GetSigner("SHA-1withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-1withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha1Digest());
_symVerifier = new HMac(new Sha1Digest());
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 11, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 11, 1);
_symSignatureSize = 20;
_symSignatureKeySize = 16;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 16;
_nonceSize = 16;
break;
case SecurityPolicyUris.Basic256:
_asymSigner = SignerUtilities.GetSigner("SHA-1withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-1withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha1Digest());
_symVerifier = new HMac(new Sha1Digest());
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 20;
_symSignatureKeySize = 24;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
case SecurityPolicyUris.Basic256Sha256:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSA");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSA");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 42, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 42, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 16;
_nonceSize = 32;
break;
case SecurityPolicyUris.Aes256_Sha256_RsaPss:
_asymSigner = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
_asymSigner.Init(true, LocalPrivateKey);
_asymVerifier = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
_asymVerifier.Init(false, RemotePublicKey);
_asymEncryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
_asymEncryptor.Init(true, RemotePublicKey);
_asymDecryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
_asymDecryptor.Init(false, LocalPrivateKey);
_symSigner = new HMac(new Sha256Digest());
_symVerifier = new HMac(new Sha256Digest());
_symEncryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_symDecryptor = CipherUtilities.GetCipher("AES/CBC/NoPadding");
_asymLocalKeySize = LocalPrivateKey.Modulus.BitLength;
_asymRemoteKeySize = RemotePublicKey.Modulus.BitLength;
_asymLocalPlainTextBlockSize = Math.Max((_asymLocalKeySize / 8) - 66, 1);
_asymRemotePlainTextBlockSize = Math.Max((_asymRemoteKeySize / 8) - 66, 1);
_symSignatureSize = 32;
_symSignatureKeySize = 32;
_symEncryptionBlockSize = 16;
_symEncryptionKeySize = 32;
_nonceSize = 32;
break;
default:
throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected);
}
_asymIsSigned = _asymIsEncrypted = true;
_symIsSigned = true;
_symIsEncrypted = false;
_asymLocalSignatureSize = _asymLocalKeySize / 8;
_asymLocalCipherTextBlockSize = Math.Max(_asymLocalKeySize / 8, 1);
_asymRemoteSignatureSize = _asymRemoteKeySize / 8;
_asymRemoteCipherTextBlockSize = Math.Max(_asymRemoteKeySize / 8, 1);
_clientSigningKey = new byte[_symSignatureKeySize];
_clientEncryptingKey = new byte[_symEncryptionKeySize];
_clientInitializationVector = new byte[_symEncryptionBlockSize];
_serverSigningKey = new byte[_symSignatureKeySize];
_serverEncryptingKey = new byte[_symEncryptionKeySize];
_serverInitializationVector = new byte[_symEncryptionBlockSize];
_encryptionBuffer = new byte[LocalSendBufferSize];
_thumbprintDigest = DigestUtilities.GetDigest("SHA-1");
}
else if (RemoteEndpoint.SecurityMode == MessageSecurityMode.None)
{
_asymIsSigned = _asymIsEncrypted = false;
_symIsSigned = _symIsEncrypted = false;
_asymLocalKeySize = 0;
_asymRemoteKeySize = 0;
_asymLocalSignatureSize = 0;
_asymLocalCipherTextBlockSize = 1;
_asymRemoteSignatureSize = 0;
_asymRemoteCipherTextBlockSize = 1;
_asymLocalPlainTextBlockSize = 1;
_asymRemotePlainTextBlockSize = 1;
_symSignatureSize = 0;
_symSignatureKeySize = 0;
_symEncryptionBlockSize = 1;
_symEncryptionKeySize = 0;
_nonceSize = 0;
_encryptionBuffer = null;
}
else
{
throw new ServiceResultException(StatusCodes.BadSecurityModeRejected);
}
}
/// <inheritdoc/>
/// <seealso href="https://reference.opcfoundation.org/v104/Core/docs/Part4/5.5.2/">OPC UA specification Part 4: Services, 5.5.2</seealso>
protected override async Task OnOpenAsync(CancellationToken token = default)
{
await base.OnOpenAsync(token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
_sendBuffer = new byte[LocalSendBufferSize];
_receiveBuffer = new byte[LocalReceiveBufferSize];
_receiveResponsesTask = ReceiveResponsesAsync(_channelCts.Token);
var openSecureChannelRequest = new OpenSecureChannelRequest
{
ClientProtocolVersion = ProtocolVersion,
RequestType = SecurityTokenRequestType.Issue,
SecurityMode = RemoteEndpoint.SecurityMode,
ClientNonce = _symIsSigned ? LocalNonce = GetNextNonce(_nonceSize) : null,
RequestedLifetime = _tokenRequestedLifetime
};
var openSecureChannelResponse = (OpenSecureChannelResponse)await RequestAsync(openSecureChannelRequest).ConfigureAwait(false);
if (openSecureChannelResponse.ServerProtocolVersion < ProtocolVersion)
{
throw new ServiceResultException(StatusCodes.BadProtocolVersionUnsupported);
}
}
/// <inheritdoc/>
/// <seealso href="https://reference.opcfoundation.org/v104/Core/docs/Part4/5.5.3/">OPC UA specification Part 4: Services, 5.5.3</seealso>
protected override async Task OnCloseAsync(CancellationToken token = default)
{
try
{
var request = new CloseSecureChannelRequest { RequestHeader = new RequestHeader { TimeoutHint = TimeoutHint, ReturnDiagnostics = DiagnosticsHint } };
await RequestAsync(request).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogError($"Error closing secure channel. {ex.Message}");
}
await base.OnCloseAsync(token).ConfigureAwait(false);
}
/// <inheritdoc/>
protected override async Task OnAbortAsync(CancellationToken token = default)
{
await base.OnAbortAsync(token).ConfigureAwait(false);
}
/// <summary>
/// Calculate the pseudo random function.
/// </summary>
/// <param name="secret">The secret.</param>
/// <param name="seed">The seed.</param>
/// <param name="sizeBytes">The size in bytes.</param>
/// <param name="securityPolicyUri">The securityPolicyUri.</param>
/// <returns>A array of bytes.</returns>
private static byte[] CalculatePSHA(byte[] secret, byte[] seed, int sizeBytes, string securityPolicyUri)
{
IDigest digest;
switch (securityPolicyUri)
{
case SecurityPolicyUris.Basic128Rsa15:
case SecurityPolicyUris.Basic256:
digest = new Sha1Digest();
break;
case SecurityPolicyUris.Basic256Sha256:
case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
case SecurityPolicyUris.Aes256_Sha256_RsaPss:
digest = new Sha256Digest();
break;
default:
digest = new Sha1Digest();
break;
}
HMac mac = new HMac(digest);
byte[] output = new byte[sizeBytes];
mac.Init(new KeyParameter(secret));
byte[] a = seed;
int size = digest.GetDigestSize();
int iterations = (output.Length + size - 1) / size;
byte[] buf = new byte[mac.GetMacSize()];
byte[] buf2 = new byte[mac.GetMacSize()];
for (int i = 0; i < iterations; i++)
{
mac.BlockUpdate(a, 0, a.Length);
mac.DoFinal(buf, 0);
a = buf;
mac.BlockUpdate(a, 0, a.Length);
mac.BlockUpdate(seed, 0, seed.Length);
mac.DoFinal(buf2, 0);
Array.Copy(buf2, 0, output, size * i, Math.Min(size, output.Length - (size * i)));
}
return output;
}
/// <summary>
/// Send service request on transport channel.
/// </summary>
/// <param name="operation">A service operation.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task SendRequestActionAsync(ServiceOperation operation)
{
try
{
if (operation.Task.Status == TaskStatus.WaitingForActivation)
{
await SendRequestAsync(operation, _channelCts.Token).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger?.LogError($"Error sending request. {ex.Message}");
await FaultAsync(ex).ConfigureAwait(false);
}
}
/// <summary>
/// Send service request on transport channel.
/// </summary>
/// <param name="operation">A service operation.</param>
/// <param name="token">A cancellation token</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task SendRequestAsync(ServiceOperation operation, CancellationToken token = default)
{
await _sendingSemaphore.WaitAsync(token).ConfigureAwait(false);
var request = operation.Request;
try
{
ThrowIfClosedOrNotOpening();
// Check if time to renew security token.
if (DateTime.UtcNow > _tokenRenewalTime)
{
_tokenRenewalTime = _tokenRenewalTime.AddMilliseconds(60000);
var openSecureChannelRequest = new OpenSecureChannelRequest
{
RequestHeader = new RequestHeader
{
TimeoutHint = TimeoutHint,
ReturnDiagnostics = DiagnosticsHint,
Timestamp = DateTime.UtcNow,
RequestHandle = GetNextHandle(),
AuthenticationToken = AuthenticationToken
},
ClientProtocolVersion = ProtocolVersion,
RequestType = SecurityTokenRequestType.Renew,
SecurityMode = RemoteEndpoint.SecurityMode,
ClientNonce = _symIsSigned ? LocalNonce = GetNextNonce(_nonceSize) : null,
RequestedLifetime = _tokenRequestedLifetime
};
_logger?.LogTrace($"Sending {openSecureChannelRequest.GetType().Name}, Handle: {openSecureChannelRequest.RequestHeader.RequestHandle}");
_pendingCompletions.TryAdd(openSecureChannelRequest.RequestHeader.RequestHandle, new ServiceOperation(openSecureChannelRequest));
await SendOpenSecureChannelRequestAsync(openSecureChannelRequest, token).ConfigureAwait(false);
}
// RequestAsync takes care that every request has a non-null header
var header = request.RequestHeader!;
header.RequestHandle = GetNextHandle();
header.AuthenticationToken = AuthenticationToken;
_logger?.LogTrace($"Sending {request.GetType().Name}, Handle: {header.RequestHandle}");
_pendingCompletions.TryAdd(header.RequestHandle, operation);
if (request is OpenSecureChannelRequest)
{
await SendOpenSecureChannelRequestAsync((OpenSecureChannelRequest)request, token).ConfigureAwait(false);
}
else if (request is CloseSecureChannelRequest)
{
await SendCloseSecureChannelRequestAsync((CloseSecureChannelRequest)request, token).ConfigureAwait(false);
operation.TrySetResult(new CloseSecureChannelResponse { ResponseHeader = new ResponseHeader { RequestHandle = header.RequestHandle, Timestamp = DateTime.UtcNow } });
}
else
{
await SendServiceRequestAsync(request, token).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger?.LogError($"Error sending {request.GetType().Name}, Handle: {request.RequestHeader!.RequestHandle}. {ex.Message}");
throw;
}
finally
{
_sendingSemaphore.Release();
}
}
/// <summary>
/// Send open secure channel service request on transport channel.
/// </summary>
/// <param name="request">A service request</param>
/// <param name="token">A cancellation token</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task SendOpenSecureChannelRequestAsync(OpenSecureChannelRequest request, CancellationToken token)
{
var bodyStream = _streamManager.GetStream("SendOpenSecureChannelRequestAsync");
var bodyEncoder = new BinaryEncoder(bodyStream, this);
try
{
bodyEncoder.WriteRequest(request);
bodyStream.Position = 0;
if (RemoteMaxMessageSize > 0 && bodyStream.Length > RemoteMaxMessageSize)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
}
// write chunks
int chunkCount = 0;
int bodyCount = (int)(bodyStream.Length - bodyStream.Position);
while (bodyCount > 0)
{
chunkCount++;
if (RemoteMaxChunkCount > 0 && chunkCount > RemoteMaxChunkCount)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
}
var stream = new MemoryStream(_sendBuffer!, 0, (int)RemoteReceiveBufferSize, true, true);
var encoder = new BinaryEncoder(stream, this);
try
{
// header
encoder.WriteUInt32(null, UaTcpMessageTypes.OPNF);
encoder.WriteUInt32(null, 0u);
encoder.WriteUInt32(null, ChannelId);
// asymmetric security header
encoder.WriteString(null, RemoteEndpoint.SecurityPolicyUri);
if (RemoteEndpoint.SecurityMode != MessageSecurityMode.None)
{
encoder.WriteByteString(null, LocalCertificate);
byte[] thumbprint = new byte[_thumbprintDigest!.GetDigestSize()];
_thumbprintDigest.BlockUpdate(RemoteCertificate, 0, RemoteCertificate!.Length);
_thumbprintDigest.DoFinal(thumbprint, 0);
encoder.WriteByteString(null, thumbprint);
}
else
{
encoder.WriteByteString(null, null);
encoder.WriteByteString(null, null);
}
int plainHeaderSize = encoder.Position;
// sequence header
encoder.WriteUInt32(null, GetNextSequenceNumber());
encoder.WriteUInt32(null, request.RequestHeader!.RequestHandle);
// body
int paddingHeaderSize;
int maxBodySize;
int bodySize;
int paddingSize;
int chunkSize;
if (_asymIsEncrypted)
{
paddingHeaderSize = _asymRemoteCipherTextBlockSize > 256 ? 2 : 1;
maxBodySize = ((((int)RemoteReceiveBufferSize - plainHeaderSize) / _asymRemoteCipherTextBlockSize) * _asymRemotePlainTextBlockSize) - _sequenceHeaderSize - paddingHeaderSize - _asymLocalSignatureSize;
if (bodyCount < maxBodySize)
{
bodySize = bodyCount;
paddingSize = (_asymRemotePlainTextBlockSize - ((_sequenceHeaderSize + bodySize + paddingHeaderSize + _asymLocalSignatureSize) % _asymRemotePlainTextBlockSize)) % _asymRemotePlainTextBlockSize;
}
else
{
bodySize = maxBodySize;
paddingSize = 0;
}
chunkSize = plainHeaderSize + (((_sequenceHeaderSize + bodySize + paddingSize + paddingHeaderSize + _asymLocalSignatureSize) / _asymRemotePlainTextBlockSize) * _asymRemoteCipherTextBlockSize);
}
else
{
paddingHeaderSize = 0;
paddingSize = 0;
maxBodySize = (int)RemoteReceiveBufferSize - plainHeaderSize - _sequenceHeaderSize - _asymLocalSignatureSize;
if (bodyCount < maxBodySize)
{
bodySize = bodyCount;
}
else
{
bodySize = maxBodySize;
}
chunkSize = plainHeaderSize + _sequenceHeaderSize + bodySize + _asymLocalSignatureSize;
}
bodyStream.Read(_sendBuffer!, encoder.Position, bodySize);
encoder.Position += bodySize;
bodyCount -= bodySize;
// padding
if (_asymIsEncrypted)
{
byte paddingByte = (byte)(paddingSize & 0xFF);
encoder.WriteByte(null, paddingByte);
for (int i = 0; i < paddingSize; i++)
{
encoder.WriteByte(null, paddingByte);
}
if (paddingHeaderSize == 2)
{
byte extraPaddingByte = (byte)((paddingSize >> 8) & 0xFF);
encoder.WriteByte(null, extraPaddingByte);
}
}
// update message type and (encrypted) length
var position = encoder.Position;
encoder.Position = 3;
encoder.WriteByte(null, bodyCount > 0 ? (byte)'C' : (byte)'F');
encoder.WriteUInt32(null, (uint)chunkSize);
encoder.Position = position;
// sign
if (_asymIsSigned)
{
// sign with local private key.
_asymSigner!.BlockUpdate(_sendBuffer, 0, position);
byte[] signature = _asymSigner.GenerateSignature();
Debug.Assert(signature.Length == _asymLocalSignatureSize, nameof(_asymLocalSignatureSize));
encoder.Write(signature, 0, _asymLocalSignatureSize);
}
// encrypt
if (_asymIsEncrypted)
{
position = encoder.Position;
Buffer.BlockCopy(_sendBuffer!, 0, _encryptionBuffer!, 0, plainHeaderSize);
byte[] plainText = new byte[_asymRemotePlainTextBlockSize];
int jj = plainHeaderSize;
for (int ii = plainHeaderSize; ii < position; ii += _asymRemotePlainTextBlockSize)
{
Buffer.BlockCopy(_sendBuffer!, ii, plainText, 0, _asymRemotePlainTextBlockSize);
// encrypt with remote public key.
byte[] cipherText = _asymEncryptor!.DoFinal(plainText);
Debug.Assert(cipherText.Length == _asymRemoteCipherTextBlockSize, nameof(_asymRemoteCipherTextBlockSize));
Buffer.BlockCopy(cipherText, 0, _encryptionBuffer!, jj, _asymRemoteCipherTextBlockSize);
jj += _asymRemoteCipherTextBlockSize;
}
await SendAsync(_encryptionBuffer!, 0, jj, token).ConfigureAwait(false);
return;
}
// pass buffer to transport
await SendAsync(_sendBuffer!, 0, encoder.Position, token).ConfigureAwait(false);
}
finally
{
encoder.Dispose();
}
}
}
finally
{
bodyEncoder.Dispose(); // also disposes stream.
}
}
/// <summary>
/// Send close secure channel request on transport channel.
/// </summary>
/// <param name="request">A service request</param>
/// <param name="token">A cancellation token</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task SendCloseSecureChannelRequestAsync(CloseSecureChannelRequest request, CancellationToken token)
{
var bodyStream = _streamManager.GetStream("SendCloseSecureChannelRequestAsync");
var bodyEncoder = new BinaryEncoder(bodyStream, this);
try
{
bodyEncoder.WriteRequest(request);
bodyStream.Position = 0;
if (RemoteMaxMessageSize > 0 && bodyStream.Length > RemoteMaxMessageSize)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
}
// write chunks
int chunkCount = 0;
int bodyCount = (int)(bodyStream.Length - bodyStream.Position);
while (bodyCount > 0)
{
chunkCount++;
if (RemoteMaxChunkCount > 0 && chunkCount > RemoteMaxChunkCount)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
}
var stream = new MemoryStream(_sendBuffer!, 0, (int)RemoteReceiveBufferSize, true, true);