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
@@ -9,12 +9,15 @@ import chalk from "chalk";
9
9
  import { assert } from "node-opcua-assert";
10
10
  import type { LocaleId } from "node-opcua-basic-types";
11
11
  import { DataTypeExtractStrategy } from "node-opcua-client-dynamic-extension-object";
12
+ import { getEcKeyOperationsFromProvider } from "node-opcua-common";
12
13
  import {
13
14
  type Certificate,
14
15
  combine_der,
15
16
  exploreCertificate,
16
17
  extractPublicKeyFromCertificateSync,
18
+ type IEcKeyOperations,
17
19
  type IKeyOperations,
20
+ isEcKeyOperations,
18
21
  makePrivateKeyFromPem,
19
22
  type Nonce,
20
23
  type PrivateKey,
@@ -28,11 +31,23 @@ import type { NodeId } from "node-opcua-nodeid";
28
31
  import { readNamespaceArray } from "node-opcua-pseudo-session";
29
32
  import {
30
33
  type ClientSecureChannelLayer,
34
+ type CryptoFactory,
31
35
  computeSignatureAsync,
36
+ eccSecurityPolicies,
32
37
  fromURI,
33
38
  getCryptoFactory,
39
+ hasAsymmetricEncryption,
40
+ makeClientSignatureData,
41
+ makeEccEncryptedSecret,
42
+ makeEcdhPolicyUriHeader,
43
+ makeUserTokenSignatureData,
44
+ readEcdhKey,
34
45
  SecurityPolicy,
35
- toCryptoKeyObject
46
+ signChannelBoundData,
47
+ toCryptoKeyObject,
48
+ usesChannelBoundSignatures,
49
+ usesEccEncryptedSecret,
50
+ verifySignedEphemeralKey
36
51
  } from "node-opcua-secure-channel";
37
52
  import {
38
53
  type ApplicationDescriptionOptions,
@@ -69,6 +84,7 @@ import { ClientBaseImpl } from "./client_base_impl.js";
69
84
  import { ClientSessionImpl } from "./client_session_impl.js";
70
85
  import type { IClientBase } from "./i_private_client.js";
71
86
  import { repair_client_sessions } from "./reconnection/reconnection.js";
87
+ import { checkCreateSessionServerSignature } from "./verify_server_signature.js";
72
88
 
73
89
  interface TokenAndSignature {
74
90
  userIdentityToken: UserIdentityToken | null;
@@ -220,6 +236,29 @@ interface IdentityTokenContext {
220
236
  securityPolicy: SecurityPolicy;
221
237
  serverCertificate: Certificate;
222
238
  serverNonce: Buffer;
239
+ /** the ephemeral key that the server gave for the secret of the user identity token */
240
+ serverEphemeralKey?: { securityPolicy: string; publicKey: Buffer } | null;
241
+ /** the key of the application certificate of the client, when it is on an elliptic curve */
242
+ applicationKeyOnCurve?: () => IEcKeyOperations | null;
243
+ /** called when the ephemeral key of the server is in a token: the server takes it one time */
244
+ ephemeralKeyIsUsed?: () => void;
245
+ /**
246
+ * What the signature of a user certificate is bound to: null for a channel whose policy has no
247
+ * SecureChannelEnhancements. It throws when the channel has them and a value is missing.
248
+ */
249
+ channelBound?: () => ChannelBoundContext | null;
250
+ }
251
+
252
+ /** What the signatures of a session are bound to (OPC 10000-4, 6.1.8). */
253
+ interface ChannelBoundContext {
254
+ cryptoFactory: CryptoFactory;
255
+ channelThumbprint: Buffer;
256
+ /** the nonce of the client in CreateSession */
257
+ clientNonce: Buffer;
258
+ serverChannelCertificate: Certificate | null | undefined;
259
+ clientChannelCertificate: Certificate | null | undefined;
260
+ /** the certificate that the CreateSession request sent */
261
+ clientCertificate: Certificate | null | undefined;
223
262
  }
224
263
 
225
264
  function createAnonymousIdentityToken(context: IdentityTokenContext): AnonymousIdentityToken {
@@ -231,6 +270,38 @@ function createAnonymousIdentityToken(context: IdentityTokenContext): AnonymousI
231
270
  return new AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
232
271
  }
233
272
 
273
+ /**
274
+ * The user certificate token policy of the endpoint for `certificate`. A server with more than
275
+ * one family of key has one such policy for each: the one whose security policy signs with the
276
+ * key of the certificate is taken, an RSA key or a key on an elliptic curve. The first one is
277
+ * taken when none fits, as before.
278
+ */
279
+ function findUserCertificateTokenPolicy(
280
+ endpoint: EndpointDescription,
281
+ certificate: Certificate,
282
+ channelSecurityPolicy: SecurityPolicy
283
+ ): UserTokenPolicy | null {
284
+ const candidates = (endpoint.userIdentityTokens || []).filter((token) => token.tokenType === UserTokenType.Certificate);
285
+ if (candidates.length > 1) {
286
+ let keyIsOnCurve: boolean;
287
+ try {
288
+ keyIsOnCurve = exploreCertificate(certificate).tbsCertificate.subjectPublicKeyInfo.keyType === "ec";
289
+ } catch {
290
+ return findUserTokenPolicy(endpoint, UserTokenType.Certificate);
291
+ }
292
+ for (const candidate of candidates) {
293
+ let securityPolicy = fromURI(candidate.securityPolicyUri);
294
+ if (securityPolicy === SecurityPolicy.Invalid) {
295
+ securityPolicy = channelSecurityPolicy;
296
+ }
297
+ if (eccSecurityPolicies.includes(securityPolicy) === keyIsOnCurve) {
298
+ return candidate;
299
+ }
300
+ }
301
+ }
302
+ return findUserTokenPolicy(endpoint, UserTokenType.Certificate);
303
+ }
304
+
234
305
  interface X509TokenAndSignature {
235
306
  userIdentityToken: X509IdentityToken;
236
307
  userTokenSignature: SignatureDataOptions;
@@ -250,11 +321,12 @@ async function createX509IdentityToken(
250
321
  ): Promise<X509TokenAndSignature> {
251
322
  const endpoint = context.endpoint;
252
323
  assert(endpoint instanceof EndpointDescription);
253
- const userTokenPolicy = findUserTokenPolicy(endpoint, UserTokenType.Certificate);
254
- /* c8 ignore next */
324
+ const userTokenPolicy = findUserCertificateTokenPolicy(endpoint, certificate, context.securityPolicy);
325
+ /* c8 ignore start */
255
326
  if (!userTokenPolicy) {
256
327
  throw makeMissingUserTokenPolicyError(endpoint, "Certificate (X509)", UserTokenType.Certificate);
257
328
  }
329
+ /* c8 ignore stop */
258
330
  let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
259
331
 
260
332
  // if the security policy is not specified we use the session security policy
@@ -275,10 +347,11 @@ async function createX509IdentityToken(
275
347
  // see Release 1.02 155 OPC Unified Architecture, Part 4
276
348
  const cryptoFactory = getCryptoFactory(securityPolicy);
277
349
 
278
- /* c8 ignore next */
350
+ /* c8 ignore start */
279
351
  if (!cryptoFactory) {
280
352
  throw new Error(" Unsupported security Policy");
281
353
  }
354
+ /* c8 ignore stop */
282
355
  /**
283
356
  * OPCUA Spec 1.04 - part 4
284
357
  * page 28:
@@ -307,6 +380,23 @@ async function createX509IdentityToken(
307
380
  * the UserTokenPolicy if the SecureChannel has a SecurityPolicy of None.
308
381
  */
309
382
 
383
+ // OPC 10000-4, 6.1.8: the signature is bound to the SecureChannel when the channel and the
384
+ // policy of the user token policy both have the SecureChannelEnhancements
385
+ const channelBound = usesChannelBoundSignatures(cryptoFactory) ? (context.channelBound?.() ?? null) : null;
386
+ if (channelBound) {
387
+ const dataToSign = makeUserTokenSignatureData(cryptoFactory, {
388
+ channelThumbprint: channelBound.channelThumbprint,
389
+ serverNonce,
390
+ serverCertificate,
391
+ serverChannelCertificate: channelBound.serverChannelCertificate,
392
+ clientCertificate: channelBound.clientCertificate,
393
+ clientChannelCertificate: channelBound.clientChannelCertificate,
394
+ clientNonce: channelBound.clientNonce
395
+ });
396
+ const userTokenSignature = (await signChannelBoundData(cryptoFactory, dataToSign, userKey)) as SignatureDataOptions;
397
+ return { userIdentityToken, userTokenSignature };
398
+ }
399
+
310
400
  // now create the proof of possession, by creating a signature
311
401
  // The data to sign is created by appending the last serverNonce to the serverCertificate
312
402
 
@@ -343,10 +433,11 @@ function createUserNameIdentityToken(
343
433
  */
344
434
  const userTokenPolicy = findUserTokenPolicy(endpoint, UserTokenType.UserName);
345
435
 
346
- /* c8 ignore next */
436
+ /* c8 ignore start */
347
437
  if (!userTokenPolicy) {
348
438
  throw makeMissingUserTokenPolicyError(endpoint, "USERNAME", UserTokenType.UserName);
349
439
  }
440
+ /* c8 ignore stop */
350
441
 
351
442
  let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
352
443
 
@@ -394,10 +485,16 @@ function createUserNameIdentityToken(
394
485
  // see Release 1.02 155 OPC Unified Architecture, Part 4
395
486
  const cryptoFactory = getCryptoFactory(securityPolicy);
396
487
 
397
- /* c8 ignore next */
488
+ /* c8 ignore start */
398
489
  if (!cryptoFactory) {
399
490
  throw new Error(` Unsupported security Policy ${securityPolicy.toString()}`);
400
491
  }
492
+ /* c8 ignore stop */
493
+ /* c8 ignore start */
494
+ if (!hasAsymmetricEncryption(cryptoFactory)) {
495
+ throw new Error(`the security policy ${securityPolicy.toString()} has no asymmetric encryption for a password`);
496
+ }
497
+ /* c8 ignore stop */
401
498
 
402
499
  identityToken = new UserNameIdentityToken({
403
500
  encryptionAlgorithm: cryptoFactory.asymmetricEncryptionAlgorithm,
@@ -415,6 +512,69 @@ function createUserNameIdentityToken(
415
512
  return identityToken;
416
513
  }
417
514
 
515
+ /**
516
+ * The SecurityPolicy of the user name token of the endpoint, when the password for it is an
517
+ * EccEncryptedSecret: a policy for a key on an elliptic curve. null for another policy.
518
+ */
519
+ function keyAgreementPolicyOfUserNameToken(context: IdentityTokenContext): SecurityPolicy | null {
520
+ const userTokenPolicy = findUserTokenPolicy(context.endpoint, UserTokenType.UserName);
521
+ if (!userTokenPolicy) {
522
+ return null;
523
+ }
524
+ let securityPolicy = fromURI(userTokenPolicy.securityPolicyUri);
525
+ if (securityPolicy === SecurityPolicy.Invalid) {
526
+ securityPolicy = context.securityPolicy;
527
+ }
528
+ return usesEccEncryptedSecret(securityPolicy) ? securityPolicy : null;
529
+ }
530
+
531
+ /**
532
+ * The user name token for a SecurityPolicy for a key on an elliptic curve: the password is an
533
+ * EccEncryptedSecret (OPC 10000-4, 7.40.2.5), made for the ephemeral key of the server and
534
+ * signed with the key of the application certificate of the client. The password never goes
535
+ * with less protection: with no ephemeral key, or no key on a curve, there is no token.
536
+ */
537
+ async function createUserNameIdentityTokenWithKeyAgreement(
538
+ context: IdentityTokenContext,
539
+ securityPolicy: SecurityPolicy,
540
+ userName: string,
541
+ password: string
542
+ ): Promise<UserNameIdentityToken> {
543
+ const userTokenPolicy = findUserTokenPolicy(context.endpoint, UserTokenType.UserName);
544
+ /* c8 ignore start */
545
+ if (!userTokenPolicy) {
546
+ throw makeMissingUserTokenPolicyError(context.endpoint, "USERNAME", UserTokenType.UserName);
547
+ }
548
+ /* c8 ignore stop */
549
+ const serverKey = context.serverEphemeralKey;
550
+ if (!serverKey || serverKey.securityPolicy !== securityPolicy) {
551
+ throw new Error(
552
+ `the server gave no ephemeral key for the security policy ${securityPolicy}: the password cannot be protected, and it is not sent`
553
+ );
554
+ }
555
+ const signingKey = context.applicationKeyOnCurve?.() ?? null;
556
+ if (!signingKey) {
557
+ throw new Error(
558
+ `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`
559
+ );
560
+ }
561
+ const encryptedPassword = await makeEccEncryptedSecret({
562
+ securityPolicy,
563
+ secret: Buffer.from(password, "utf-8"),
564
+ nonce: context.serverNonce || Buffer.alloc(0),
565
+ receiverPublicKey: serverKey.publicKey,
566
+ signingKey
567
+ });
568
+ context.ephemeralKeyIsUsed?.();
569
+ return new UserNameIdentityToken({
570
+ // no algorithm name: this policy has no asymmetric encryption
571
+ encryptionAlgorithm: null,
572
+ password: encryptedPassword,
573
+ policyId: userTokenPolicy.policyId,
574
+ userName
575
+ });
576
+ }
577
+
418
578
  function _adjustRevisedSessionTimeout(revisedSessionTimeout: number, requestedTimeout: number): number {
419
579
  // Some old OPCUA Servers are known to report an invalid revisedSessionTimeout
420
580
  // such as Siemens SimoCode Pro V.
@@ -534,10 +694,11 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
534
694
  if (err) {
535
695
  callback(err);
536
696
  } else {
537
- /* c8 ignore next */
697
+ /* c8 ignore start */
538
698
  if (!session) {
539
699
  return callback(new Error("Internal Error"));
540
700
  }
701
+ /* c8 ignore stop */
541
702
 
542
703
  this._addSession(session as ClientSessionImpl);
543
704
 
@@ -795,7 +956,7 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
795
956
  if (!this._secureChannel) {
796
957
  return callback?.(new Error(" client must be connected first"));
797
958
  }
798
- // c8 ignore next
959
+ /* c8 ignore start */
799
960
  if (!this.__resolveEndPoint() || !this.endpoint) {
800
961
  return callback?.(
801
962
  new Error(
@@ -808,6 +969,7 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
808
969
  )
809
970
  );
810
971
  }
972
+ /* c8 ignore stop */
811
973
 
812
974
  assert(
813
975
  !internalSession._client || matchUri(internalSession._client.endpointUrl, this.endpointUrl),
@@ -816,7 +978,7 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
816
978
 
817
979
  const old_client = internalSession._client;
818
980
 
819
- // c8 ignore next
981
+ /* c8 ignore next */
820
982
  doDebug && debugLog("OPCUAClientImpl#reactivateSession");
821
983
 
822
984
  this._activateSession(
@@ -838,10 +1000,11 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
838
1000
  }
839
1001
  callback?.();
840
1002
  } else {
841
- // c8 ignore next
1003
+ /* c8 ignore start */
842
1004
  if (doDebug) {
843
1005
  debugLog(chalk.red.bgWhite("reactivateSession has failed !"), err.message);
844
1006
  }
1007
+ /* c8 ignore stop */
845
1008
  callback?.(err);
846
1009
  }
847
1010
  }
@@ -869,11 +1032,12 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
869
1032
  assert(this.endpointUrl !== undefined, " must have a valid server endpointUrl");
870
1033
  assert(this.endpoint);
871
1034
 
872
- // c8 ignore next
1035
+ /* c8 ignore start */
873
1036
  if (!this._secureChannel) {
874
1037
  callback(new Error("Invalid channel"));
875
1038
  return;
876
1039
  }
1040
+ /* c8 ignore stop */
877
1041
 
878
1042
  const applicationUri = this._getApplicationUri();
879
1043
 
@@ -895,7 +1059,8 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
895
1059
  const sessionName = session.name;
896
1060
 
897
1061
  const request = new CreateSessionRequest({
898
- clientCertificate: this.getCertificate(),
1062
+ // the certificate of the SecureChannel: a client can have one for each family of key
1063
+ clientCertificate: this._secureChannel?.getCertificate() ?? this.getCertificate(),
899
1064
  clientDescription: applicationDescription,
900
1065
  clientNonce: this.clientNonce,
901
1066
  endpointUrl: this.endpointUrl,
@@ -908,10 +1073,16 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
908
1073
  // a client Nonce must be provided if security mode is set
909
1074
  assert(this._secureChannel.securityMode === MessageSecurityMode.None || request.clientNonce !== null);
910
1075
 
1076
+ // OPC 10000-6, 6.8.2: with a policy for a key on an elliptic curve, the client asks the server
1077
+ // for an ephemeral key, to protect the secret of its user identity token
1078
+ if (usesEccEncryptedSecret(this._secureChannel.securityPolicy)) {
1079
+ request.requestHeader.additionalHeader = makeEcdhPolicyUriHeader(this._secureChannel.securityPolicy);
1080
+ }
1081
+
911
1082
  this.performMessageTransaction(request, (err: Error | null, response?: Response) => {
912
- /* c8 ignore next */
1083
+ /* c8 ignore start */
913
1084
  if (err) {
914
- // c8 ignore next
1085
+ /* c8 ignore next */
915
1086
  doDebug && debugLog("__createSession_step3 has failed", err.message);
916
1087
  return callback(err);
917
1088
  // // we could have an invalid state here or a connection error
@@ -922,11 +1093,13 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
922
1093
  // }, 5 * 1000);
923
1094
  // return;
924
1095
  }
1096
+ /* c8 ignore stop */
925
1097
 
926
- /* c8 ignore next */
1098
+ /* c8 ignore start */
927
1099
  if (!response || !(response instanceof CreateSessionResponse)) {
928
1100
  return callback(new Error("internal error"));
929
1101
  }
1102
+ /* c8 ignore stop */
930
1103
 
931
1104
  if (response.responseHeader.serviceResult === StatusCodes.BadTooManySessions) {
932
1105
  return callback(new Error(response.responseHeader.serviceResult.toString()));
@@ -939,13 +1112,42 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
939
1112
  return callback(err);
940
1113
  }
941
1114
 
942
- // c8 ignore next
1115
+ /* c8 ignore start */
943
1116
  if (!validateServerNonce(response.serverNonce)) {
944
1117
  return callback(new Error("Invalid server Nonce"));
945
1118
  }
1119
+ /* c8 ignore stop */
946
1120
 
947
- // todo: verify SignedSoftwareCertificates and response.serverSignature
1121
+ // OPC 10000-4 §5.7.2.2 and §6.1.8: check the server certificate and the server signature
1122
+ // before the session is used and before the client signature is computed.
1123
+ if (!this._secureChannel) {
1124
+ return callback(new Error("Invalid channel"));
1125
+ }
1126
+ const signatureStatus = checkCreateSessionServerSignature({
1127
+ securityMode: this._secureChannel.securityMode,
1128
+ securityPolicy: this._secureChannel.securityPolicy,
1129
+ channelServerCertificate: this.serverCertificate,
1130
+ clientCertificate: request.clientCertificate,
1131
+ clientNonce: request.clientNonce,
1132
+ serverCertificate: response.serverCertificate,
1133
+ serverSignature: response.serverSignature,
1134
+ channelThumbprint: this._secureChannel.channelThumbprint,
1135
+ clientChannelCertificate: request.clientCertificate,
1136
+ serverNonce: response.serverNonce
1137
+ });
1138
+ if (signatureStatus.isNotGood()) {
1139
+ const reason =
1140
+ signatureStatus === StatusCodes.BadCertificateInvalid
1141
+ ? "the server certificate in the CreateSession response is not the certificate of the secure channel"
1142
+ : "the server signature in the CreateSession response is missing or invalid";
1143
+ warningLog(`CreateSession: ${reason} (${signatureStatus.toString()})`);
1144
+ return callback(new Error(`${signatureStatus.toString()}: ${reason}`));
1145
+ }
948
1146
 
1147
+ if (request.clientNonce) {
1148
+ session._clientNonce = request.clientNonce;
1149
+ }
1150
+ session._clientCertificate = request.clientCertificate;
949
1151
  session.name = request.sessionName || "";
950
1152
  session.sessionId = response.sessionId;
951
1153
  session.authenticationToken = response.authenticationToken;
@@ -955,7 +1157,13 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
955
1157
  session.serverCertificate = response.serverCertificate;
956
1158
  session.serverSignature = response.serverSignature;
957
1159
 
958
- // c8 ignore next
1160
+ session._serverEphemeralKey = null;
1161
+ const ephemeralKeyError = this.#takeServerEphemeralKey(session, response.responseHeader.additionalHeader);
1162
+ if (ephemeralKeyError) {
1163
+ return callback(ephemeralKeyError);
1164
+ }
1165
+
1166
+ /* c8 ignore next */
959
1167
  doDebug && debugLog("revised session timeout = ", session.timeout, response.revisedSessionTimeout);
960
1168
 
961
1169
  response.serverEndpoints = response.serverEndpoints || [];
@@ -996,11 +1204,12 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
996
1204
  // see OPCUA Part 4 - $7.35
997
1205
  assert(typeof callback === "function");
998
1206
 
999
- // c8 ignore next
1207
+ /* c8 ignore start */
1000
1208
  if (!this._secureChannel) {
1001
1209
  callback(new Error(" No secure channel"));
1002
1210
  return;
1003
1211
  }
1212
+ /* c8 ignore stop */
1004
1213
 
1005
1214
  // `session.serverCertificate` is captured once, at CreateSession. If the
1006
1215
  // server has rotated its certificate since (push certificate management,
@@ -1034,8 +1243,16 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1034
1243
  endpoint: this.endpoint as EndpointDescription,
1035
1244
  securityPolicy: this._secureChannel.securityPolicy,
1036
1245
  serverCertificate,
1037
- serverNonce: serverNonce as Buffer // please check this !
1246
+ serverNonce: serverNonce as Buffer, // please check this !
1247
+ serverEphemeralKey: session._serverEphemeralKey,
1248
+ applicationKeyOnCurve: () =>
1249
+ this.#keyOnCurveForPolicy((this._secureChannel as ClientSecureChannelLayer).securityPolicy),
1250
+ ephemeralKeyIsUsed: () => {
1251
+ ephemeralKeyIsUsed = true;
1252
+ },
1253
+ channelBound: () => this.#channelBoundContext(this._secureChannel as ClientSecureChannelLayer, session)
1038
1254
  };
1255
+ let ephemeralKeyIsUsed = false;
1039
1256
 
1040
1257
  this.createUserIdentityToken(context, userIdentityInfo, async (err: Error | null, data?: TokenAndSignature | null) => {
1041
1258
  if (err) {
@@ -1052,7 +1269,8 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1052
1269
  (await this.computeClientSignature(
1053
1270
  this._secureChannel as ClientSecureChannelLayer,
1054
1271
  serverCertificate,
1055
- serverNonce
1272
+ serverNonce,
1273
+ session
1056
1274
  )) || undefined;
1057
1275
  } catch (signatureError) {
1058
1276
  session._client = _old_client;
@@ -1114,6 +1332,13 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1114
1332
  });
1115
1333
 
1116
1334
  request.requestHeader.authenticationToken = session.authenticationToken as NodeId;
1335
+ // OPC 10000-6, 6.8.2: the client names the policy in each ActivateSession too, so that
1336
+ // the server gives the ephemeral key for the next one. A server can give a new key
1337
+ // only when it is asked.
1338
+ const channelPolicy = (this._secureChannel as ClientSecureChannelLayer).securityPolicy;
1339
+ if (usesEccEncryptedSecret(channelPolicy)) {
1340
+ request.requestHeader.additionalHeader = makeEcdhPolicyUriHeader(channelPolicy);
1341
+ }
1117
1342
  session.lastRequestSentTime = new Date();
1118
1343
 
1119
1344
  this.performMessageTransaction(request, (err1: Error | null, response?: Response) => {
@@ -1123,10 +1348,11 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1123
1348
  session.noteServerAnswer(err1, response);
1124
1349
 
1125
1350
  if (!err1 && response && response.responseHeader.serviceResult.isGoodish()) {
1126
- /* c8 ignore next */
1351
+ /* c8 ignore start */
1127
1352
  if (!(response instanceof ActivateSessionResponse)) {
1128
1353
  return callback(new Error("Internal Error"));
1129
1354
  }
1355
+ /* c8 ignore stop */
1130
1356
 
1131
1357
  if (!validateServerNonce(response.serverNonce)) {
1132
1358
  return callback(new Error("Invalid server Nonce"));
@@ -1136,6 +1362,14 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1136
1362
  // OPC 10000-18 §5.2.8) so a Client can react without server access.
1137
1363
  session.lastActivateSessionStatusCode = response.responseHeader.serviceResult;
1138
1364
  session.serverNonce = response.serverNonce;
1365
+ // the server takes an ephemeral key one time, and gives the next one in this response
1366
+ if (ephemeralKeyIsUsed) {
1367
+ session._serverEphemeralKey = null;
1368
+ }
1369
+ const ephemeralKeyError = this.#takeServerEphemeralKey(session, response.responseHeader.additionalHeader);
1370
+ if (ephemeralKeyError) {
1371
+ return callback(ephemeralKeyError);
1372
+ }
1139
1373
  if (this.keepSessionAlive) {
1140
1374
  session.startKeepAliveManager(this.keepAliveInterval);
1141
1375
  }
@@ -1145,10 +1379,11 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1145
1379
  // restore client
1146
1380
  session._client = _old_client;
1147
1381
 
1148
- /* c8 ignore next */
1382
+ /* c8 ignore start */
1149
1383
  if (!err1 && response) {
1150
1384
  err1 = new Error(response.responseHeader.serviceResult.toString());
1151
1385
  }
1386
+ /* c8 ignore stop */
1152
1387
  session._client = _old_client;
1153
1388
  return callback(err1);
1154
1389
  }
@@ -1265,7 +1500,7 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1265
1500
  assert(typeof callback === "function");
1266
1501
  assert(this._secureChannel);
1267
1502
  if (!this.__resolveEndPoint() || !this.endpoint) {
1268
- /* c8 ignore next */
1503
+ /* c8 ignore start */
1269
1504
  if (this._serverEndpoints) {
1270
1505
  warningLog(
1271
1506
  "server endpoints =",
@@ -1283,6 +1518,7 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1283
1518
  .join("\n")
1284
1519
  );
1285
1520
  }
1521
+ /* c8 ignore stop */
1286
1522
  return callback(
1287
1523
  new Error(
1288
1524
  " End point must exist " +
@@ -1306,23 +1542,129 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1306
1542
  *
1307
1543
  * @private
1308
1544
  */
1309
- private computeClientSignature(channel: ClientSecureChannelLayer, serverCertificate: Buffer, serverNonce: Nonce | undefined) {
1545
+ private async computeClientSignature(
1546
+ channel: ClientSecureChannelLayer,
1547
+ serverCertificate: Buffer,
1548
+ serverNonce: Nonce | undefined,
1549
+ session?: ClientSessionImpl
1550
+ ) {
1310
1551
  // through the opaque key-operations path: works whether the client's
1311
1552
  // application instance key is local or HSM/KMS-held
1312
- return computeSignatureAsync(
1553
+ // a policy for a key on an elliptic curve signs with the key of the client on a curve
1554
+ const policyIsForCurve = eccSecurityPolicies.includes(channel.securityPolicy);
1555
+ const key = policyIsForCurve
1556
+ ? this.#keyOnCurveForPolicy(channel.securityPolicy)
1557
+ : this.#rsaKeyForPolicy(channel.securityPolicy);
1558
+ if (policyIsForCurve && !key) {
1559
+ // no key is not "nothing to sign" here: the request would go with no signature
1560
+ throw new Error(
1561
+ `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`
1562
+ );
1563
+ }
1564
+ const channelBound = key ? this.#channelBoundContext(channel, session) : null;
1565
+ if (key && channelBound) {
1566
+ // OPC 10000-4, 6.1.8: the signature is bound to the SecureChannel
1567
+ const dataToSign = makeClientSignatureData(channelBound.cryptoFactory, {
1568
+ channelThumbprint: channelBound.channelThumbprint,
1569
+ serverNonce: serverNonce || Buffer.alloc(0),
1570
+ serverCertificate,
1571
+ serverChannelCertificate: channelBound.serverChannelCertificate,
1572
+ clientChannelCertificate: channelBound.clientChannelCertificate,
1573
+ clientNonce: channelBound.clientNonce
1574
+ });
1575
+ return await signChannelBoundData(channelBound.cryptoFactory, dataToSign, key);
1576
+ }
1577
+ return await computeSignatureAsync(
1313
1578
  serverCertificate,
1314
1579
  serverNonce || Buffer.alloc(0),
1315
- this.getKeyOperations(),
1580
+ key,
1316
1581
  channel.securityPolicy,
1317
1582
  this.signServerCertificateChain ? "chain" : "leaf"
1318
1583
  );
1319
1584
  }
1585
+ /**
1586
+ * What the signatures of a session are bound to (OPC 10000-4, 6.1.8), and null when the policy
1587
+ * of the channel has the earlier calculation. It throws when the policy has the binding and the
1588
+ * session has not the nonce of CreateSession, or the channel has no ChannelThumbprint.
1589
+ */
1590
+ #channelBoundContext(channel: ClientSecureChannelLayer, session?: ClientSessionImpl): ChannelBoundContext | null {
1591
+ const cryptoFactory = getCryptoFactory(channel.securityPolicy);
1592
+ if (!cryptoFactory || !usesChannelBoundSignatures(cryptoFactory)) {
1593
+ return null;
1594
+ }
1595
+ const clientNonce = session?._clientNonce;
1596
+ const channelThumbprint = channel.channelThumbprint;
1597
+ if (!clientNonce || !channelThumbprint) {
1598
+ throw new Error(
1599
+ `the security policy ${channel.securityPolicy} needs the nonce of CreateSession and the ChannelThumbprint to sign the session`
1600
+ );
1601
+ }
1602
+ return {
1603
+ cryptoFactory,
1604
+ channelThumbprint,
1605
+ clientNonce,
1606
+ serverChannelCertificate: Array.isArray(this.serverCertificate) ? this.serverCertificate[0] : this.serverCertificate,
1607
+ clientChannelCertificate: channel.getCertificate(),
1608
+ clientCertificate: session?._clientCertificate
1609
+ };
1610
+ }
1611
+ /**
1612
+ * The key of this client on an elliptic curve for a security policy, or null when it has
1613
+ * none: the key of the certificate of that policy, for a client with two certificates.
1614
+ */
1615
+ #keyOnCurveForPolicy(securityPolicy: SecurityPolicy): IEcKeyOperations | null {
1616
+ const identity = this.getApplicationIdentity?.(securityPolicy);
1617
+ if (identity) {
1618
+ return isEcKeyOperations(identity.keyOperations) ? identity.keyOperations : null;
1619
+ }
1620
+ return getEcKeyOperationsFromProvider(this.getProvider());
1621
+ }
1622
+
1623
+ /** the RSA key of this client for a security policy: the twin of {@link #keyOnCurveForPolicy} */
1624
+ #rsaKeyForPolicy(securityPolicy: SecurityPolicy): IKeyOperations {
1625
+ const identity = this.getApplicationIdentity?.(securityPolicy);
1626
+ if (identity && !isEcKeyOperations(identity.keyOperations)) {
1627
+ return identity.keyOperations;
1628
+ }
1629
+ return this.getKeyOperations();
1630
+ }
1631
+
1320
1632
  /**
1321
1633
  * requireTrustedServerForUserName: the password goes only encrypted, and only to a server
1322
1634
  * whose CreateSession certificate passes the client certificate manager
1323
1635
  */
1324
- async #assertServerFitForUserName(context: IdentityTokenContext, token: UserNameIdentityToken): Promise<void> {
1325
- if (!token.encryptionAlgorithm) {
1636
+ /**
1637
+ * Keeps the ephemeral key of an additional header of the server, for the secret of the next
1638
+ * user identity token of `session`. The key must be signed with the certificate of the
1639
+ * server: an error is returned for another key, and nothing is kept.
1640
+ */
1641
+ #takeServerEphemeralKey(session: ClientSessionImpl, additionalHeader: unknown): Error | null {
1642
+ const key = readEcdhKey(additionalHeader);
1643
+ if (!key || !this._secureChannel) {
1644
+ return null;
1645
+ }
1646
+ if (!("publicKey" in key)) {
1647
+ // the server gave a status in place of a key
1648
+ session._serverEphemeralKey = null;
1649
+ return null;
1650
+ }
1651
+ const securityPolicy = this._secureChannel.securityPolicy;
1652
+ if (!verifySignedEphemeralKey(securityPolicy, key.publicKey, key.signature, session.serverCertificate)) {
1653
+ session._serverEphemeralKey = null;
1654
+ return new Error(
1655
+ "BadSecurityChecksFailed: the ephemeral key of the server for the user identity token is not signed with the certificate of the server"
1656
+ );
1657
+ }
1658
+ session._serverEphemeralKey = { securityPolicy, publicKey: key.publicKey };
1659
+ return null;
1660
+ }
1661
+
1662
+ async #assertServerFitForUserName(
1663
+ context: IdentityTokenContext,
1664
+ token: UserNameIdentityToken,
1665
+ passwordIsProtected = false
1666
+ ): Promise<void> {
1667
+ if (!passwordIsProtected && !token.encryptionAlgorithm) {
1326
1668
  throw new Error(
1327
1669
  "CLIENT: requireTrustedServerForUserName is set and the user name token would carry the password in clear text" +
1328
1670
  " (the server gives no certificate, or its user token policy uses SecurityPolicy None)"
@@ -1391,6 +1733,18 @@ export class OPCUAClientImpl extends ClientBaseImpl<OPCUAClientBaseEvents> {
1391
1733
  case UserTokenType.UserName: {
1392
1734
  const userName = userIdentityInfo.userName || "";
1393
1735
  const password = userIdentityInfo.password || "";
1736
+ const policyWithKeyAgreement = keyAgreementPolicyOfUserNameToken(context);
1737
+ if (policyWithKeyAgreement) {
1738
+ createUserNameIdentityTokenWithKeyAgreement(context, policyWithKeyAgreement, userName, password)
1739
+ .then(async (token) => {
1740
+ if (this.requireTrustedServerForUserName) {
1741
+ await this.#assertServerFitForUserName(context, token, true);
1742
+ }
1743
+ callback(null, { userIdentityToken: token, userTokenSignature });
1744
+ })
1745
+ .catch((err: Error) => callback(err));
1746
+ return;
1747
+ }
1394
1748
  const userNameToken = createUserNameIdentityToken(context, userName, password);
1395
1749
  if (this.requireTrustedServerForUserName) {
1396
1750
  this.#assertServerFitForUserName(context, userNameToken).then(