diff --git a/Applications/ConsoleReferenceClient/ClientSamples.cs b/Applications/ConsoleReferenceClient/ClientSamples.cs index 6f85b169f5..9e2952d8f3 100644 --- a/Applications/ConsoleReferenceClient/ClientSamples.cs +++ b/Applications/ConsoleReferenceClient/ClientSamples.cs @@ -862,7 +862,7 @@ namespace Quickstarts result.Sort((x, y) => x.NodeId.CompareTo(y.NodeId)); m_logger.LogInformation( - "ManagedBrowseFullAddressSpace found {Count} references on server in {Duration}ms.", + "ManagedBrowseFullAddressSpace found {Count} references on server in {Duration} ms.", result.Count, stopWatch.ElapsedMilliseconds); @@ -1083,7 +1083,7 @@ namespace Quickstarts result.Sort((x, y) => x.NodeId.CompareTo(y.NodeId)); m_logger.LogInformation( - "BrowseFullAddressSpace found {Count} references on server in {Duration}ms.", + "BrowseFullAddressSpace found {Count} references on server in {Duration} ms.", referenceDescriptions.Count, stopWatch.ElapsedMilliseconds); diff --git a/Applications/ConsoleReferenceClient/Quickstarts.ReferenceClient.Config.xml b/Applications/ConsoleReferenceClient/Quickstarts.ReferenceClient.Config.xml index f067984d1d..790439a676 100644 --- a/Applications/ConsoleReferenceClient/Quickstarts.ReferenceClient.Config.xml +++ b/Applications/ConsoleReferenceClient/Quickstarts.ReferenceClient.Config.xml @@ -91,11 +91,11 @@ 65535 4194304 65535 - 300000 + 30000 30000 - 60000 + 600000 opc.tcp://{0}:4840 http://{0}:52601/UADiscovery diff --git a/Applications/ConsoleReferenceClient/RunConnectAll.cs b/Applications/ConsoleReferenceClient/RunConnectAll.cs index 0d0c22281e..50c5500ec6 100644 --- a/Applications/ConsoleReferenceClient/RunConnectAll.cs +++ b/Applications/ConsoleReferenceClient/RunConnectAll.cs @@ -25,13 +25,40 @@ namespace SecurityTestClient private ISession m_session; const string ServerUrl = "opc.tcp://localhost:62541"; - //const string ServerUrl = "opc.tcp://WhiteCat:4880/Softing/OpcUa/TestServer"; + const string UserName = "sysadmin"; + const string Password = "demo12"; + const bool supportsX509 = true; + + //const string ServerUrl = "opc.tcp://10.103.19.71:52520/OPCUA/SampleConsoleServer"; + //const string UserName = "opcua"; + //const string Password = "opcua"; + //static bool supportsX509 = false; + + //const string ServerUrl = "opc.tcp://10.103.141.179:4840"; + //const string UserName = "iop"; + //const string Password = "test"; + //static bool supportsX509 = false; + + //const string ServerUrl = "opc.tcp://78.46.151.116:4840"; + //const string UserName = "user1"; + //const string Password = "passsword"; + //static bool supportsX509 = false; + + //const string ServerUrl = "opc.tcp://10.103.119.62:4888/Softing/OpcUa/TestServer"; + //const string UserName = "usr"; + //const string Password = "pwd"; + //const bool supportsX509 = true; + + static string TargetPolicy = SecurityPolicies.ECC_nistP256_AesGcm; + const int kMaxSearchDepth = 128; const int ReconnectPeriod = 1000; const int ReconnectPeriodExponentialBackoff = 15000; public RunConnectAll(ApplicationConfiguration configuration, ITelemetryContext context) { + CryptoTrace.Enabled = true; + m_context = context; m_configuration = configuration; m_logger = context.CreateLogger("Test"); @@ -108,12 +135,11 @@ namespace SecurityTestClient ServerUrl, ct).ConfigureAwait(false); - //endpoints = endpoints.Where(x => x.SecurityPolicyUri == SecurityPolicies.RSA_DH_ChaChaPoly).ToList(); + endpoints = endpoints.Where(x => x.SecurityPolicyUri == TargetPolicy).ToList(); var endpointConfiguration = EndpointConfiguration.Create(m_configuration); var sessionFactory = new DefaultSessionFactory(m_context); - var userNameidentity = new UserIdentity("sysadmin", new UTF8Encoding(false).GetBytes("demo")); - //var userNameidentity = new UserIdentity("usr", new UTF8Encoding(false).GetBytes("pwd")); + var userNameidentity = new UserIdentity(UserName, new UTF8Encoding(false).GetBytes(Password)); foreach (var ii in endpoints) { @@ -123,7 +149,15 @@ namespace SecurityTestClient var certificateIdentity = await LoadUserCertificateAsync(thumbprint, "password", ct).ConfigureAwait(false); - foreach (var identity in new UserIdentity[] { userNameidentity, certificateIdentity }) + var identities = new List + { + new UserIdentity() + }; + + if (!String.IsNullOrEmpty(UserName)) { identities.Add(userNameidentity); } + if (supportsX509) { identities.Add(certificateIdentity); } + + foreach (var identity in identities) { try { @@ -149,7 +183,7 @@ namespace SecurityTestClient m_logger.LogWarning("Waiting for SecureChannel renew"); await session.UpdateSessionAsync(identity, null, ct).ConfigureAwait(false); - for (int count = 0; count < 8; count++) + for (int count = 0; count < 20; count++) { var result = await session.ReadAsync( null, @@ -628,7 +662,7 @@ namespace SecurityTestClient result.Sort((x, y) => x.NodeId.CompareTo(y.NodeId)); m_logger.LogWarning( - "BrowseFullAddressSpace found {Count} references on server in {ElapsedMilliseconds}ms.", + "BrowseFullAddressSpace found {Count} references on server in {ElapsedMilliseconds} ms.", referenceDescriptions.Count, stopWatch.ElapsedMilliseconds); diff --git a/Applications/ConsoleReferenceClient/generate_user_certificate.ps1 b/Applications/ConsoleReferenceClient/generate_user_certificate.ps1 index ee938f5431..23e8769a63 100644 --- a/Applications/ConsoleReferenceClient/generate_user_certificate.ps1 +++ b/Applications/ConsoleReferenceClient/generate_user_certificate.ps1 @@ -15,6 +15,62 @@ foreach ($d in @($certDir, $privateDir)) { } } +function New-CertificateWithAKI { + param( + [System.Security.Cryptography.X509Certificates.X509Certificate2] $SourceCert, + [string] $HashAlgorithmName = 'SHA256' + ) + + $hashAlg = [System.Security.Cryptography.HashAlgorithmName]::new($HashAlgorithmName) + + # Determine key type and create CertificateRequest + $ecdsa = [System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions]::GetECDsaPrivateKey($SourceCert) + $rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($SourceCert) + + if ($ecdsa) { + $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new( + $SourceCert.SubjectName, $ecdsa, $hashAlg) + } + elseif ($rsa) { + $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new( + $SourceCert.SubjectName, $rsa, $hashAlg, + [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) + } + else { + throw "Unsupported key type" + } + + # Copy all extensions from source cert + foreach ($ext in $SourceCert.Extensions) { + $req.CertificateExtensions.Add($ext) + } + + # Build Authority Key Identifier from Subject Key Identifier + $skiExt = $SourceCert.Extensions | Where-Object { + $_ -is [System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension] + } + + if ($skiExt) { + $hex = $skiExt.SubjectKeyIdentifier + $keyIdBytes = [byte[]]::new($hex.Length / 2) + for ($i = 0; $i -lt $keyIdBytes.Length; $i++) { + $keyIdBytes[$i] = [System.Convert]::ToByte($hex.Substring($i * 2, 2), 16) + } + # AKI ASN.1: SEQUENCE { [0] IMPLICIT keyIdentifier } + # 30 80 + [byte[]] $akiInner = @(0x80, $keyIdBytes.Length) + $keyIdBytes + [byte[]] $akiValue = @(0x30, $akiInner.Length) + $akiInner + $akiOid = [System.Security.Cryptography.Oid]::new('2.5.29.35', 'Authority Key Identifier') + $akiExt = [System.Security.Cryptography.X509Certificates.X509Extension]::new( + $akiOid, $akiValue, $false) + $req.CertificateExtensions.Add($akiExt) + } + + return $req.CreateSelfSigned( + [DateTimeOffset]::new($SourceCert.NotBefore), + [DateTimeOffset]::new($SourceCert.NotAfter)) +} + # 2. Create a self-signed ECC certificate (NIST P-256) # $cert = New-SelfSignedCertificate ` # -Subject "CN=iama.tester@example.com" ` @@ -28,36 +84,47 @@ foreach ($d in @($certDir, $privateDir)) { foreach ($curve in $curves) { - Write-Host "Generating certificate for curve: $curve" - - $signatureAlgorithm = if ($curve -match 'P384') { 'SHA384' } else { 'SHA256' } + Write-Host "Generating certificate for curve: $curve" - # Create certificate parameters and dynamically insert the curve - $params = @{ - Type = 'Custom' - Subject = 'CN=iama.tester@example.com' - TextExtension = @( - '2.5.29.37={text}1.3.6.1.5.5.7.3.2' - '2.5.29.17={text}upn=iama.tester@example.com' - ) - KeyUsage = @('DigitalSignature', 'NonRepudiation') - KeyAlgorithm = "ECDSA_$curve" # <-- dynamic! - CurveExport = 'CurveName' - HashAlgorithm = $signatureAlgorithm - CertStoreLocation = 'Cert:\CurrentUser\My' - } +$signatureAlgorithm = if ($curve -match 'P384') { 'SHA384' } else { 'SHA256' } - # 1. Create cert - $cert = New-SelfSignedCertificate @params +# OIDs for the extensions +# 2.5.29.14 = Subject Key Identifier +# 2.5.29.35 = Authority Key Identifier +# 2.5.29.19 = Basic Constraints (Subject Type=End Entity or CA) +$name = 'CN=iama.tester@example.com,O=' + $curve; + +$params = @{ + Type = 'Custom' + Subject = $name + TextExtension = @( + '2.5.29.37={text}1.3.6.1.5.5.7.3.2', # Enhanced Key Usage (Client Auth) + '2.5.29.17={text}upn=iama.tester@example.com', # SAN + '2.5.29.19={text}ca=0' # Basic Constraints: Not a CA + ) + KeyUsage = @('DigitalSignature', 'NonRepudiation') # Added KeyCertSign for self-signed logic + KeyAlgorithm = "ECDSA_$curve" + CurveExport = 'CurveName' + HashAlgorithm = $signatureAlgorithm + CertStoreLocation = 'Cert:\CurrentUser\My' + NotAfter = (Get-Date).AddYears(2) # Best practice to set an explicit expiry +} + +# 1. Create cert and rebuild with Authority Key Identifier +$tempCert = New-SelfSignedCertificate @params +$cert = New-CertificateWithAKI -SourceCert $tempCert -HashAlgorithmName $signatureAlgorithm +Remove-Item "Cert:\CurrentUser\My\$($tempCert.Thumbprint)" -Force + +Write-Host "Certificate generated with Thumbprint: $($cert.Thumbprint)" # 2. Export DER $derPath = Join-Path $certDir "iama.tester.$curve.der" - Export-Certificate -Cert $cert -FilePath $derPath -Type CERT + [System.IO.File]::WriteAllBytes($derPath, $cert.RawData) # 3. Export PFX with password - $secret = ConvertTo-SecureString -String "password" -Force -AsPlainText $pfxPath = Join-Path $privateDir "iama.tester.$curve.pfx" - Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $secret + $pfxBytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx, 'password') + [System.IO.File]::WriteAllBytes($pfxPath, $pfxBytes) Write-Host "Finished: $curve`n" } @@ -71,13 +138,18 @@ $rsaParams = @{ '2.5.29.37={text}1.3.6.1.5.5.7.3.2' '2.5.29.17={text}upn=iama.tester@example.com' ) - KeyUsage = @('DigitalSignature','DataEncipherment','NonRepudiation','KeyEncipherment') + KeyUsage = @('DigitalSignature','DataEncipherment','NonRepudiation','KeyEncipherment', 'CertSign') KeyAlgorithm = 'RSA' KeyLength = 2048 CertStoreLocation = 'Cert:\CurrentUser\My' } -$rsaCert = New-SelfSignedCertificate @rsaParams +$tempRsaCert = New-SelfSignedCertificate @rsaParams +$rsaCert = New-CertificateWithAKI -SourceCert $tempRsaCert -HashAlgorithmName 'SHA256' +Remove-Item "Cert:\CurrentUser\My\$($tempRsaCert.Thumbprint)" -Force -Export-Certificate -Cert $rsaCert -FilePath (Join-Path $certDir "iama.tester.rsa.der") -Type CERT -Export-PfxCertificate -Cert $rsaCert -FilePath (Join-Path $privateDir "iama.tester.rsa.pfx") -Password $secret +$derPath = Join-Path $certDir "iama.tester.rsa.der" +[System.IO.File]::WriteAllBytes($derPath, $rsaCert.RawData) +$pfxPath = Join-Path $privateDir "iama.tester.rsa.pfx" +$pfxBytes = $rsaCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx, 'password') +[System.IO.File]::WriteAllBytes($pfxPath, $pfxBytes) diff --git a/Applications/ConsoleReferenceServer/Quickstarts.ReferenceServer.Config.xml b/Applications/ConsoleReferenceServer/Quickstarts.ReferenceServer.Config.xml index 2f60e9cb95..d3b6a316e6 100644 --- a/Applications/ConsoleReferenceServer/Quickstarts.ReferenceServer.Config.xml +++ b/Applications/ConsoleReferenceServer/Quickstarts.ReferenceServer.Config.xml @@ -123,18 +123,6 @@ + Sign_2 http://opcfoundation.org/UA/SecurityPolicy#ECC_nistP256_AesGcm @@ -151,6 +141,44 @@ SignAndEncrypt_3 http://opcfoundation.org/UA/SecurityPolicy#ECC_nistP256_AesGcm + + + Sign_2 http://opcfoundation.org/UA/SecurityPolicy#RSA_DH_AesGcm @@ -176,64 +214,16 @@ SignAndEncrypt_3 http://opcfoundation.org/UA/SecurityPolicy#RSA_DH_AesGcm - - - - - - - - - - - - - - - - - - - - - - - - - - - - +--> None_1 http://opcfoundation.org/UA/SecurityPolicy#None diff --git a/Libraries/Opc.Ua.Client/Session/Session.cs b/Libraries/Opc.Ua.Client/Session/Session.cs index 436e57f044..8d3de0c65e 100644 --- a/Libraries/Opc.Ua.Client/Session/Session.cs +++ b/Libraries/Opc.Ua.Client/Session/Session.cs @@ -4942,7 +4942,7 @@ namespace Opc.Ua.Client SecurityPolicies.GetInfo(m_userTokenSecurityPolicyUri), key.PublicKey); - m_logger.LogWarning("Updating ServerEphemeralKey: {Key}", CryptoTrace.KeyToString(m_eccServerEphemeralKey.Data)); + m_logger.LogWarning("Updating ServerEphemeralKey: {Key} bytes", m_eccServerEphemeralKey.Data?.Length ?? 0); } } } diff --git a/Libraries/Opc.Ua.Server/Server/StandardServer.cs b/Libraries/Opc.Ua.Server/Server/StandardServer.cs index 0154890748..19296a1fc5 100644 --- a/Libraries/Opc.Ua.Server/Server/StandardServer.cs +++ b/Libraries/Opc.Ua.Server/Server/StandardServer.cs @@ -660,7 +660,7 @@ namespace Opc.Ua.Server Value = new ExtensionObject(key) }); - m_logger.LogWarning("Returning new EphmeralKey: {PublicKey}.", CryptoTrace.KeyToString(key.PublicKey)); + m_logger.LogWarning("Returning new EphmeralKey: {PublicKey} bytes.", key.PublicKey?.Length ?? 0); } else { @@ -700,7 +700,7 @@ namespace Opc.Ua.Server response.Parameters .Add(new KeyValuePair { Key = AdditionalParameterNames.ECDHKey, Value = new ExtensionObject(key) }); - m_logger.LogWarning("Returning new EphmeralKey: {PublicKey}.", CryptoTrace.KeyToString(key.PublicKey)); + m_logger.LogWarning("Returning new EphmeralKey: {PublicKey} bytes.", key.PublicKey?.Length ?? 0); } return response; diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CryptoUtils.cs b/Stack/Opc.Ua.Core/Security/Certificates/CryptoUtils.cs index cc6e55fa91..98b456e8dd 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/CryptoUtils.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/CryptoUtils.cs @@ -1215,16 +1215,24 @@ namespace Opc.Ua /// public static class CryptoTrace { + /// + /// Enabled crypto traces to stdout. + /// + public static bool Enabled { get; set; } = true; + /// /// Starts a trace block. /// public static void Start(ConsoleColor color, string format, params object[] args) { #if DEBUG - Console.ForegroundColor = color; - Console.Write("============ "); - Console.Write(format, args); - Console.WriteLine(" ============"); + if (Enabled) + { + Console.ForegroundColor = color; + Console.Write("============ "); + Console.Write(format, args); + Console.WriteLine(" ============"); + } #endif } @@ -1234,10 +1242,13 @@ namespace Opc.Ua public static void Finish(string format, params object[] args) { #if DEBUG - Console.Write("============ "); - Console.Write(format, args); - Console.WriteLine(" Finished ============"); - Console.ForegroundColor = ConsoleColor.White; + if (Enabled) + { + Console.Write("============ "); + Console.Write(format, args); + Console.WriteLine(" Finished ============"); + Console.ForegroundColor = ConsoleColor.White; + } #endif } @@ -1247,7 +1258,10 @@ namespace Opc.Ua public static void Write(string format, params object[] args) { #if DEBUG - Console.Write(format, args); + if (Enabled) + { + Console.Write(format, args); + } #endif } @@ -1257,7 +1271,10 @@ namespace Opc.Ua public static void WriteLine(string format, params object[] args) { #if DEBUG - Console.WriteLine(format, args); + if (Enabled) + { + Console.WriteLine(format, args); + } #endif } @@ -1267,13 +1284,20 @@ namespace Opc.Ua public static string KeyToString(ArraySegment key) { #if DEBUG - byte[] bytes = new byte[key.Count]; - Buffer.BlockCopy(key.Array ?? [], key.Offset, bytes, 0, key.Count); - return KeyToString(bytes); + if (Enabled) + { + byte[] bytes = new byte[key.Count]; + Buffer.BlockCopy(key.Array ?? [], key.Offset, bytes, 0, key.Count); + return KeyToString(bytes); + } + else + { + return String.Empty; + } #else return String.Empty; #endif - } + } /// /// Returns a debug string for a key. @@ -1281,29 +1305,36 @@ namespace Opc.Ua public static string KeyToString(byte[] key) { #if DEBUG - if (key == null || key.Length == 0) + if (Enabled) { - return "Len=0:---"; + if (key == null || key.Length == 0) + { + return "Len=0:---"; + } + + byte checksum = 0; + + foreach (var item in key) + { + checksum ^= item; + } + + if (key.Length <= 16) + { + return "Len=" + key.Length.ToString(CultureInfo.InvariantCulture) + + ":" + + Utils.ToHexString(key) + + "=>XOR=" + + checksum.ToString(CultureInfo.InvariantCulture); + } + + var text = Utils.ToHexString(key); + return $"Len={key.Length}:{text.Substring(0, 8)}...{text.Substring(text.Length - 8, 8)}=>XOR={checksum}"; } - - byte checksum = 0; - - foreach (var item in key) + else { - checksum ^= item; + return String.Empty; } - - if (key.Length <= 16) - { - return "Len=" + key.Length.ToString(CultureInfo.InvariantCulture) + - ":" + - Utils.ToHexString(key) + - "=>XOR=" + - checksum.ToString(CultureInfo.InvariantCulture); - } - - var text = Utils.ToHexString(key); - return $"Len={key.Length}:{text.Substring(0, 8)}...{text.Substring(text.Length - 8, 8)}=>XOR={checksum}"; #else return String.Empty; #endif diff --git a/Stack/Opc.Ua.Core/Security/Certificates/EncryptedSecret.cs b/Stack/Opc.Ua.Core/Security/Certificates/EncryptedSecret.cs index 21c86173f8..d0cbdf3c35 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/EncryptedSecret.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/EncryptedSecret.cs @@ -210,6 +210,13 @@ namespace Opc.Ua encoder.WriteByteString(null, senderCertificate); encoder.WriteDateTime(null, DateTime.UtcNow); + if (ReceiverNonce?.Data == null) + { + throw new ServiceResultException( + StatusCodes.BadArgumentsMissing, + $"The receiver did not provide an ephemeral key."); + } + byte[] senderNonce = SenderNonce.Data; byte[] receiverNonce = ReceiverNonce.Data; @@ -241,13 +248,13 @@ namespace Opc.Ua { case SymmetricEncryptionAlgorithm.Aes128Cbc: case SymmetricEncryptionAlgorithm.Aes256Cbc: - paddingCount = GetPaddingCount(SecurityPolicy.InitializationVectorLength, encoder.Position - startOfSecret); + paddingCount = GetPaddingCount(SecurityPolicy.InitializationVectorLength, secret.Length, encoder.Position - startOfSecret); tagLength = 0; break; case SymmetricEncryptionAlgorithm.Aes128Gcm: case SymmetricEncryptionAlgorithm.Aes256Gcm: case SymmetricEncryptionAlgorithm.ChaCha20Poly1305: - paddingCount = GetPaddingCount(encryptingKey.Length, encoder.Position - startOfSecret); + paddingCount = GetPaddingCount(16, secret.Length, encoder.Position - startOfSecret); tagLength = SecurityPolicy.SymmetricSignatureLength; break; } @@ -306,13 +313,18 @@ namespace Opc.Ua return message; } - private int GetPaddingCount(int blockSize, int dataLength) + private int GetPaddingCount(int blockSize, int secretLength, int dataLength) { - int paddingCount = blockSize - ((dataLength + 2) % blockSize); + dataLength += 2; // add padding size - if (paddingCount == blockSize) + int paddingCount = + dataLength % blockSize == 0 + ? 0 + : blockSize - dataLength % blockSize; + + if (paddingCount + secretLength < blockSize) { - paddingCount = 0; + paddingCount += blockSize; } return paddingCount; diff --git a/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicies.cs b/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicies.cs index aab7821d92..afffa7223d 100644 --- a/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicies.cs +++ b/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicies.cs @@ -677,6 +677,11 @@ namespace Opc.Ua securityPolicy.Uri); } + if (securityPolicy.SecureChannelEnhancements) + { + signatureData.Signature = null; + } + signatureData.Signature = CryptoUtils.Sign( new ArraySegment(dataToSign), localCertificate, diff --git a/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicyInfo.cs b/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicyInfo.cs index c5122b7bae..b1a35bae16 100644 --- a/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicyInfo.cs +++ b/Stack/Opc.Ua.Core/Security/Constants/SecurityPolicyInfo.cs @@ -113,6 +113,11 @@ namespace Opc.Ua /// public CertificateKeyAlgorithm EphemeralKeyAlgorithm { get; private set; } + /// + /// The algorithm used to calculate the thumbprint of the certificate. + /// + public CertificateThumbprintAlgorithm CertificateThumbprintAlgorithm { get; private set; } + /// /// The length, in bytes, of the Nonces used when opening a SecureChannel. /// @@ -194,13 +199,26 @@ namespace Opc.Ua CryptoTrace.WriteLine($"ClientChannelCertificate={CryptoTrace.KeyToString(clientChannelCertificate)}"); CryptoTrace.WriteLine($"ClientNonce={CryptoTrace.KeyToString(clientNonce)}"); + using HashAlgorithm hash = CertificateThumbprintAlgorithm switch + { + CertificateThumbprintAlgorithm.SHA256 => SHA256.Create(), + CertificateThumbprintAlgorithm.SHA384 => SHA384.Create(), + CertificateThumbprintAlgorithm.SHA512 => SHA512.Create(), + _ => throw new NotSupportedException() + }; + + var serverCertificateHash = serverCertificate != null ? hash.ComputeHash(serverCertificate) : null; + var serverChannelCertificateHash = serverChannelCertificate != null ? hash.ComputeHash(serverChannelCertificate) : null; + var clientCertificateHash = clientCertificate != null ? hash.ComputeHash(clientCertificate) : null; + var clientChannelCertificateHash = clientChannelCertificate != null ? hash.ComputeHash(clientChannelCertificate) : null; + data = Utils.Append( channelThumbprint, serverNonce, - serverCertificate, - serverChannelCertificate, - clientCertificate, - clientChannelCertificate, + serverCertificateHash, + serverChannelCertificateHash, + clientCertificateHash, + clientChannelCertificateHash, clientNonce); } else @@ -240,11 +258,22 @@ namespace Opc.Ua CryptoTrace.WriteLine($"ClientChannelCertificate={CryptoTrace.KeyToString(clientChannelCertificate)}"); CryptoTrace.WriteLine($"ServerNonce={CryptoTrace.KeyToString(serverNonce)}"); + using HashAlgorithm hash = CertificateThumbprintAlgorithm switch + { + CertificateThumbprintAlgorithm.SHA256 => SHA256.Create(), + CertificateThumbprintAlgorithm.SHA384 => SHA384.Create(), + CertificateThumbprintAlgorithm.SHA512 => SHA512.Create(), + _ => throw new NotSupportedException() + }; + + var serverChannelCertificateHash = serverChannelCertificate != null ? hash.ComputeHash(serverChannelCertificate) : null; + var clientChannelCertificateHash = clientChannelCertificate != null ? hash.ComputeHash(clientChannelCertificate) : null; + data = Utils.Append( channelThumbprint, clientNonce, - serverChannelCertificate, - clientChannelCertificate, + serverChannelCertificateHash, + clientChannelCertificateHash, serverNonce); } else @@ -285,12 +314,24 @@ namespace Opc.Ua CryptoTrace.WriteLine($"ClientChannelCertificate={CryptoTrace.KeyToString(clientChannelCertificate)}"); CryptoTrace.WriteLine($"ClientNonce={CryptoTrace.KeyToString(clientNonce)}"); + using HashAlgorithm hash = CertificateThumbprintAlgorithm switch + { + CertificateThumbprintAlgorithm.SHA256 => SHA256.Create(), + CertificateThumbprintAlgorithm.SHA384 => SHA384.Create(), + CertificateThumbprintAlgorithm.SHA512 => SHA512.Create(), + _ => throw new NotSupportedException() + }; + + var serverCertificateHash = serverCertificate != null ? hash.ComputeHash(serverCertificate) : null; + var serverChannelCertificateHash = serverChannelCertificate != null ? hash.ComputeHash(serverChannelCertificate) : null; + var clientChannelCertificateHash = clientChannelCertificate != null ? hash.ComputeHash(clientChannelCertificate) : null; + data = Utils.Append( channelThumbprint, serverNonce, - serverCertificate, - serverChannelCertificate, - clientChannelCertificate, + serverCertificateHash, + serverChannelCertificateHash, + clientChannelCertificateHash, clientNonce); } else @@ -350,7 +391,7 @@ namespace Opc.Ua MinAsymmetricKeyLength = 0, MaxAsymmetricKeyLength = 0, SecureChannelNonceLength = 32, - LegacySequenceNumbers = false, + LegacySequenceNumbers = true, AsymmetricEncryptionAlgorithm = AsymmetricEncryptionAlgorithm.None, AsymmetricSignatureAlgorithm = AsymmetricSignatureAlgorithm.None, CertificateKeyFamily = CertificateKeyFamily.None, @@ -360,7 +401,8 @@ namespace Opc.Ua KeyDerivationAlgorithm = KeyDerivationAlgorithm.None, SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.None, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.None, - SecureChannelEnhancements = false + SecureChannelEnhancements = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -386,7 +428,8 @@ namespace Opc.Ua KeyDerivationAlgorithm = KeyDerivationAlgorithm.PSha1, SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha1, - IsDeprecated = true + IsDeprecated = true, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -412,7 +455,8 @@ namespace Opc.Ua KeyDerivationAlgorithm = KeyDerivationAlgorithm.PSha1, SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha1, - IsDeprecated = true + IsDeprecated = true, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -437,7 +481,8 @@ namespace Opc.Ua KeyDerivationAlgorithm = KeyDerivationAlgorithm.PSha256, SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha256, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -462,7 +507,8 @@ namespace Opc.Ua EphemeralKeyAlgorithm = CertificateKeyAlgorithm.None, SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha256, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -487,7 +533,8 @@ namespace Opc.Ua SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha256, InitializationVectorLength = 128 / 8, SymmetricSignatureLength = 256 / 8, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA1 }; /// @@ -513,7 +560,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -539,7 +587,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -565,7 +614,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -591,7 +641,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -617,7 +668,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -643,7 +695,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -669,7 +722,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha256, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -695,7 +749,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -721,7 +776,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -747,7 +803,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha384, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -773,7 +830,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -799,7 +857,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -825,7 +884,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha256, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -851,7 +911,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -877,7 +938,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -903,7 +965,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Cbc, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.HmacSha384, SecureChannelEnhancements = false, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -929,7 +992,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes256Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes256Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -955,7 +1019,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA384 }; /// @@ -981,7 +1046,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.Aes128Gcm, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.Aes128Gcm, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; /// @@ -1007,7 +1073,8 @@ namespace Opc.Ua SymmetricEncryptionAlgorithm = SymmetricEncryptionAlgorithm.ChaCha20Poly1305, SymmetricSignatureAlgorithm = SymmetricSignatureAlgorithm.ChaCha20Poly1305, SecureChannelEnhancements = true, - IsDeprecated = false + IsDeprecated = false, + CertificateThumbprintAlgorithm = CertificateThumbprintAlgorithm.SHA256 }; } @@ -1272,4 +1339,30 @@ namespace Opc.Ua /// Aes256Gcm } + + /// + /// The algorithm used to generate certificate thumbprints. + /// + public enum CertificateThumbprintAlgorithm + { + /// + /// The SHA1 algorithm. This algorithm is considered insecure. + /// + SHA1, + + /// + /// The SHA256 algorithm. + /// + SHA256, + + /// + /// The SHA384 algorithm. + /// + SHA384, + + /// + /// The SHA512 algorithm. + /// + SHA512 + } } diff --git a/Stack/Opc.Ua.Core/Stack/Tcp/TcpServerChannel.cs b/Stack/Opc.Ua.Core/Stack/Tcp/TcpServerChannel.cs index f306901e0c..0172f581a4 100644 --- a/Stack/Opc.Ua.Core/Stack/Tcp/TcpServerChannel.cs +++ b/Stack/Opc.Ua.Core/Stack/Tcp/TcpServerChannel.cs @@ -697,6 +697,12 @@ namespace Opc.Ua.Bindings token = CreateToken(); token.TokenId = GetNewTokenId(); token.ServerNonce = CreateNonce(ServerCertificate); + + CryptoTrace.Start(ConsoleColor.Red, $"PreviousSecret"); + CryptoTrace.WriteLine($"PreviousSecret={CryptoTrace.KeyToString(token.PreviousSecret)}"); + CryptoTrace.WriteLine($"CurrentSecret={CryptoTrace.KeyToString(CurrentToken?.Secret)}"); + CryptoTrace.Finish($"PreviousSecret"); + token.PreviousSecret = CurrentToken?.Secret; // check the client nonce.