Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export function iterateOnSignedAndEncryptedMessageChunks(buffer: Buffer, callback: ChunkVisitorFunc) {
const params = {signatureLength: 128, algorithm: "RSA-SHA1", privateKey: senderPrivateKey};
const options = {
chunkSize: 2048,
cipherBlockSize: 128,
encryptBufferFunc: (chunk: Buffer) => publicEncrypt_long(chunk, receiverPublicKey, 128, 11, RSA_PKCS1_PADDING),
plainBlockSize: 128 - 11,
requestId: 10,
sequenceHeaderSize: 0, // ??
signBufferFunc: (chunk: Buffer) => makeMessageChunkSignature(chunk, params),
signatureLength: 128,
};
const securityHeader = new AsymmetricAlgorithmSecurityHeader({
receiverCertificateThumbprint,
securityPolicyUri: "http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15",
senderCertificate,
});
const msgChunkManager = new SecureMessageChunkManager("OPN", options, securityHeader, sequenceNumberGenerator);
msgChunkManager.on("chunk", (chunk: Buffer, final: boolean) => callback(null, chunk));
msgChunkManager.write(buffer, buffer.length);
msgChunkManager.end();
}
function iterate_on_signed_message_chunks(buffer, callback) {
const params = {signatureLength: 128, algorithm: "RSA-SHA1", privateKey: senderPrivateKey};
const options = {
requestId: 10,
chunkSize: 2048,
signatureLength: 128,
signingFunc: function (chunk) {
return crypto_utils.makeMessageChunkSignature(chunk, params);
}
};
const securityHeader = new AsymmetricAlgorithmSecurityHeader({
securityPolicyUri: "http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15",
senderCertificate: senderCertificate,
receiverCertificateThumbprint: null // null === no encryption ...receiverCertificateThumbprint
});
const msgChunkManager = new SecureMessageChunkManager("OPN", options, securityHeader, sequenceNumberGenerator);
msgChunkManager.on("chunk", function (chunk, final) {
callback(null, chunk);
});
msgChunkManager.write(buffer, buffer.length);
msgChunkManager.end();
}
exports.iterate_on_signed_message_chunks = iterate_on_signed_message_chunks;
algorithm: "RSA-SHA1",
privateKey: senderPrivateKey,
signatureLength: 128,
};
const options = {
chunkSize: 2048,
cipherBlockSize: 0,
plainBlockSize: 0,
requestId: 10,
sequenceHeaderSize: 0,
signBufferFunc: (chunk: Buffer) => makeMessageChunkSignature(chunk, params),
signatureLength: 128,
};
const securityHeader = new AsymmetricAlgorithmSecurityHeader({
receiverCertificateThumbprint: null, // null === no encryption ...receiverCertificateThumbprint
securityPolicyUri: "http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15",
senderCertificate,
});
const msgChunkManager = new SecureMessageChunkManager("OPN", options, securityHeader, sequenceNumberGenerator);
msgChunkManager.on("chunk", (chunk: Buffer, final: boolean) => callback(null, chunk));
msgChunkManager.write(buffer, buffer.length);
msgChunkManager.end();
}
"use strict";
var should = require("should");
var assert = require("node-opcua-assert").assert;
var endpoints_service = require("node-opcua-service-endpoints");
var GetEndpointsResponse = endpoints_service.GetEndpointsResponse;
var EndpointDescription = require("node-opcua-service-endpoints").EndpointDescription;
var ApplicationType = require("node-opcua-service-endpoints").ApplicationType;
var UserTokenType = require("node-opcua-service-endpoints").UserTokenType;
var MessageSecurityMode = require("node-opcua-service-secure-channel").MessageSecurityMode;
exports.fixture1 = (function () {
// empty GetEndpointsResponse
return new GetEndpointsResponse();
})();
exports.makeEndPoint = function () {
var data = {
endpointUrl: "toto",
server: {
applicationUri: "OPCUA node-js",
productUri: "some product uri",
export function performMessageChunkManagerTest(options: SecureMessageChunkManagerOptions) {
options = options || {};
const securityHeader = new SymmetricAlgorithmSecurityHeader();
const bodySize = 32;
const headerSize = 12 + securityHeader.binaryStoreSize();
options.signatureLength = options.signatureLength || 0; // 128 bytes for signature
options.chunkSize = bodySize + options.signatureLength + headerSize + 8; // bodySize useful bytes
options.requestId = 1;
const sequenceNumberGenerator = new SequenceNumberGenerator();
const msgChunkManager = new SecureMessageChunkManager(
"HEL", options, securityHeader, sequenceNumberGenerator
);
const chunks: Buffer[] = [];
import { ActivateSessionResponse, CreateSessionResponse } from "node-opcua-service-session";
import { AcknowledgeMessage } from "node-opcua-transport";
import { DirectTransport } from "node-opcua-transport/dist/test_helpers";
import * as _ from "underscore";
const debugLog = make_debugLog(__filename);
export const fakeAcknowledgeMessage = new AcknowledgeMessage({
maxChunkCount: 600000,
maxMessageSize: 100000,
protocolVersion: 0,
receiveBufferSize: 8192,
sendBufferSize: 8192,
});
export const fakeCloseSecureChannelResponse = new CloseSecureChannelResponse({});
export const fakeOpenSecureChannelResponse = new OpenSecureChannelResponse({
serverProtocolVersion: 0,
securityToken: {
channelId: 23,
createdAt: new Date(), // now
revisedLifetime: 30000,
tokenId: 1,
},
serverNonce: Buffer.from("qwerty")
});
export const fakeGetEndpointsResponse = new GetEndpointsResponse({
endpoints: [
{
const openSecureChannelResponse = response as OpenSecureChannelResponse;
// record channelId for future transactions
this.channelId = openSecureChannelResponse.securityToken.channelId;
// todo : verify that server certificate is valid
// A self-signed application instance certificate does not need to be verified with a CA.
// todo : verify that Certificate URI matches the ApplicationURI of the server
assert(openSecureChannelResponse.securityToken.tokenId > 0 || msgType === "OPN",
"_sendSecureOpcUARequest: invalid token Id ");
assert(openSecureChannelResponse.hasOwnProperty("serverNonce"));
this.securityToken = openSecureChannelResponse.securityToken;
this.serverNonce = openSecureChannelResponse.serverNonce;
if (this.securityMode !== MessageSecurityMode.None) {
// verify that server nonce if provided is at least 32 bytes long
/* istanbul ignore next */
if (!openSecureChannelResponse.serverNonce) {
console.log(" client : server nonce is invalid !");
return callback(new Error(" Invalid server nonce"));
}
// This parameter shall have a length equal to key size used for the symmetric
// encryption algorithm that is identified by the securityPolicyUri.
if (openSecureChannelResponse.serverNonce.length !== this.clientNonce.length) {
console.log(" client : server nonce is invalid !");
return callback(new Error(" Invalid server nonce length"));
}
}
const cryptoFactory = this.messageBuilder.cryptoFactory;
serviceResult: serviceResult
},
serverProtocolVersion: self.protocolVersion,
securityToken: self.securityToken,
serverNonce: self.serverNonce
});
// get the clientCertificate from message securityHeader
// for convenience
self.clientCertificate = message.securityHeader ? message.securityHeader.senderCertificate : null;
let description;
// If the SecurityMode is not None then the Server shall verify that a SenderCertificate and a
// ReceiverCertificateThumbprint were specified in the SecurityHeader.
if (self.securityMode.value !== MessageSecurityMode.NONE.value) {
if (!_check_receiverCertificateThumbprint.call(self, self.clientSecurityHeader)) {
description =
"Server#OpenSecureChannelRequest : Invalid receiver certificate thumbprint : the thumbprint doesn't match server certificate !";
console.log(description.cyan);
response.responseHeader.serviceResult = StatusCodes.BadCertificateInvalid;
}
}
if (self.clientCertificate) {
const certificate_status = _check_certificate_validity(self.clientCertificate);
if (StatusCodes.Good !== certificate_status) {
description = "Sender Certificate Error";
console.log(description.cyan, certificate_status.toString().bgRed.yellow);
// OPCUA specification v1.02 part 6 page 42 $6.7.4
// If an error occurs after the Server has verified Message security it shall return a ServiceFault instead
// of a OpenSecureChannel response. The ServiceFault Message is described in Part 4, 7.28.
// which are two different nonce, with different size (although they share the same name )
self.clientNonce = crypto.randomBytes(32);
const request = new CreateSessionRequest({
clientDescription: applicationDescription,
serverUri: self.serverUri,
endpointUrl: self.endpointUrl,
sessionName: self._nextSessionName(),
clientNonce: self.clientNonce,
clientCertificate: self.getCertificate(),
requestedSessionTimeout: self.requestedSessionTimeout,
maxResponseMessageSize: 800000
});
/* a client Nonce must be provided if security mode is set*/
assert(self._secureChannel.securityMode === MessageSecurityMode.NONE || request.clientNonce !== null);
self.performMessageTransaction(request, function (err, response) {
if (!err) {
//xx console.log("xxxxx response",response.toString());
//xx console.log("xxxxx response",response.responseHeader.serviceResult);
if (response.responseHeader.serviceResult === StatusCodes.BadTooManySessions) {
err = new Error("Too Many Sessions : " + response.responseHeader.serviceResult.toString());
} else if (response.responseHeader.serviceResult === StatusCodes.Good) {
assert(response instanceof CreateSessionResponse);
// istanbul ignore next
if (!validateServerNonce(request.serverNonce)) {
return callback(new Error("invalid server Nonce"));
}
// We shall decrypt it with the receiver private key.
const buf = binaryStream.buffer.slice(binaryStream.length);
if (!securityTokenData.derivedKeys) {
console.log("xxxxxxx NO DERIVED KEYX");
return false;
}
const derivedKeys: DerivedKeys = securityTokenData.derivedKeys;
assert(derivedKeys !== null);
assert(derivedKeys.signatureLength > 0, " must provide a signature length");
if (this.securityMode === MessageSecurityMode.SignAndEncrypt) {
const decryptedBuffer = decryptBufferWithDerivedKeys(buf, derivedKeys);
// replace decrypted buffer in initial buffer
decryptedBuffer.copy(binaryStream.buffer, binaryStream.length);
// adjust length
binaryStream.buffer = binaryStream.buffer.slice(0, binaryStream.length + decryptedBuffer.length);
/* istanbul ignore next */
if (doDebug) {
debugLog(chalk.cyan("DE-----------------------------"));
debugLog(hexDump(binaryStream.buffer));
debugLog(chalk.cyan("-------------------------------"));
}
}