fix(opcua-client): send UserName passwords in the legacy RSA format so 65-char API keys log in to SDK 1.5 servers (#880)
SDK 2.0.1's UserNameIdentityTokenHandler encrypts a password longer than 64 bytes
(a private RsaEncryptedSecretPasswordThreshold, no setting) as an RsaEncryptedSecret
with EncryptionAlgorithm=null. SDK 1.5.378 (.106 and .182) decrypts only the legacy
format under RSA policies; its SecurityPolicies.Decrypt answers a null algorithm with
BadIdentityTokenInvalid ("Unexpected encryption algorithm") before any key check.
Every production API key is 65 chars, so no SDK 2 OtOpcUa client could use one
against QA (b8b4c18f), a rollback target or an older third-party server.
LegacyRsaUserNameIdentityTokenHandler (Driver.OpcUaClient.Session, plugged in through
the public UserIdentity(IUserIdentityTokenHandler) ctor) always uses the legacy
format, RSA-OAEP(len|password|serverNonce) under the server certificate, under an RSA
policy. That is what SDK 2 sends for passwords of 64 bytes or less and what SDK 1.5
clients always send. The legacy format has no size limit (the plaintext is
length-framed over as many RSA blocks as it needs), and an SDK 2 server reads both
formats. Policy None, the ECC policies and a missing certificate go to the SDK
handler unchanged.
OpcUaUserIdentityFactory.UserName is now the one UserName identity the driver, the
AdminUI browse and Client.Shared (CLI/UI) present. Client.Shared references .Session
for it.
Tests: handler unit tests (all three RSA policies, the 1.5-required algorithm URI,
SDK 2 server-side decrypt, the session Copy() keeps the type, None unchanged, and an
SDK control pinning the 64/65-byte switch); a Client.Shared identity test; and an
SDK2<->SDK2 integration test where a 65-char key is admitted in both formats and a
wrong 65-char key reaches the key check (BadIdentityTokenRejected). The #800 Windows
gate's SDK 2 CLI 65-char case now gates against the 1.5 server too.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
+137
@@ -0,0 +1,137 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Security.Certificates;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
|
||||
|
||||
/// <summary>
|
||||
/// UserName token handler that always encrypts the password in the legacy RSA format under an RSA security
|
||||
/// policy, whatever the password's length (lmxopcua#880).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// SDK 2.0.1's <see cref="UserNameIdentityTokenHandler"/> encrypts a password longer than 64 bytes (a private
|
||||
/// <c>RsaEncryptedSecretPasswordThreshold</c> constant with no setting) as an <c>RsaEncryptedSecret</c>, with
|
||||
/// <see cref="UserNameIdentityToken.EncryptionAlgorithm"/> left null. A 64-byte or shorter password is sent in
|
||||
/// the legacy format: <c>RSA-OAEP(len ‖ password ‖ serverNonce)</c> under the server certificate, with the
|
||||
/// algorithm URI set. An SDK 1.5.378 server decrypts only the legacy format under an RSA policy. A null
|
||||
/// algorithm reaches its <c>SecurityPolicies.Decrypt</c> as "Unexpected encryption algorithm", so
|
||||
/// <c>BadIdentityTokenInvalid</c> is returned before any credential check. Every production OtOpcUa API key
|
||||
/// is 65 characters long (<c>otua_</c> + 16 hex + <c>_</c> + 43), so an SDK 2 client could not use one
|
||||
/// against an SDK 1.5 server: QA, any rollback target, or an older third-party stack.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The legacy format needs no size limit, because the SDK frames the plaintext with a length and spreads it
|
||||
/// over as many RSA blocks as it needs. An SDK 2 server accepts both formats. It uses the legacy decryptor
|
||||
/// whenever the algorithm URI is set. This handler therefore sends what SDK 1.5 clients (ScadaBridge
|
||||
/// included) always send, and what SDK 2 itself sends for every password up to 64 bytes. The crypto is the
|
||||
/// same RSA-OAEP under the server certificate, bound to the server nonce. The only thing lost is
|
||||
/// <c>RsaEncryptedSecret</c>'s block padding of the secret's length. Policy <c>None</c> and the ECC policies
|
||||
/// are handed to the SDK handler unchanged, so this type never sends anything in a weaker form than the SDK
|
||||
/// would.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class LegacyRsaUserNameIdentityTokenHandler : IUserIdentityTokenHandler
|
||||
{
|
||||
private readonly UserNameIdentityTokenHandler _inner;
|
||||
private readonly ISecurityPolicyRegistry _policies;
|
||||
|
||||
/// <summary>Create the handler for a user name and its plaintext password.</summary>
|
||||
/// <param name="username">The user name.</param>
|
||||
/// <param name="password">The password bytes (UTF-8 for an API key).</param>
|
||||
/// <param name="securityPolicies">The policy registry, or null for <see cref="SecurityPolicies.Default"/>.</param>
|
||||
public LegacyRsaUserNameIdentityTokenHandler(string username, ReadOnlySpan<byte> password,
|
||||
ISecurityPolicyRegistry? securityPolicies = null)
|
||||
: this(new UserNameIdentityTokenHandler(username, password, securityPolicies),
|
||||
securityPolicies ?? SecurityPolicies.Default)
|
||||
{
|
||||
}
|
||||
|
||||
private LegacyRsaUserNameIdentityTokenHandler(UserNameIdentityTokenHandler inner, ISecurityPolicyRegistry policies)
|
||||
{
|
||||
_inner = inner;
|
||||
_policies = policies;
|
||||
}
|
||||
|
||||
/// <summary>The user name in the token.</summary>
|
||||
public string UserName => _inner.UserName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public UserIdentityToken Token => _inner.Token;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string DisplayName => _inner.DisplayName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public UserTokenType TokenType => _inner.TokenType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void UpdatePolicy(UserTokenPolicy userTokenPolicy) => _inner.UpdatePolicy(userTokenPolicy);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask EncryptAsync(Certificate receiverCertificate, byte[] receiverNonce, string securityPolicyUri,
|
||||
IServiceMessageContext context, Nonce? receiverEphemeralKey = null, Certificate? senderCertificate = null,
|
||||
CertificateCollection? senderIssuerCertificates = null, bool doNotEncodeSenderCertificate = false,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var password = _inner.DecryptedPassword;
|
||||
var policy = password is null || string.IsNullOrEmpty(securityPolicyUri)
|
||||
? null
|
||||
: _policies.GetInfo(securityPolicyUri);
|
||||
|
||||
// Only an RSA policy (no ephemeral key) with a receiver certificate is ours. None, ECC, an unknown policy
|
||||
// and a missing certificate get the SDK's own handling, and its own errors.
|
||||
if (policy is null || policy.Uri == SecurityPolicies.None
|
||||
|| policy.EphemeralKeyAlgorithm != CertificateKeyAlgorithm.None || receiverCertificate is null)
|
||||
{
|
||||
return _inner.EncryptAsync(receiverCertificate!, receiverNonce, securityPolicyUri, context,
|
||||
receiverEphemeralKey, senderCertificate, senderIssuerCertificates, doNotEncodeSenderCertificate, ct);
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var token = (UserNameIdentityToken)_inner.Token;
|
||||
var plaintext = Utils.Append(password, receiverNonce);
|
||||
try
|
||||
{
|
||||
var encrypted = _policies.Encrypt(receiverCertificate, policy.Uri, plaintext);
|
||||
token.Password = encrypted.Data.ToByteString();
|
||||
token.EncryptionAlgorithm = encrypted.Algorithm;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Array.Clear(plaintext);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DecryptAsync(Certificate certificate, Nonce receiverNonce, string securityPolicyUri,
|
||||
IServiceMessageContext context, Nonce? ephemeralKey = null, Certificate? senderCertificate = null,
|
||||
CertificateCollection? senderIssuerCertificates = null, ICertificateValidatorEx? validator = null,
|
||||
CancellationToken ct = default) =>
|
||||
_inner.DecryptAsync(certificate, receiverNonce, securityPolicyUri, context, ephemeralKey, senderCertificate,
|
||||
senderIssuerCertificates, validator, ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<SignatureData> SignAsync(byte[] dataToSign, string securityPolicyUri, CancellationToken ct = default) =>
|
||||
_inner.SignAsync(dataToSign, securityPolicyUri, ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<bool> VerifyAsync(byte[] dataToVerify, SignatureData signatureData, string securityPolicyUri,
|
||||
CancellationToken ct = default) =>
|
||||
_inner.VerifyAsync(dataToVerify, signatureData, securityPolicyUri, ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>The SDK session encrypts a <c>Copy()</c> of the handler, so the clone must keep this type.</remarks>
|
||||
public object Clone() => new LegacyRsaUserNameIdentityTokenHandler((UserNameIdentityTokenHandler)_inner.Clone(), _policies);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(IUserIdentityTokenHandler? other) =>
|
||||
other is LegacyRsaUserNameIdentityTokenHandler legacy ? _inner.Equals(legacy._inner) : _inner.Equals(other);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool Equals(object? obj) => obj is IUserIdentityTokenHandler other && Equals(other);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(UserName ?? string.Empty);
|
||||
}
|
||||
+23
-3
@@ -24,13 +24,33 @@ public static class OpcUaUserIdentityFactory
|
||||
options.AuthType switch
|
||||
{
|
||||
OpcUaAuthType.Anonymous => new UserIdentity(new AnonymousIdentityToken()),
|
||||
OpcUaAuthType.Username => new UserIdentity(
|
||||
options.Username ?? string.Empty,
|
||||
System.Text.Encoding.UTF8.GetBytes(options.Password ?? string.Empty)),
|
||||
OpcUaAuthType.Username => UserName(options.Username ?? string.Empty, options.Password ?? string.Empty),
|
||||
OpcUaAuthType.Certificate => FromCertificate(options),
|
||||
_ => new UserIdentity(new AnonymousIdentityToken()),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The UserName identity every OtOpcUa OPC UA client presents: the driver, the AdminUI browse and the Client
|
||||
/// CLI/UI (through <c>Client.Shared</c>). Under an RSA policy the password always travels in the legacy
|
||||
/// encrypted format, so a 65-character API key also logs in to an SDK 1.5 server (lmxopcua#880). See
|
||||
/// <see cref="LegacyRsaUserNameIdentityTokenHandler"/>.
|
||||
/// </summary>
|
||||
/// <param name="username">The user name (<c>apikey</c> for an OtOpcUa API key).</param>
|
||||
/// <param name="password">The plaintext password; sent UTF-8 encoded.</param>
|
||||
/// <returns>The <see cref="UserIdentity"/> for session activation.</returns>
|
||||
public static UserIdentity UserName(string username, string password)
|
||||
{
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(password);
|
||||
try
|
||||
{
|
||||
return new UserIdentity(new LegacyRsaUserNameIdentityTokenHandler(username, bytes));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Array.Clear(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build a <see cref="UserIdentity"/> carrying a client user-authentication certificate loaded from
|
||||
/// <see cref="OpcUaClientDriverOptions.UserCertificatePath"/>. Fails fast if the path is missing, the file
|
||||
|
||||
Reference in New Issue
Block a user