node-opcua-client 2.189.0 → 2.190.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/alarms_and_conditions/client_alarm_tools.d.ts.map +1 -1
  2. package/dist/alarms_and_conditions/client_alarm_tools.js +2 -1
  3. package/dist/alarms_and_conditions/client_alarm_tools.js.map +1 -1
  4. package/dist/client_monitored_item_toolbox.d.ts.map +1 -1
  5. package/dist/client_monitored_item_toolbox.js +8 -4
  6. package/dist/client_monitored_item_toolbox.js.map +1 -1
  7. package/dist/client_session_keepalive_manager.d.ts.map +1 -1
  8. package/dist/client_session_keepalive_manager.js +18 -12
  9. package/dist/client_session_keepalive_manager.js.map +1 -1
  10. package/dist/private/client_base_impl.d.ts +10 -1
  11. package/dist/private/client_base_impl.d.ts.map +1 -1
  12. package/dist/private/client_base_impl.js +188 -77
  13. package/dist/private/client_base_impl.js.map +1 -1
  14. package/dist/private/client_monitored_item_impl.d.ts.map +1 -1
  15. package/dist/private/client_monitored_item_impl.js +2 -1
  16. package/dist/private/client_monitored_item_impl.js.map +1 -1
  17. package/dist/private/client_publish_engine.d.ts.map +1 -1
  18. package/dist/private/client_publish_engine.js +16 -8
  19. package/dist/private/client_publish_engine.js.map +1 -1
  20. package/dist/private/client_session_impl.d.ts +21 -0
  21. package/dist/private/client_session_impl.d.ts.map +1 -1
  22. package/dist/private/client_session_impl.js +122 -57
  23. package/dist/private/client_session_impl.js.map +1 -1
  24. package/dist/private/client_subscription_impl.d.ts.map +1 -1
  25. package/dist/private/client_subscription_impl.js +27 -17
  26. package/dist/private/client_subscription_impl.js.map +1 -1
  27. package/dist/private/opcua_client_impl.d.ts.map +1 -1
  28. package/dist/private/opcua_client_impl.js +307 -29
  29. package/dist/private/opcua_client_impl.js.map +1 -1
  30. package/dist/private/reconnection/client_publish_engine_reconnection.d.ts.map +1 -1
  31. package/dist/private/reconnection/client_publish_engine_reconnection.js +6 -3
  32. package/dist/private/reconnection/client_publish_engine_reconnection.js.map +1 -1
  33. package/dist/private/reconnection/client_subscription_reconnection.d.ts.map +1 -1
  34. package/dist/private/reconnection/client_subscription_reconnection.js +6 -3
  35. package/dist/private/reconnection/client_subscription_reconnection.js.map +1 -1
  36. package/dist/private/reconnection/reconnection.d.ts.map +1 -1
  37. package/dist/private/reconnection/reconnection.js +6 -4
  38. package/dist/private/reconnection/reconnection.js.map +1 -1
  39. package/dist/private/verify_server_signature.d.ts +51 -0
  40. package/dist/private/verify_server_signature.d.ts.map +1 -0
  41. package/dist/private/verify_server_signature.js +76 -0
  42. package/dist/private/verify_server_signature.js.map +1 -0
  43. package/dist/reverse/client_reverse_connect.js +2 -2
  44. package/dist/reverse/client_reverse_connect.js.map +1 -1
  45. package/dist/tools/read_history_server_capabilities.js +6 -3
  46. package/dist/tools/read_history_server_capabilities.js.map +1 -1
  47. package/dist/verify.d.ts +6 -0
  48. package/dist/verify.d.ts.map +1 -1
  49. package/dist/verify.js +32 -10
  50. package/dist/verify.js.map +1 -1
  51. package/package.json +45 -45
  52. package/source/alarms_and_conditions/client_alarm_tools.ts +2 -1
  53. package/source/client_monitored_item_toolbox.ts +8 -4
  54. package/source/client_session_keepalive_manager.ts +18 -12
  55. package/source/private/client_base_impl.ts +206 -78
  56. package/source/private/client_monitored_item_impl.ts +2 -1
  57. package/source/private/client_publish_engine.ts +16 -8
  58. package/source/private/client_session_impl.ts +122 -57
  59. package/source/private/client_subscription_impl.ts +27 -17
  60. package/source/private/opcua_client_impl.ts +383 -29
  61. package/source/private/reconnection/client_publish_engine_reconnection.ts +6 -3
  62. package/source/private/reconnection/client_subscription_reconnection.ts +6 -3
  63. package/source/private/reconnection/reconnection.ts +6 -4
  64. package/source/private/verify_server_signature.ts +109 -0
  65. package/source/reverse/client_reverse_connect.ts +2 -2
  66. package/source/tools/read_history_server_capabilities.ts +6 -3
  67. package/source/verify.ts +34 -12
@@ -6,12 +6,13 @@ import { callbackify } from "node:util";
6
6
  import chalk from "chalk";
7
7
  import { assert } from "node-opcua-assert";
8
8
  import { DataTypeExtractStrategy } from "node-opcua-client-dynamic-extension-object";
9
- import { combine_der, exploreCertificate, extractPublicKeyFromCertificateSync, makePrivateKeyFromPem, split_der, toPem } from "node-opcua-crypto/web";
9
+ import { getEcKeyOperationsFromProvider } from "node-opcua-common";
10
+ import { combine_der, exploreCertificate, extractPublicKeyFromCertificateSync, isEcKeyOperations, makePrivateKeyFromPem, split_der, toPem } from "node-opcua-crypto/web";
10
11
  import { LocalizedText } from "node-opcua-data-model";
11
12
  import { checkDebugFlag, make_debugLog, make_errorLog, make_warningLog } from "node-opcua-debug";
12
13
  import { extractFullyQualifiedDomainName } from "node-opcua-hostname";
13
14
  import { readNamespaceArray } from "node-opcua-pseudo-session";
14
- import { computeSignatureAsync, fromURI, getCryptoFactory, SecurityPolicy, toCryptoKeyObject } from "node-opcua-secure-channel";
15
+ import { computeSignatureAsync, eccSecurityPolicies, fromURI, getCryptoFactory, hasAsymmetricEncryption, makeClientSignatureData, makeEccEncryptedSecret, makeEcdhPolicyUriHeader, makeUserTokenSignatureData, readEcdhKey, SecurityPolicy, signChannelBoundData, toCryptoKeyObject, usesChannelBoundSignatures, usesEccEncryptedSecret, verifySignedEphemeralKey } from "node-opcua-secure-channel";
15
16
  import { EndpointDescription, UserTokenType } from "node-opcua-service-endpoints";
16
17
  import { MessageSecurityMode } from "node-opcua-service-secure-channel";
17
18
  import { ActivateSessionRequest, ActivateSessionResponse, AnonymousIdentityToken, CreateSessionRequest, CreateSessionResponse, UserNameIdentityToken, X509IdentityToken } from "node-opcua-service-session";
@@ -21,6 +22,7 @@ import { OPCUAClient } from "../opcua_client.js";
21
22
  import { ClientBaseImpl } from "./client_base_impl.js";
22
23
  import { ClientSessionImpl } from "./client_session_impl.js";
23
24
  import { repair_client_sessions } from "./reconnection/reconnection.js";
25
+ import { checkCreateSessionServerSignature } from "./verify_server_signature.js";
24
26
  const doDebug = checkDebugFlag("opcua_client_impl");
25
27
  const debugLog = make_debugLog("opcua_client_impl");
26
28
  const errorLog = make_errorLog("opcua_client_impl");
@@ -151,6 +153,34 @@ function createAnonymousIdentityToken(context) {
151
153
  }
152
154
  return new AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
153
155
  }
156
+ /**
157
+ * The user certificate token policy of the endpoint for `certificate`. A server with more than
158
+ * one family of key has one such policy for each: the one whose security policy signs with the
159
+ * key of the certificate is taken, an RSA key or a key on an elliptic curve. The first one is
160
+ * taken when none fits, as before.
161
+ */
162
+ function findUserCertificateTokenPolicy(endpoint, certificate, channelSecurityPolicy) {
163
+ const candidates = (endpoint.userIdentityTokens || []).filter((token) => token.tokenType === UserTokenType.Certificate);
164
+ if (candidates.length > 1) {
165
+ let keyIsOnCurve;
166
+ try {
167
+ keyIsOnCurve = exploreCertificate(certificate).tbsCertificate.subjectPublicKeyInfo.keyType === "ec";
168
+ }
169
+ catch {
170
+ return findUserTokenPolicy(endpoint, UserTokenType.Certificate);
171
+ }
172
+ for (const candidate of candidates) {
173
+ let securityPolicy = fromURI(candidate.securityPolicyUri);
174
+ if (securityPolicy === SecurityPolicy.Invalid) {
175
+ securityPolicy = channelSecurityPolicy;
176
+ }
177
+ if (eccSecurityPolicies.includes(securityPolicy) === keyIsOnCurve) {
178
+ return candidate;
179
+ }
180
+ }
181
+ }
182
+ return findUserTokenPolicy(endpoint, UserTokenType.Certificate);
183
+ }
154
184
  /**
155
185
  *
156
186
  * @param context
@@ -161,11 +191,12 @@ function createAnonymousIdentityToken(context) {
161
191
  async function createX509IdentityToken(context, certificate, userKey) {
162
192
  const endpoint = context.endpoint;
163
193
  assert(endpoint instanceof EndpointDescription);
164
- const userTokenPolicy = findUserTokenPolicy(endpoint, UserTokenType.Certificate);
165
- /* c8 ignore next */
194
+ const userTokenPolicy = findUserCertificateTokenPolicy(endpoint, certificate, context.securityPolicy);
195
+ /* c8 ignore start */
166
196
  if (!userTokenPolicy) {
167
197
  throw makeMissingUserTokenPolicyError(endpoint, "Certificate (X509)", UserTokenType.Certificate);
168
198
  }
199
+ /* c8 ignore stop */
169
200
  let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
170
201
  // if the security policy is not specified we use the session security policy
171
202
  if (securityPolicy === SecurityPolicy.Invalid) {
@@ -181,10 +212,11 @@ async function createX509IdentityToken(context, certificate, userKey) {
181
212
  assert(serverNonce instanceof Buffer);
182
213
  // see Release 1.02 155 OPC Unified Architecture, Part 4
183
214
  const cryptoFactory = getCryptoFactory(securityPolicy);
184
- /* c8 ignore next */
215
+ /* c8 ignore start */
185
216
  if (!cryptoFactory) {
186
217
  throw new Error(" Unsupported security Policy");
187
218
  }
219
+ /* c8 ignore stop */
188
220
  /**
189
221
  * OPCUA Spec 1.04 - part 4
190
222
  * page 28:
@@ -212,6 +244,22 @@ async function createX509IdentityToken(context, certificate, userKey) {
212
244
  * ActivateSession if required by the SecurityPolicy. The Server should specify a SecurityPolicy for
213
245
  * the UserTokenPolicy if the SecureChannel has a SecurityPolicy of None.
214
246
  */
247
+ // OPC 10000-4, 6.1.8: the signature is bound to the SecureChannel when the channel and the
248
+ // policy of the user token policy both have the SecureChannelEnhancements
249
+ const channelBound = usesChannelBoundSignatures(cryptoFactory) ? (context.channelBound?.() ?? null) : null;
250
+ if (channelBound) {
251
+ const dataToSign = makeUserTokenSignatureData(cryptoFactory, {
252
+ channelThumbprint: channelBound.channelThumbprint,
253
+ serverNonce,
254
+ serverCertificate,
255
+ serverChannelCertificate: channelBound.serverChannelCertificate,
256
+ clientCertificate: channelBound.clientCertificate,
257
+ clientChannelCertificate: channelBound.clientChannelCertificate,
258
+ clientNonce: channelBound.clientNonce
259
+ });
260
+ const userTokenSignature = (await signChannelBoundData(cryptoFactory, dataToSign, userKey));
261
+ return { userIdentityToken, userTokenSignature };
262
+ }
215
263
  // now create the proof of possession, by creating a signature
216
264
  // The data to sign is created by appending the last serverNonce to the serverCertificate
217
265
  // The signature generated with the key associated with the User Certificate —
@@ -235,10 +283,11 @@ function createUserNameIdentityToken(session, userName, password) {
235
283
  *
236
284
  */
237
285
  const userTokenPolicy = findUserTokenPolicy(endpoint, UserTokenType.UserName);
238
- /* c8 ignore next */
286
+ /* c8 ignore start */
239
287
  if (!userTokenPolicy) {
240
288
  throw makeMissingUserTokenPolicyError(endpoint, "USERNAME", UserTokenType.UserName);
241
289
  }
290
+ /* c8 ignore stop */
242
291
  let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
243
292
  // if the security policy is not specified we use the session security policy
244
293
  if (securityPolicy === SecurityPolicy.Invalid) {
@@ -278,10 +327,16 @@ function createUserNameIdentityToken(session, userName, password) {
278
327
  }
279
328
  // see Release 1.02 155 OPC Unified Architecture, Part 4
280
329
  const cryptoFactory = getCryptoFactory(securityPolicy);
281
- /* c8 ignore next */
330
+ /* c8 ignore start */
282
331
  if (!cryptoFactory) {
283
332
  throw new Error(` Unsupported security Policy ${securityPolicy.toString()}`);
284
333
  }
334
+ /* c8 ignore stop */
335
+ /* c8 ignore start */
336
+ if (!hasAsymmetricEncryption(cryptoFactory)) {
337
+ throw new Error(`the security policy ${securityPolicy.toString()} has no asymmetric encryption for a password`);
338
+ }
339
+ /* c8 ignore stop */
285
340
  identityToken = new UserNameIdentityToken({
286
341
  encryptionAlgorithm: cryptoFactory.asymmetricEncryptionAlgorithm,
287
342
  password: Buffer.from(password, "utf-8"),
@@ -295,6 +350,58 @@ function createUserNameIdentityToken(session, userName, password) {
295
350
  identityToken.password = cryptoFactory.asymmetricEncrypt(block, toCryptoKeyObject(publicKey));
296
351
  return identityToken;
297
352
  }
353
+ /**
354
+ * The SecurityPolicy of the user name token of the endpoint, when the password for it is an
355
+ * EccEncryptedSecret: a policy for a key on an elliptic curve. null for another policy.
356
+ */
357
+ function keyAgreementPolicyOfUserNameToken(context) {
358
+ const userTokenPolicy = findUserTokenPolicy(context.endpoint, UserTokenType.UserName);
359
+ if (!userTokenPolicy) {
360
+ return null;
361
+ }
362
+ let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
363
+ if (securityPolicy === SecurityPolicy.Invalid) {
364
+ securityPolicy = context.securityPolicy;
365
+ }
366
+ return usesEccEncryptedSecret(securityPolicy) ? securityPolicy : null;
367
+ }
368
+ /**
369
+ * The user name token for a SecurityPolicy for a key on an elliptic curve: the password is an
370
+ * EccEncryptedSecret (OPC 10000-4, 7.40.2.5), made for the ephemeral key of the server and
371
+ * signed with the key of the application certificate of the client. The password never goes
372
+ * with less protection: with no ephemeral key, or no key on a curve, there is no token.
373
+ */
374
+ async function createUserNameIdentityTokenWithKeyAgreement(context, securityPolicy, userName, password) {
375
+ const userTokenPolicy = findUserTokenPolicy(context.endpoint, UserTokenType.UserName);
376
+ /* c8 ignore start */
377
+ if (!userTokenPolicy) {
378
+ throw makeMissingUserTokenPolicyError(context.endpoint, "USERNAME", UserTokenType.UserName);
379
+ }
380
+ /* c8 ignore stop */
381
+ const serverKey = context.serverEphemeralKey;
382
+ if (!serverKey || serverKey.securityPolicy !== securityPolicy) {
383
+ throw new Error(`the server gave no ephemeral key for the security policy ${securityPolicy}: the password cannot be protected, and it is not sent`);
384
+ }
385
+ const signingKey = context.applicationKeyOnCurve?.() ?? null;
386
+ if (!signingKey) {
387
+ throw new Error(`the security policy ${securityPolicy} needs a private key on an elliptic curve to protect the password, and the key of the client is not on a curve`);
388
+ }
389
+ const encryptedPassword = await makeEccEncryptedSecret({
390
+ securityPolicy,
391
+ secret: Buffer.from(password, "utf-8"),
392
+ nonce: context.serverNonce || Buffer.alloc(0),
393
+ receiverPublicKey: serverKey.publicKey,
394
+ signingKey
395
+ });
396
+ context.ephemeralKeyIsUsed?.();
397
+ return new UserNameIdentityToken({
398
+ // no algorithm name: this policy has no asymmetric encryption
399
+ encryptionAlgorithm: null,
400
+ password: encryptedPassword,
401
+ policyId: userTokenPolicy.policyId,
402
+ userName
403
+ });
404
+ }
298
405
  function _adjustRevisedSessionTimeout(revisedSessionTimeout, requestedTimeout) {
299
406
  // Some old OPCUA Servers are known to report an invalid revisedSessionTimeout
300
407
  // such as Siemens SimoCode Pro V.
@@ -373,10 +480,11 @@ export class OPCUAClientImpl extends ClientBaseImpl {
373
480
  callback(err);
374
481
  }
375
482
  else {
376
- /* c8 ignore next */
483
+ /* c8 ignore start */
377
484
  if (!session) {
378
485
  return callback(new Error("Internal Error"));
379
486
  }
487
+ /* c8 ignore stop */
380
488
  this._addSession(session);
381
489
  this._activateSession(session, userIdentityInfo, (err1, session2) => {
382
490
  if (err1) {
@@ -568,7 +676,7 @@ export class OPCUAClientImpl extends ClientBaseImpl {
568
676
  if (!this._secureChannel) {
569
677
  return callback?.(new Error(" client must be connected first"));
570
678
  }
571
- // c8 ignore next
679
+ /* c8 ignore start */
572
680
  if (!this.__resolveEndPoint() || !this.endpoint) {
573
681
  return callback?.(new Error(" End point must exist " +
574
682
  this._secureChannel?.endpointUrl +
@@ -577,9 +685,10 @@ export class OPCUAClientImpl extends ClientBaseImpl {
577
685
  " securityPolicy = " +
578
686
  this.securityPolicy));
579
687
  }
688
+ /* c8 ignore stop */
580
689
  assert(!internalSession._client || matchUri(internalSession._client.endpointUrl, this.endpointUrl), "cannot reactivateSession on a different endpoint");
581
690
  const old_client = internalSession._client;
582
- // c8 ignore next
691
+ /* c8 ignore next */
583
692
  doDebug && debugLog("OPCUAClientImpl#reactivateSession");
584
693
  this._activateSession(internalSession, internalSession.userIdentityInfo, (err /*, newSession?: ClientSessionImpl*/) => {
585
694
  if (!err) {
@@ -597,10 +706,11 @@ export class OPCUAClientImpl extends ClientBaseImpl {
597
706
  callback?.();
598
707
  }
599
708
  else {
600
- // c8 ignore next
709
+ /* c8 ignore start */
601
710
  if (doDebug) {
602
711
  debugLog(chalk.red.bgWhite("reactivateSession has failed !"), err.message);
603
712
  }
713
+ /* c8 ignore stop */
604
714
  callback?.(err);
605
715
  }
606
716
  });
@@ -624,11 +734,12 @@ export class OPCUAClientImpl extends ClientBaseImpl {
624
734
  assert(this.serverUri !== undefined, ` must have a valid server URI ${this.serverUri}`);
625
735
  assert(this.endpointUrl !== undefined, " must have a valid server endpointUrl");
626
736
  assert(this.endpoint);
627
- // c8 ignore next
737
+ /* c8 ignore start */
628
738
  if (!this._secureChannel) {
629
739
  callback(new Error("Invalid channel"));
630
740
  return;
631
741
  }
742
+ /* c8 ignore stop */
632
743
  const applicationUri = this._getApplicationUri();
633
744
  const applicationDescription = {
634
745
  applicationName: new LocalizedText({ text: this.applicationName, locale: null }),
@@ -645,7 +756,8 @@ export class OPCUAClientImpl extends ClientBaseImpl {
645
756
  // recycle session name if already exists
646
757
  const sessionName = session.name;
647
758
  const request = new CreateSessionRequest({
648
- clientCertificate: this.getCertificate(),
759
+ // the certificate of the SecureChannel: a client can have one for each family of key
760
+ clientCertificate: this._secureChannel?.getCertificate() ?? this.getCertificate(),
649
761
  clientDescription: applicationDescription,
650
762
  clientNonce: this.clientNonce,
651
763
  endpointUrl: this.endpointUrl,
@@ -656,10 +768,15 @@ export class OPCUAClientImpl extends ClientBaseImpl {
656
768
  });
657
769
  // a client Nonce must be provided if security mode is set
658
770
  assert(this._secureChannel.securityMode === MessageSecurityMode.None || request.clientNonce !== null);
771
+ // OPC 10000-6, 6.8.2: with a policy for a key on an elliptic curve, the client asks the server
772
+ // for an ephemeral key, to protect the secret of its user identity token
773
+ if (usesEccEncryptedSecret(this._secureChannel.securityPolicy)) {
774
+ request.requestHeader.additionalHeader = makeEcdhPolicyUriHeader(this._secureChannel.securityPolicy);
775
+ }
659
776
  this.performMessageTransaction(request, (err, response) => {
660
- /* c8 ignore next */
777
+ /* c8 ignore start */
661
778
  if (err) {
662
- // c8 ignore next
779
+ /* c8 ignore next */
663
780
  doDebug && debugLog("__createSession_step3 has failed", err.message);
664
781
  return callback(err);
665
782
  // // we could have an invalid state here or a connection error
@@ -670,10 +787,12 @@ export class OPCUAClientImpl extends ClientBaseImpl {
670
787
  // }, 5 * 1000);
671
788
  // return;
672
789
  }
673
- /* c8 ignore next */
790
+ /* c8 ignore stop */
791
+ /* c8 ignore start */
674
792
  if (!response || !(response instanceof CreateSessionResponse)) {
675
793
  return callback(new Error("internal error"));
676
794
  }
795
+ /* c8 ignore stop */
677
796
  if (response.responseHeader.serviceResult === StatusCodes.BadTooManySessions) {
678
797
  return callback(new Error(response.responseHeader.serviceResult.toString()));
679
798
  }
@@ -681,11 +800,39 @@ export class OPCUAClientImpl extends ClientBaseImpl {
681
800
  err = new Error(`Error ${response.responseHeader.serviceResult.name} ${response.responseHeader.serviceResult.description}`);
682
801
  return callback(err);
683
802
  }
684
- // c8 ignore next
803
+ /* c8 ignore start */
685
804
  if (!validateServerNonce(response.serverNonce)) {
686
805
  return callback(new Error("Invalid server Nonce"));
687
806
  }
688
- // todo: verify SignedSoftwareCertificates and response.serverSignature
807
+ /* c8 ignore stop */
808
+ // OPC 10000-4 §5.7.2.2 and §6.1.8: check the server certificate and the server signature
809
+ // before the session is used and before the client signature is computed.
810
+ if (!this._secureChannel) {
811
+ return callback(new Error("Invalid channel"));
812
+ }
813
+ const signatureStatus = checkCreateSessionServerSignature({
814
+ securityMode: this._secureChannel.securityMode,
815
+ securityPolicy: this._secureChannel.securityPolicy,
816
+ channelServerCertificate: this.serverCertificate,
817
+ clientCertificate: request.clientCertificate,
818
+ clientNonce: request.clientNonce,
819
+ serverCertificate: response.serverCertificate,
820
+ serverSignature: response.serverSignature,
821
+ channelThumbprint: this._secureChannel.channelThumbprint,
822
+ clientChannelCertificate: request.clientCertificate,
823
+ serverNonce: response.serverNonce
824
+ });
825
+ if (signatureStatus.isNotGood()) {
826
+ const reason = signatureStatus === StatusCodes.BadCertificateInvalid
827
+ ? "the server certificate in the CreateSession response is not the certificate of the secure channel"
828
+ : "the server signature in the CreateSession response is missing or invalid";
829
+ warningLog(`CreateSession: ${reason} (${signatureStatus.toString()})`);
830
+ return callback(new Error(`${signatureStatus.toString()}: ${reason}`));
831
+ }
832
+ if (request.clientNonce) {
833
+ session._clientNonce = request.clientNonce;
834
+ }
835
+ session._clientCertificate = request.clientCertificate;
689
836
  session.name = request.sessionName || "";
690
837
  session.sessionId = response.sessionId;
691
838
  session.authenticationToken = response.authenticationToken;
@@ -693,7 +840,12 @@ export class OPCUAClientImpl extends ClientBaseImpl {
693
840
  session.serverNonce = response.serverNonce;
694
841
  session.serverCertificate = response.serverCertificate;
695
842
  session.serverSignature = response.serverSignature;
696
- // c8 ignore next
843
+ session._serverEphemeralKey = null;
844
+ const ephemeralKeyError = this.#takeServerEphemeralKey(session, response.responseHeader.additionalHeader);
845
+ if (ephemeralKeyError) {
846
+ return callback(ephemeralKeyError);
847
+ }
848
+ /* c8 ignore next */
697
849
  doDebug && debugLog("revised session timeout = ", session.timeout, response.revisedSessionTimeout);
698
850
  response.serverEndpoints = response.serverEndpoints || [];
699
851
  if (!verifyEndpointDescriptionMatches(this, response.serverEndpoints)) {
@@ -724,11 +876,12 @@ export class OPCUAClientImpl extends ClientBaseImpl {
724
876
  _activateSession(session, userIdentityInfo, callback) {
725
877
  // see OPCUA Part 4 - $7.35
726
878
  assert(typeof callback === "function");
727
- // c8 ignore next
879
+ /* c8 ignore start */
728
880
  if (!this._secureChannel) {
729
881
  callback(new Error(" No secure channel"));
730
882
  return;
731
883
  }
884
+ /* c8 ignore stop */
732
885
  // `session.serverCertificate` is captured once, at CreateSession. If the
733
886
  // server has rotated its certificate since (push certificate management,
734
887
  // OPC UA Part 12), the client has already re-learned the current one in
@@ -756,8 +909,15 @@ export class OPCUAClientImpl extends ClientBaseImpl {
756
909
  endpoint: this.endpoint,
757
910
  securityPolicy: this._secureChannel.securityPolicy,
758
911
  serverCertificate,
759
- serverNonce: serverNonce // please check this !
912
+ serverNonce: serverNonce, // please check this !
913
+ serverEphemeralKey: session._serverEphemeralKey,
914
+ applicationKeyOnCurve: () => this.#keyOnCurveForPolicy(this._secureChannel.securityPolicy),
915
+ ephemeralKeyIsUsed: () => {
916
+ ephemeralKeyIsUsed = true;
917
+ },
918
+ channelBound: () => this.#channelBoundContext(this._secureChannel, session)
760
919
  };
920
+ let ephemeralKeyIsUsed = false;
761
921
  this.createUserIdentityToken(context, userIdentityInfo, async (err, data) => {
762
922
  if (err) {
763
923
  session._client = _old_client;
@@ -769,7 +929,7 @@ export class OPCUAClientImpl extends ClientBaseImpl {
769
929
  let clientSignature;
770
930
  try {
771
931
  clientSignature =
772
- (await this.computeClientSignature(this._secureChannel, serverCertificate, serverNonce)) || undefined;
932
+ (await this.computeClientSignature(this._secureChannel, serverCertificate, serverNonce, session)) || undefined;
773
933
  }
774
934
  catch (signatureError) {
775
935
  session._client = _old_client;
@@ -823,6 +983,13 @@ export class OPCUAClientImpl extends ClientBaseImpl {
823
983
  userTokenSignature
824
984
  });
825
985
  request.requestHeader.authenticationToken = session.authenticationToken;
986
+ // OPC 10000-6, 6.8.2: the client names the policy in each ActivateSession too, so that
987
+ // the server gives the ephemeral key for the next one. A server can give a new key
988
+ // only when it is asked.
989
+ const channelPolicy = this._secureChannel.securityPolicy;
990
+ if (usesEccEncryptedSecret(channelPolicy)) {
991
+ request.requestHeader.additionalHeader = makeEcdhPolicyUriHeader(channelPolicy);
992
+ }
826
993
  session.lastRequestSentTime = new Date();
827
994
  this.performMessageTransaction(request, (err1, response) => {
828
995
  // this path bypasses ClientSessionImpl._performMessageTransaction, so it has to
@@ -830,10 +997,11 @@ export class OPCUAClientImpl extends ClientBaseImpl {
830
997
  // server that answers and rejects the activation is still a server we reached.
831
998
  session.noteServerAnswer(err1, response);
832
999
  if (!err1 && response && response.responseHeader.serviceResult.isGoodish()) {
833
- /* c8 ignore next */
1000
+ /* c8 ignore start */
834
1001
  if (!(response instanceof ActivateSessionResponse)) {
835
1002
  return callback(new Error("Internal Error"));
836
1003
  }
1004
+ /* c8 ignore stop */
837
1005
  if (!validateServerNonce(response.serverNonce)) {
838
1006
  return callback(new Error("Invalid server Nonce"));
839
1007
  }
@@ -842,6 +1010,14 @@ export class OPCUAClientImpl extends ClientBaseImpl {
842
1010
  // OPC 10000-18 §5.2.8) so a Client can react without server access.
843
1011
  session.lastActivateSessionStatusCode = response.responseHeader.serviceResult;
844
1012
  session.serverNonce = response.serverNonce;
1013
+ // the server takes an ephemeral key one time, and gives the next one in this response
1014
+ if (ephemeralKeyIsUsed) {
1015
+ session._serverEphemeralKey = null;
1016
+ }
1017
+ const ephemeralKeyError = this.#takeServerEphemeralKey(session, response.responseHeader.additionalHeader);
1018
+ if (ephemeralKeyError) {
1019
+ return callback(ephemeralKeyError);
1020
+ }
845
1021
  if (this.keepSessionAlive) {
846
1022
  session.startKeepAliveManager(this.keepAliveInterval);
847
1023
  }
@@ -851,10 +1027,11 @@ export class OPCUAClientImpl extends ClientBaseImpl {
851
1027
  else {
852
1028
  // restore client
853
1029
  session._client = _old_client;
854
- /* c8 ignore next */
1030
+ /* c8 ignore start */
855
1031
  if (!err1 && response) {
856
1032
  err1 = new Error(response.responseHeader.serviceResult.toString());
857
1033
  }
1034
+ /* c8 ignore stop */
858
1035
  session._client = _old_client;
859
1036
  return callback(err1);
860
1037
  }
@@ -956,7 +1133,7 @@ export class OPCUAClientImpl extends ClientBaseImpl {
956
1133
  assert(typeof callback === "function");
957
1134
  assert(this._secureChannel);
958
1135
  if (!this.__resolveEndPoint() || !this.endpoint) {
959
- /* c8 ignore next */
1136
+ /* c8 ignore start */
960
1137
  if (this._serverEndpoints) {
961
1138
  warningLog("server endpoints =", this._serverEndpoints
962
1139
  .map((endpoint) => endpoint.endpointUrl +
@@ -968,6 +1145,7 @@ export class OPCUAClientImpl extends ClientBaseImpl {
968
1145
  endpoint.userIdentityTokens?.map((u) => UserTokenType[u.tokenType]).join(","))
969
1146
  .join("\n"));
970
1147
  }
1148
+ /* c8 ignore stop */
971
1149
  return callback(new Error(" End point must exist " +
972
1150
  this._secureChannel?.endpointUrl +
973
1151
  " securityMode = " +
@@ -985,17 +1163,105 @@ export class OPCUAClientImpl extends ClientBaseImpl {
985
1163
  *
986
1164
  * @private
987
1165
  */
988
- computeClientSignature(channel, serverCertificate, serverNonce) {
1166
+ async computeClientSignature(channel, serverCertificate, serverNonce, session) {
989
1167
  // through the opaque key-operations path: works whether the client's
990
1168
  // application instance key is local or HSM/KMS-held
991
- return computeSignatureAsync(serverCertificate, serverNonce || Buffer.alloc(0), this.getKeyOperations(), channel.securityPolicy, this.signServerCertificateChain ? "chain" : "leaf");
1169
+ // a policy for a key on an elliptic curve signs with the key of the client on a curve
1170
+ const policyIsForCurve = eccSecurityPolicies.includes(channel.securityPolicy);
1171
+ const key = policyIsForCurve
1172
+ ? this.#keyOnCurveForPolicy(channel.securityPolicy)
1173
+ : this.#rsaKeyForPolicy(channel.securityPolicy);
1174
+ if (policyIsForCurve && !key) {
1175
+ // no key is not "nothing to sign" here: the request would go with no signature
1176
+ throw new Error(`the security policy ${channel.securityPolicy} needs a private key on an elliptic curve to sign the session, and the key of the client is not on a curve`);
1177
+ }
1178
+ const channelBound = key ? this.#channelBoundContext(channel, session) : null;
1179
+ if (key && channelBound) {
1180
+ // OPC 10000-4, 6.1.8: the signature is bound to the SecureChannel
1181
+ const dataToSign = makeClientSignatureData(channelBound.cryptoFactory, {
1182
+ channelThumbprint: channelBound.channelThumbprint,
1183
+ serverNonce: serverNonce || Buffer.alloc(0),
1184
+ serverCertificate,
1185
+ serverChannelCertificate: channelBound.serverChannelCertificate,
1186
+ clientChannelCertificate: channelBound.clientChannelCertificate,
1187
+ clientNonce: channelBound.clientNonce
1188
+ });
1189
+ return await signChannelBoundData(channelBound.cryptoFactory, dataToSign, key);
1190
+ }
1191
+ return await computeSignatureAsync(serverCertificate, serverNonce || Buffer.alloc(0), key, channel.securityPolicy, this.signServerCertificateChain ? "chain" : "leaf");
1192
+ }
1193
+ /**
1194
+ * What the signatures of a session are bound to (OPC 10000-4, 6.1.8), and null when the policy
1195
+ * of the channel has the earlier calculation. It throws when the policy has the binding and the
1196
+ * session has not the nonce of CreateSession, or the channel has no ChannelThumbprint.
1197
+ */
1198
+ #channelBoundContext(channel, session) {
1199
+ const cryptoFactory = getCryptoFactory(channel.securityPolicy);
1200
+ if (!cryptoFactory || !usesChannelBoundSignatures(cryptoFactory)) {
1201
+ return null;
1202
+ }
1203
+ const clientNonce = session?._clientNonce;
1204
+ const channelThumbprint = channel.channelThumbprint;
1205
+ if (!clientNonce || !channelThumbprint) {
1206
+ throw new Error(`the security policy ${channel.securityPolicy} needs the nonce of CreateSession and the ChannelThumbprint to sign the session`);
1207
+ }
1208
+ return {
1209
+ cryptoFactory,
1210
+ channelThumbprint,
1211
+ clientNonce,
1212
+ serverChannelCertificate: Array.isArray(this.serverCertificate) ? this.serverCertificate[0] : this.serverCertificate,
1213
+ clientChannelCertificate: channel.getCertificate(),
1214
+ clientCertificate: session?._clientCertificate
1215
+ };
1216
+ }
1217
+ /**
1218
+ * The key of this client on an elliptic curve for a security policy, or null when it has
1219
+ * none: the key of the certificate of that policy, for a client with two certificates.
1220
+ */
1221
+ #keyOnCurveForPolicy(securityPolicy) {
1222
+ const identity = this.getApplicationIdentity?.(securityPolicy);
1223
+ if (identity) {
1224
+ return isEcKeyOperations(identity.keyOperations) ? identity.keyOperations : null;
1225
+ }
1226
+ return getEcKeyOperationsFromProvider(this.getProvider());
1227
+ }
1228
+ /** the RSA key of this client for a security policy: the twin of {@link #keyOnCurveForPolicy} */
1229
+ #rsaKeyForPolicy(securityPolicy) {
1230
+ const identity = this.getApplicationIdentity?.(securityPolicy);
1231
+ if (identity && !isEcKeyOperations(identity.keyOperations)) {
1232
+ return identity.keyOperations;
1233
+ }
1234
+ return this.getKeyOperations();
992
1235
  }
993
1236
  /**
994
1237
  * requireTrustedServerForUserName: the password goes only encrypted, and only to a server
995
1238
  * whose CreateSession certificate passes the client certificate manager
996
1239
  */
997
- async #assertServerFitForUserName(context, token) {
998
- if (!token.encryptionAlgorithm) {
1240
+ /**
1241
+ * Keeps the ephemeral key of an additional header of the server, for the secret of the next
1242
+ * user identity token of `session`. The key must be signed with the certificate of the
1243
+ * server: an error is returned for another key, and nothing is kept.
1244
+ */
1245
+ #takeServerEphemeralKey(session, additionalHeader) {
1246
+ const key = readEcdhKey(additionalHeader);
1247
+ if (!key || !this._secureChannel) {
1248
+ return null;
1249
+ }
1250
+ if (!("publicKey" in key)) {
1251
+ // the server gave a status in place of a key
1252
+ session._serverEphemeralKey = null;
1253
+ return null;
1254
+ }
1255
+ const securityPolicy = this._secureChannel.securityPolicy;
1256
+ if (!verifySignedEphemeralKey(securityPolicy, key.publicKey, key.signature, session.serverCertificate)) {
1257
+ session._serverEphemeralKey = null;
1258
+ return new Error("BadSecurityChecksFailed: the ephemeral key of the server for the user identity token is not signed with the certificate of the server");
1259
+ }
1260
+ session._serverEphemeralKey = { securityPolicy, publicKey: key.publicKey };
1261
+ return null;
1262
+ }
1263
+ async #assertServerFitForUserName(context, token, passwordIsProtected = false) {
1264
+ if (!passwordIsProtected && !token.encryptionAlgorithm) {
999
1265
  throw new Error("CLIENT: requireTrustedServerForUserName is set and the user name token would carry the password in clear text" +
1000
1266
  " (the server gives no certificate, or its user token policy uses SecurityPolicy None)");
1001
1267
  }
@@ -1049,6 +1315,18 @@ export class OPCUAClientImpl extends ClientBaseImpl {
1049
1315
  case UserTokenType.UserName: {
1050
1316
  const userName = userIdentityInfo.userName || "";
1051
1317
  const password = userIdentityInfo.password || "";
1318
+ const policyWithKeyAgreement = keyAgreementPolicyOfUserNameToken(context);
1319
+ if (policyWithKeyAgreement) {
1320
+ createUserNameIdentityTokenWithKeyAgreement(context, policyWithKeyAgreement, userName, password)
1321
+ .then(async (token) => {
1322
+ if (this.requireTrustedServerForUserName) {
1323
+ await this.#assertServerFitForUserName(context, token, true);
1324
+ }
1325
+ callback(null, { userIdentityToken: token, userTokenSignature });
1326
+ })
1327
+ .catch((err) => callback(err));
1328
+ return;
1329
+ }
1052
1330
  const userNameToken = createUserNameIdentityToken(context, userName, password);
1053
1331
  if (this.requireTrustedServerForUserName) {
1054
1332
  this.#assertServerFitForUserName(context, userNameToken).then(() => callback(null, { userIdentityToken: userNameToken, userTokenSignature }), (err) => callback(err));