node-opcua-client 2.189.0 → 2.191.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
@@ -48,7 +48,7 @@ function _sendRepublish(session: ClientSessionImpl, subscription: ClientSubscrip
48
48
  subscriptionId: subscription.subscriptionId
49
49
  });
50
50
 
51
- /* c8 ignore next */
51
+ /* c8 ignore start */
52
52
  if (doDebug) {
53
53
  /* c8 ignore next */
54
54
  debugLog(
@@ -58,6 +58,7 @@ function _sendRepublish(session: ClientSessionImpl, subscription: ClientSubscrip
58
58
  request.retransmitSequenceNumber
59
59
  );
60
60
  }
61
+ /* c8 ignore stop */
61
62
 
62
63
  if (!session || session._closeEventHasBeenEmitted) {
63
64
  /* c8 ignore next */
@@ -106,11 +107,12 @@ async function _republish(engine: ClientSidePublishEngine, subscription: ClientS
106
107
  isDone = result.isDone;
107
108
  }
108
109
 
109
- /* c8 ignore next */
110
+ /* c8 ignore start */
110
111
  if (doDebug) {
111
112
  debugLog("nbPendingPublishRequest = ", engine.nbPendingPublishRequests);
112
113
  debugLog(" _republish ends with ", "null");
113
114
  }
115
+ /* c8 ignore stop */
114
116
  }
115
117
 
116
118
  async function __askSubscriptionRepublish(engine: ClientSidePublishEngine, subscription: ClientSubscriptionImpl): Promise<void> {
@@ -144,11 +146,12 @@ async function __askSubscriptionRepublish(engine: ClientSidePublishEngine, subsc
144
146
  // In this case, Client must recreate a subscription and recreate monitored item without altering
145
147
  // the event handlers
146
148
  //
147
- /* c8 ignore next */
149
+ /* c8 ignore start */
148
150
  doDebug &&
149
151
  debugLog(
150
152
  chalk.bgWhite.red("__askSubscriptionRepublish failed " + " subscriptionId is not valid anymore on server side.")
151
153
  );
154
+ /* c8 ignore stop */
152
155
  await recreateSubscriptionAndMonitoredItem(subscription);
153
156
  return;
154
157
  }
@@ -94,10 +94,11 @@ export async function recreateSubscriptionAndMonitoredItem(_subscription: Client
94
94
  });
95
95
 
96
96
  const session = subscription.session;
97
- /* c8 ignore next */
97
+ /* c8 ignore start */
98
98
  if (!session) {
99
99
  throw new Error("no session");
100
100
  }
101
+ /* c8 ignore stop */
101
102
 
102
103
  /* c8 ignore next */
103
104
  doDebug && debugLog("Recreating ", itemsToCreate.length, " monitored items");
@@ -108,17 +109,19 @@ export async function recreateSubscriptionAndMonitoredItem(_subscription: Client
108
109
  let _errCount = 0;
109
110
  monitoredItemResults.forEach((monitoredItemResult, index) => {
110
111
  const itemToCreate = itemsToCreate[index];
111
- /* c8 ignore next */
112
+ /* c8 ignore start */
112
113
  if (!itemToCreate?.requestedParameters) {
113
114
  _errCount++;
114
115
  return;
115
116
  }
117
+ /* c8 ignore stop */
116
118
  const clientHandle = itemToCreate.requestedParameters.clientHandle;
117
- /* c8 ignore next */
119
+ /* c8 ignore start */
118
120
  if (!clientHandle) {
119
121
  _errCount++;
120
122
  return;
121
123
  }
124
+ /* c8 ignore stop */
122
125
  const monitoredItem = subscription.monitoredItems[clientHandle] as ClientMonitoredItemImpl;
123
126
  if (monitoredItem) {
124
127
  monitoredItem._applyResult(monitoredItemResult);
@@ -321,13 +321,14 @@ function attempt_subscription_transfer(
321
321
  }
322
322
 
323
323
  const results = transferSubscriptionsResponse.results || [];
324
- // c8 ignore next
324
+ /* c8 ignore start */
325
325
  if (doDebug) {
326
326
  debugLog(
327
327
  chalk.cyan(" => transfer subscriptions done"),
328
328
  results.map((x) => x.statusCode.toString()).join(" ")
329
329
  );
330
330
  }
331
+ /* c8 ignore stop */
331
332
 
332
333
  const subscriptionsToRecreate = [];
333
334
 
@@ -384,16 +385,17 @@ async function repair_client_session_by_recreating_a_new_session_async(
384
385
  // and may be upgraded in between, we have to invalidate the extra data type manager
385
386
  invalidateExtraDataTypeManager(session);
386
387
 
387
- // c8 ignore next
388
+ /* c8 ignore start */
388
389
  if (doDebug) {
389
390
  debugLog(" repairing client session by_recreating a new session for old session ", session.sessionId.toString());
390
391
  }
392
+ /* c8 ignore stop */
391
393
 
392
394
  const listenerCountBefore = session.listenerCount("");
393
395
 
394
396
  // Step 1: suspend old session publish engine
395
397
  _throwIfShouldNotContinue(session);
396
- // c8 ignore next
398
+ /* c8 ignore next */
397
399
  doDebug && debugLog(chalk.bgWhite.red(" => suspend old session publish engine...."));
398
400
  session.getPublishEngine().suspend(true);
399
401
 
@@ -585,7 +587,7 @@ export function repair_client_session(client: IClientBase, session: ClientSessio
585
587
  return;
586
588
  }
587
589
 
588
- // c8 ignore next
590
+ /* c8 ignore next */
589
591
  doDebug && debugLog(chalk.yellow("session has been restored"), session.sessionId.toString());
590
592
  session.emit("session_restored");
591
593
  callback(err);
@@ -0,0 +1,109 @@
1
+ /**
2
+ * @module node-opcua-client-private
3
+ */
4
+ import { type Certificate, split_der } from "node-opcua-crypto";
5
+ import {
6
+ getCryptoFactory,
7
+ makeServerSignatureData,
8
+ type SecurityPolicy,
9
+ usesChannelBoundSignatures,
10
+ verifyChannelBoundData,
11
+ verifySignature
12
+ } from "node-opcua-secure-channel";
13
+ import { MessageSecurityMode } from "node-opcua-service-secure-channel";
14
+ import { type StatusCode, StatusCodes } from "node-opcua-status-code";
15
+ import type { SignatureData } from "node-opcua-types";
16
+
17
+ export interface ServerSignatureCheckInput {
18
+ /** security mode of the SecureChannel that carries the CreateSession call */
19
+ securityMode: MessageSecurityMode;
20
+ /** SecurityPolicy of that SecureChannel */
21
+ securityPolicy: SecurityPolicy;
22
+ /** the server certificate (or chain) that the client used to open the SecureChannel */
23
+ channelServerCertificate: Certificate | Certificate[] | null | undefined;
24
+ /** CreateSessionRequest.clientCertificate, as the client sent it (leaf or chain) */
25
+ clientCertificate: Certificate | null | undefined;
26
+ /** CreateSessionRequest.clientNonce */
27
+ clientNonce: Buffer | null | undefined;
28
+ /** CreateSessionResponse.serverCertificate (leaf or chain) */
29
+ serverCertificate: Certificate | null | undefined;
30
+ /** CreateSessionResponse.serverSignature */
31
+ serverSignature: SignatureData | null | undefined;
32
+ /**
33
+ * For a policy with SecureChannelEnhancements, the signature is bound to the channel (OPC 10000-4
34
+ * 6.1.8): the ChannelThumbprint of the SecureChannel, the certificate that this client used to
35
+ * open it, and CreateSessionResponse.serverNonce.
36
+ */
37
+ channelThumbprint?: Buffer | null;
38
+ clientChannelCertificate?: Certificate | null;
39
+ serverNonce?: Buffer | null;
40
+ }
41
+
42
+ function leafOf(certificate: Certificate | Certificate[] | null | undefined): Certificate | null {
43
+ if (!certificate) {
44
+ return null;
45
+ }
46
+ const first = Array.isArray(certificate) ? certificate[0] : certificate;
47
+ if (!first || first.length === 0) {
48
+ return null;
49
+ }
50
+ try {
51
+ return split_der(first)[0] || null;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Checks the server part of a CreateSession response (OPC 10000-4 v1.05.07 §5.7.2.2, Table 15):
59
+ *
60
+ * - serverCertificate: "the Client shall verify that this Certificate is the same as the one it
61
+ * used to create the SecureChannel". Only the leaf certificates are compared, because the server
62
+ * may send its chain in one place and its leaf in the other.
63
+ * - serverSignature: calculated with the method of §6.1.8 (legacy form, Table 102): the signature,
64
+ * made with the key of the serverCertificate, over clientCertificate | clientNonce.
65
+ * §6.1.8 also says that the ClientSignature shall not be computed until the ServerSignature is
66
+ * validated.
67
+ *
68
+ * With the security mode None no signature is generated (Table 15), and the check is skipped.
69
+ *
70
+ * @returns StatusCodes.Good, BadCertificateInvalid when the response certificate is not the
71
+ * certificate of the SecureChannel, or BadApplicationSignatureInvalid when the signature
72
+ * is missing or does not verify.
73
+ */
74
+ export function checkCreateSessionServerSignature(input: ServerSignatureCheckInput): StatusCode {
75
+ if (input.securityMode === MessageSecurityMode.None) {
76
+ return StatusCodes.Good;
77
+ }
78
+ const channelLeaf = leafOf(input.channelServerCertificate);
79
+ const responseLeaf = leafOf(input.serverCertificate);
80
+ if (!channelLeaf || !responseLeaf || !channelLeaf.equals(responseLeaf)) {
81
+ return StatusCodes.BadCertificateInvalid;
82
+ }
83
+ const serverSignature = input.serverSignature;
84
+ if (!serverSignature?.signature || serverSignature.signature.length === 0) {
85
+ return StatusCodes.BadApplicationSignatureInvalid;
86
+ }
87
+ if (!input.clientCertificate || input.clientCertificate.length === 0 || !input.clientNonce) {
88
+ return StatusCodes.BadApplicationSignatureInvalid;
89
+ }
90
+ const cryptoFactory = getCryptoFactory(input.securityPolicy);
91
+ if (cryptoFactory && usesChannelBoundSignatures(cryptoFactory)) {
92
+ if (!input.channelThumbprint || !input.serverNonce || !input.clientNonce) {
93
+ return StatusCodes.BadApplicationSignatureInvalid;
94
+ }
95
+ const dataToVerify = makeServerSignatureData(cryptoFactory, {
96
+ channelThumbprint: input.channelThumbprint,
97
+ clientNonce: input.clientNonce,
98
+ serverChannelCertificate: channelLeaf,
99
+ clientChannelCertificate: input.clientChannelCertificate,
100
+ serverNonce: input.serverNonce
101
+ });
102
+ return verifyChannelBoundData(cryptoFactory, dataToVerify, serverSignature, responseLeaf)
103
+ ? StatusCodes.Good
104
+ : StatusCodes.BadApplicationSignatureInvalid;
105
+ }
106
+ // verifySignature tries the leaf of clientCertificate first, then the whole chain, as §6.1.8 asks
107
+ const ok = verifySignature(input.clientCertificate, input.clientNonce, serverSignature, responseLeaf, input.securityPolicy);
108
+ return ok ? StatusCodes.Good : StatusCodes.BadApplicationSignatureInvalid;
109
+ }
@@ -156,7 +156,7 @@ export class ClientReverseConnect {
156
156
  server.removeListener("error", onListenError);
157
157
  const addr = server.address();
158
158
  this.#listeningPort = addr && typeof addr === "object" ? addr.port : port;
159
- // c8 ignore next
159
+ /* c8 ignore next */
160
160
  doDebug && debugLog(`ClientReverseConnect listening on ${host}:${this.#listeningPort}`);
161
161
  resolve();
162
162
  });
@@ -340,7 +340,7 @@ export class ClientReverseConnect {
340
340
  }
341
341
 
342
342
  // no waiter yet: hold the validated connection briefly in case a client registers imminently.
343
- // c8 ignore next
343
+ /* c8 ignore next */
344
344
  doDebug && debugLog(`reverse connection from ${serverUri} held (no matching client yet)`);
345
345
  timer = setTimeout(() => {
346
346
  timer = undefined;
@@ -46,10 +46,11 @@ export function readHistoryServerCapabilities(
46
46
  if (err) {
47
47
  return callback(err);
48
48
  }
49
- /* c8 ignore next */
49
+ /* c8 ignore start */
50
50
  if (!result) {
51
51
  return callback(new Error("Internal Error"));
52
52
  }
53
+ /* c8 ignore stop */
53
54
  if (result.statusCode.isNotGood()) {
54
55
  return callback(new Error(`StatusCode = ${result.statusCode.toString()}`));
55
56
  }
@@ -98,10 +99,11 @@ export function readHistoryServerCapabilities(
98
99
  if (innerErr) {
99
100
  return callback(innerErr);
100
101
  }
101
- /* c8 ignore next */
102
+ /* c8 ignore start */
102
103
  if (!results) {
103
104
  return callback(new Error("Internal Error"));
104
105
  }
106
+ /* c8 ignore stop */
105
107
 
106
108
  const nodeIds = results.map((innerResult: BrowsePathResult) =>
107
109
  innerResult.statusCode.isGood() && innerResult.targets ? innerResult.targets[0].targetId : new NodeId()
@@ -118,10 +120,11 @@ export function readHistoryServerCapabilities(
118
120
  if (err2) {
119
121
  return callback(err2);
120
122
  }
121
- /* c8 ignore next */
123
+ /* c8 ignore start */
122
124
  if (!dataValues) {
123
125
  return callback(new Error("Internal Error"));
124
126
  }
127
+ /* c8 ignore stop */
125
128
 
126
129
  for (let i = 0; i < dataValues.length; i++) {
127
130
  const propName = lowerFirstLetter(properties[i]);
package/source/verify.ts CHANGED
@@ -5,7 +5,6 @@ import { PrivateKeyUnavailableError } from "node-opcua-crypto";
5
5
  import {
6
6
  type Certificate,
7
7
  exploreCertificate,
8
- explorePrivateKey,
9
8
  extractPublicKeyFromCertificateSync,
10
9
  type PrivateKey,
11
10
  publicKeyAndPrivateKeyMatches
@@ -104,9 +103,19 @@ export function verifyIsOPCUAValidCertificate(
104
103
  `certificateFile = ${certificateFile}\n`
105
104
  );
106
105
  }
106
+ // a key on an elliptic curve signs and does not encrypt: OPC 10000-6, 6.2.2 asks it for
107
+ // digitalSignature, and its strength is the curve, which the security policy checks
108
+ const keyIsOnCurve = certificateInfo.tbsCertificate.subjectPublicKeyInfo.keyType === "ec";
107
109
  const keyUsage = certificateInfo.tbsCertificate.extensions?.keyUsage;
108
110
  if (!keyUsage) {
109
111
  warningLog(`[NODE-OPCUA-W15] The certificate keyUsage is missing\ncertificateFile = ${certificateFile}`);
112
+ } else if (keyIsOnCurve) {
113
+ if (!keyUsage.digitalSignature) {
114
+ warningLog(
115
+ `[NODE-OPCUA-W16] The certificate keyUsage must include digitalSignature.\n` +
116
+ `certificateFile = ${certificateFile}`
117
+ );
118
+ }
110
119
  } else {
111
120
  // spec says that certificate shall include digitalSignature, nonRepudiation, keyEncipherment and dataEncipherment.
112
121
  // Other key uses are allowed.
@@ -135,7 +144,9 @@ export function verifyIsOPCUAValidCertificate(
135
144
  }
136
145
 
137
146
  const keyLengthInBits = certificateInfo.tbsCertificate.subjectPublicKeyInfo.keyLength * 8;
138
- if (keyLengthInBits < 1024) {
147
+ if (keyIsOnCurve) {
148
+ // no RSA key length to check
149
+ } else if (keyLengthInBits < 1024) {
139
150
  errorLog(
140
151
  `[NODE-OPCUA-W19] The public key length shall be greater than or equal to 1024 bits. key length is ${keyLengthInBits}.\n` +
141
152
  `see https://reference.opcfoundation.org/v104/GDS/docs/7.6.3/\n` +
@@ -150,6 +161,16 @@ export function verifyIsOPCUAValidCertificate(
150
161
  }
151
162
  }
152
163
 
164
+ /**
165
+ * The length in bits of the RSA key of a certificate, or 0 for a key that is not an RSA key
166
+ * (a key on an elliptic curve, or an Ed25519 key, has no such length). A reader that does not
167
+ * give the key type is taken to read an RSA key.
168
+ */
169
+ export function rsaKeyLengthInBitsOfCertificate(certificate: Certificate): number {
170
+ const info = exploreCertificate(certificate).tbsCertificate.subjectPublicKeyInfo;
171
+ return info.keyType === "rsa" || info.keyType === undefined ? info.keyLength * 8 : 0;
172
+ }
173
+
153
174
  export async function performCertificateSanityCheck(
154
175
  secureObject: OPCUASecureObject,
155
176
  serverOrClient: "server" | "client",
@@ -181,16 +202,17 @@ export async function performCertificateSanityCheck(
181
202
  "[NODE-OPCUA-E01] Configuration error : the certificate and the private key do not match ! please fix your configuration"
182
203
  );
183
204
  }
184
- // verify that the certificate provided has the right key length ( at least 2048)
185
- const privateKeyInfo = explorePrivateKey(privateKey);
186
- const keyLengthInBits = privateKeyInfo.modulus.length * 8;
187
- if (keyLengthInBits <= 1024) {
188
- warningLog(
189
- `[NODE-OPCUA-W04] The public/private key pair uses a key length which is equal or lower than 1024 bits. ( key length was ${keyLengthInBits} )\n` +
190
- `OPCUA version 1.04 requires that security key length are greater or equal to 2048 bits.\n` +
191
- `The ${serverOrClient} is operating at risk. `
192
- );
193
- }
205
+ }
206
+ // verify that the certificate provided has the right key length ( at least 2048)
207
+ // The certificate and the key match (checked above): the certificate says what the key is,
208
+ // also when the process cannot read the key.
209
+ const keyLengthInBits = rsaKeyLengthInBitsOfCertificate(certificate);
210
+ if (keyLengthInBits > 0 && keyLengthInBits <= 1024) {
211
+ warningLog(
212
+ `[NODE-OPCUA-W04] The public/private key pair uses a key length which is equal or lower than 1024 bits. ( key length was ${keyLengthInBits} )\n` +
213
+ `OPCUA version 1.04 requires that security key length are greater or equal to 2048 bits.\n` +
214
+ `The ${serverOrClient} is operating at risk. `
215
+ );
194
216
  }
195
217
 
196
218
  const options = {