ua_securechannel.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "ua_util.h"
  5. #include "ua_securechannel.h"
  6. #include "ua_types_encoding_binary.h"
  7. #include "ua_types_generated_encoding_binary.h"
  8. #include "ua_transport_generated_encoding_binary.h"
  9. #include "ua_types_generated_handling.h"
  10. #include "ua_transport_generated_handling.h"
  11. #include "ua_plugin_securitypolicy.h"
  12. #define UA_BITMASK_MESSAGETYPE 0x00ffffff
  13. #define UA_BITMASK_CHUNKTYPE 0xff000000
  14. #define UA_ASYMMETRIC_ALG_SECURITY_HEADER_FIXED_LENGTH 12
  15. #define UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH 4
  16. #define UA_SEQUENCE_HEADER_LENGTH 8
  17. #define UA_SECUREMH_AND_SYMALGH_LENGTH \
  18. (UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + \
  19. UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH)
  20. const UA_ByteString
  21. UA_SECURITY_POLICY_NONE_URI = {47, (UA_Byte *) "http://opcfoundation.org/UA/SecurityPolicy#None"};
  22. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  23. UA_THREAD_LOCAL UA_StatusCode decrypt_verifySignatureFailure;
  24. UA_THREAD_LOCAL UA_StatusCode sendAsym_sendFailure;
  25. UA_THREAD_LOCAL UA_StatusCode processSym_seqNumberFailure;
  26. #endif
  27. UA_StatusCode
  28. UA_SecureChannel_init(UA_SecureChannel *channel,
  29. const UA_SecurityPolicy *securityPolicy,
  30. const UA_ByteString *remoteCertificate) {
  31. if(channel == NULL || securityPolicy == NULL || remoteCertificate == NULL)
  32. return UA_STATUSCODE_BADINTERNALERROR;
  33. /* Linked lists are also initialized by zeroing out */
  34. memset(channel, 0, sizeof(UA_SecureChannel));
  35. channel->state = UA_SECURECHANNELSTATE_FRESH;
  36. channel->securityPolicy = securityPolicy;
  37. UA_StatusCode retval = securityPolicy->channelModule.
  38. newContext(securityPolicy, remoteCertificate, &channel->channelContext);
  39. if(retval != UA_STATUSCODE_GOOD)
  40. return retval;
  41. retval = UA_ByteString_copy(remoteCertificate, &channel->remoteCertificate);
  42. if(retval != UA_STATUSCODE_GOOD)
  43. return retval;
  44. UA_ByteString remoteCertificateThumbprint = {20, channel->remoteCertificateThumbprint};
  45. retval = securityPolicy->asymmetricModule.
  46. makeCertificateThumbprint(securityPolicy, &channel->remoteCertificate,
  47. &remoteCertificateThumbprint);
  48. return retval;
  49. }
  50. void
  51. UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel) {
  52. /* Delete members */
  53. UA_ByteString_deleteMembers(&channel->remoteCertificate);
  54. UA_ByteString_deleteMembers(&channel->localNonce);
  55. UA_ByteString_deleteMembers(&channel->remoteNonce);
  56. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  57. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  58. /* Delete the channel context for the security policy */
  59. if(channel->securityPolicy)
  60. channel->securityPolicy->channelModule.deleteContext(channel->channelContext);
  61. /* Detach from the connection and close the connection */
  62. if(channel->connection) {
  63. if(channel->connection->state != UA_CONNECTION_CLOSED)
  64. channel->connection->close(channel->connection);
  65. UA_Connection_detachSecureChannel(channel->connection);
  66. }
  67. /* Remove session pointers (not the sessions) and NULL the pointers back to
  68. * the SecureChannel in the Session */
  69. UA_SessionHeader *sh, *temp;
  70. LIST_FOREACH_SAFE(sh, &channel->sessions, pointers, temp) {
  71. sh->channel = NULL;
  72. LIST_REMOVE(sh, pointers);
  73. }
  74. /* Remove the buffered chunks */
  75. struct ChunkEntry *ch, *temp_ch;
  76. LIST_FOREACH_SAFE(ch, &channel->chunks, pointers, temp_ch) {
  77. UA_ByteString_deleteMembers(&ch->bytes);
  78. LIST_REMOVE(ch, pointers);
  79. UA_free(ch);
  80. }
  81. }
  82. UA_StatusCode
  83. UA_SecureChannel_generateNonce(const UA_SecureChannel *channel,
  84. size_t nonceLength,
  85. UA_ByteString *nonce) {
  86. UA_ByteString_deleteMembers(nonce);
  87. UA_StatusCode retval = UA_ByteString_allocBuffer(nonce, nonceLength);
  88. if(retval != UA_STATUSCODE_GOOD)
  89. return retval;
  90. return channel->securityPolicy->symmetricModule.
  91. generateNonce(channel->securityPolicy, nonce);
  92. }
  93. UA_StatusCode
  94. UA_SecureChannel_generateNewKeys(UA_SecureChannel *channel) {
  95. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  96. const UA_SecurityPolicyChannelModule *channelModule =
  97. &securityPolicy->channelModule;
  98. const UA_SecurityPolicySymmetricModule *symmetricModule =
  99. &securityPolicy->symmetricModule;
  100. /* Symmetric key length */
  101. size_t encryptionKeyLength = symmetricModule->cryptoModule.
  102. getLocalEncryptionKeyLength(securityPolicy, channel->channelContext);
  103. const size_t buffSize = symmetricModule->encryptionBlockSize +
  104. symmetricModule->signingKeyLength + encryptionKeyLength;
  105. UA_ByteString buffer = {buffSize, (UA_Byte *) UA_alloca(buffSize)};
  106. /* Remote keys */
  107. UA_StatusCode retval = symmetricModule->generateKey(securityPolicy, &channel->localNonce,
  108. &channel->remoteNonce, &buffer);
  109. if(retval != UA_STATUSCODE_GOOD)
  110. return retval;
  111. const UA_ByteString remoteSigningKey = {symmetricModule->signingKeyLength, buffer.data};
  112. const UA_ByteString remoteEncryptingKey = {encryptionKeyLength,
  113. buffer.data + symmetricModule->signingKeyLength};
  114. const UA_ByteString remoteIv = {symmetricModule->encryptionBlockSize,
  115. buffer.data + symmetricModule->signingKeyLength +
  116. encryptionKeyLength};
  117. retval = channelModule->setRemoteSymSigningKey(channel->channelContext, &remoteSigningKey);
  118. retval |= channelModule->setRemoteSymEncryptingKey(channel->channelContext, &remoteEncryptingKey);
  119. retval |= channelModule->setRemoteSymIv(channel->channelContext, &remoteIv);
  120. if(retval != UA_STATUSCODE_GOOD)
  121. return retval;
  122. /* Local keys */
  123. retval = symmetricModule->generateKey(securityPolicy, &channel->remoteNonce,
  124. &channel->localNonce, &buffer);
  125. if(retval != UA_STATUSCODE_GOOD)
  126. return retval;
  127. const UA_ByteString localSigningKey = {symmetricModule->signingKeyLength, buffer.data};
  128. const UA_ByteString localEncryptingKey = {encryptionKeyLength,
  129. buffer.data + symmetricModule->signingKeyLength};
  130. const UA_ByteString localIv = {symmetricModule->encryptionBlockSize,
  131. buffer.data + symmetricModule->signingKeyLength +
  132. encryptionKeyLength};
  133. retval = channelModule->setLocalSymSigningKey(channel->channelContext, &localSigningKey);
  134. retval |= channelModule->setLocalSymEncryptingKey(channel->channelContext, &localEncryptingKey);
  135. retval |= channelModule->setLocalSymIv(channel->channelContext, &localIv);
  136. return retval;
  137. }
  138. UA_SessionHeader *
  139. UA_SecureChannel_getSession(UA_SecureChannel *channel,
  140. const UA_NodeId *authenticationToken) {
  141. struct UA_SessionHeader *sh;
  142. LIST_FOREACH(sh, &channel->sessions, pointers) {
  143. if(UA_NodeId_equal(&sh->authenticationToken, authenticationToken))
  144. break;
  145. }
  146. return sh;
  147. }
  148. UA_StatusCode
  149. UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  150. if(channel->nextSecurityToken.tokenId == 0) // no security token issued
  151. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  152. //FIXME: not thread-safe
  153. memcpy(&channel->securityToken, &channel->nextSecurityToken,
  154. sizeof(UA_ChannelSecurityToken));
  155. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  156. return UA_SecureChannel_generateNewKeys(channel);
  157. }
  158. /***************************/
  159. /* Send Asymmetric Message */
  160. /***************************/
  161. static UA_UInt16
  162. calculatePaddingAsym(const UA_SecurityPolicy *securityPolicy, const void *channelContext,
  163. size_t bytesToWrite, UA_Byte *paddingSize, UA_Byte *extraPaddingSize) {
  164. size_t plainTextBlockSize = securityPolicy->channelModule.
  165. getRemoteAsymPlainTextBlockSize(channelContext);
  166. size_t signatureSize = securityPolicy->asymmetricModule.cryptoModule.
  167. getLocalSignatureSize(securityPolicy, channelContext);
  168. size_t paddingBytes = 1;
  169. if(securityPolicy->asymmetricModule.cryptoModule.
  170. getRemoteEncryptionKeyLength(securityPolicy, channelContext) > 2048)
  171. ++paddingBytes;
  172. size_t padding = (plainTextBlockSize - ((bytesToWrite + signatureSize + paddingBytes) %
  173. plainTextBlockSize));
  174. *paddingSize = (UA_Byte) (padding & 0xff);
  175. *extraPaddingSize = (UA_Byte) (padding >> 8);
  176. return (UA_UInt16) padding;
  177. }
  178. static size_t
  179. calculateAsymAlgSecurityHeaderLength(const UA_SecureChannel *channel) {
  180. size_t asymHeaderLength = UA_ASYMMETRIC_ALG_SECURITY_HEADER_FIXED_LENGTH +
  181. channel->securityPolicy->policyUri.length;
  182. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  183. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  184. /* OPN is always encrypted even if mode sign only */
  185. asymHeaderLength += 20; /* Thumbprints are always 20 byte long */
  186. asymHeaderLength += channel->securityPolicy->localCertificate.length;
  187. }
  188. return asymHeaderLength;
  189. }
  190. static void
  191. hideBytesAsym(const UA_SecureChannel *channel, UA_Byte **buf_start, const UA_Byte **buf_end) {
  192. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  193. *buf_start += UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + UA_SEQUENCE_HEADER_LENGTH;
  194. /* Add the SecurityHeaderLength */
  195. *buf_start += calculateAsymAlgSecurityHeaderLength(channel);
  196. size_t potentialEncryptionMaxSize = (size_t) (*buf_end - *buf_start) + UA_SEQUENCE_HEADER_LENGTH;
  197. /* Hide bytes for signature and padding */
  198. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  199. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  200. *buf_end -= securityPolicy->asymmetricModule.cryptoModule.
  201. getLocalSignatureSize(securityPolicy, channel->channelContext);
  202. *buf_end -= 2; /* padding byte and extraPadding byte */
  203. /* Add some overhead length due to RSA implementations adding a signature themselves */
  204. *buf_end -= securityPolicy->channelModule.
  205. getRemoteAsymEncryptionBufferLengthOverhead(channel->channelContext,
  206. potentialEncryptionMaxSize);
  207. }
  208. }
  209. /* Sends an OPN message using asymmetric encryption if defined */
  210. UA_StatusCode
  211. UA_SecureChannel_sendAsymmetricOPNMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  212. const void *content, const UA_DataType *contentType) {
  213. if(channel->securityMode == UA_MESSAGESECURITYMODE_INVALID)
  214. return UA_STATUSCODE_BADSECURITYMODEREJECTED;
  215. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  216. UA_Connection *connection = channel->connection;
  217. if(!connection)
  218. return UA_STATUSCODE_BADINTERNALERROR;
  219. /* Allocate the message buffer */
  220. UA_ByteString buf = UA_BYTESTRING_NULL;
  221. UA_StatusCode retval =
  222. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &buf);
  223. if(retval != UA_STATUSCODE_GOOD)
  224. return retval;
  225. /* Restrict buffer to the available space for the payload */
  226. UA_Byte *buf_pos = buf.data;
  227. const UA_Byte *buf_end = &buf.data[buf.length];
  228. hideBytesAsym(channel, &buf_pos, &buf_end);
  229. /* Encode the message type and content */
  230. UA_NodeId typeId = UA_NODEID_NUMERIC(0, contentType->binaryEncodingId);
  231. retval = UA_encodeBinary(&typeId, &UA_TYPES[UA_TYPES_NODEID], &buf_pos, &buf_end, NULL, NULL);
  232. retval |= UA_encodeBinary(content, contentType, &buf_pos, &buf_end, NULL, NULL);
  233. if(retval != UA_STATUSCODE_GOOD) {
  234. connection->releaseSendBuffer(connection, &buf);
  235. return retval;
  236. }
  237. /* Compute the length of the asym header */
  238. const size_t securityHeaderLength = calculateAsymAlgSecurityHeaderLength(channel);
  239. /* Pad the message. Also if securitymode is only sign, since we are using
  240. * asymmetric communication to exchange keys and thus need to encrypt. */
  241. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  242. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  243. const UA_Byte *buf_body_start =
  244. &buf.data[UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH +
  245. UA_SEQUENCE_HEADER_LENGTH + securityHeaderLength];
  246. const size_t bytesToWrite =
  247. (uintptr_t) buf_pos - (uintptr_t) buf_body_start + UA_SEQUENCE_HEADER_LENGTH;
  248. UA_Byte paddingSize = 0;
  249. UA_Byte extraPaddingSize = 0;
  250. UA_UInt16 totalPaddingSize =
  251. calculatePaddingAsym(securityPolicy, channel->channelContext,
  252. bytesToWrite, &paddingSize, &extraPaddingSize);
  253. // This is <= because the paddingSize byte also has to be written.
  254. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  255. *buf_pos = paddingSize;
  256. ++buf_pos;
  257. }
  258. if(securityPolicy->asymmetricModule.cryptoModule.
  259. getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext) > 2048) {
  260. *buf_pos = extraPaddingSize;
  261. ++buf_pos;
  262. }
  263. }
  264. /* The total message length */
  265. size_t pre_sig_length = (uintptr_t) buf_pos - (uintptr_t) buf.data;
  266. size_t total_length = pre_sig_length;
  267. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  268. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  269. total_length += securityPolicy->asymmetricModule.cryptoModule.
  270. getLocalSignatureSize(securityPolicy, channel->channelContext);
  271. /* Encode the headers at the beginning of the message */
  272. UA_Byte *header_pos = buf.data;
  273. size_t dataToEncryptLength =
  274. total_length - (UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength);
  275. UA_SecureConversationMessageHeader respHeader;
  276. respHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  277. respHeader.messageHeader.messageSize = (UA_UInt32)
  278. (total_length + securityPolicy->channelModule.
  279. getRemoteAsymEncryptionBufferLengthOverhead(channel->channelContext, dataToEncryptLength));
  280. respHeader.secureChannelId = channel->securityToken.channelId;
  281. retval = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  282. &header_pos, &buf_end, NULL, NULL);
  283. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  284. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  285. asymHeader.securityPolicyUri = channel->securityPolicy->policyUri;
  286. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  287. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  288. asymHeader.senderCertificate = channel->securityPolicy->localCertificate;
  289. asymHeader.receiverCertificateThumbprint.length = 20;
  290. asymHeader.receiverCertificateThumbprint.data = channel->remoteCertificateThumbprint;
  291. }
  292. retval |= UA_encodeBinary(&asymHeader, &UA_TRANSPORT[UA_TRANSPORT_ASYMMETRICALGORITHMSECURITYHEADER],
  293. &header_pos, &buf_end, NULL, NULL);
  294. UA_SequenceHeader seqHeader;
  295. seqHeader.requestId = requestId;
  296. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  297. retval |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  298. &header_pos, &buf_end, NULL, NULL);
  299. /* Did encoding the header succeed? */
  300. if(retval != UA_STATUSCODE_GOOD) {
  301. connection->releaseSendBuffer(connection, &buf);
  302. return retval;
  303. }
  304. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  305. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  306. /* Sign message */
  307. const UA_ByteString dataToSign = {pre_sig_length, buf.data};
  308. size_t sigsize = securityPolicy->asymmetricModule.cryptoModule.
  309. getLocalSignatureSize(securityPolicy, channel->channelContext);
  310. UA_ByteString signature = {sigsize, buf.data + pre_sig_length};
  311. retval = securityPolicy->asymmetricModule.cryptoModule.
  312. sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  313. if(retval != UA_STATUSCODE_GOOD) {
  314. connection->releaseSendBuffer(connection, &buf);
  315. return retval;
  316. }
  317. /* Specification part 6, 6.7.4: The OpenSecureChannel Messages are
  318. * signed and encrypted if the SecurityMode is not None (even if the
  319. * SecurityMode is SignOnly). */
  320. size_t unencrypted_length =
  321. UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength;
  322. UA_ByteString dataToEncrypt = {total_length - unencrypted_length,
  323. &buf.data[unencrypted_length]};
  324. retval = securityPolicy->asymmetricModule.cryptoModule.
  325. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  326. if(retval != UA_STATUSCODE_GOOD) {
  327. connection->releaseSendBuffer(connection, &buf);
  328. return retval;
  329. }
  330. }
  331. /* Send the message, the buffer is freed in the network layer */
  332. buf.length = respHeader.messageHeader.messageSize;
  333. retval = connection->send(connection, &buf);
  334. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  335. retval |= sendAsym_sendFailure
  336. #endif
  337. return retval;
  338. }
  339. /**************************/
  340. /* Send Symmetric Message */
  341. /**************************/
  342. static UA_UInt16
  343. calculatePaddingSym(const UA_SecurityPolicy *securityPolicy, const void *channelContext,
  344. size_t bytesToWrite, UA_Byte *paddingSize, UA_Byte *extraPaddingSize) {
  345. UA_UInt16 padding = (UA_UInt16) (securityPolicy->symmetricModule.encryptionBlockSize -
  346. ((bytesToWrite + securityPolicy->symmetricModule.cryptoModule.
  347. getLocalSignatureSize(securityPolicy, channelContext) + 1) %
  348. securityPolicy->symmetricModule.encryptionBlockSize));
  349. *paddingSize = (UA_Byte) padding;
  350. *extraPaddingSize = (UA_Byte) (padding >> 8);
  351. return padding;
  352. }
  353. static void
  354. setBufPos(UA_MessageContext *mc) {
  355. const UA_SecureChannel *channel= mc->channel;
  356. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  357. /* Forward the data pointer so that the payload is encoded after the
  358. * message header */
  359. mc->buf_pos = &mc->messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  360. mc->buf_end = &mc->messageBuffer.data[mc->messageBuffer.length];
  361. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  362. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  363. mc->buf_end -= securityPolicy->symmetricModule.cryptoModule.
  364. getLocalSignatureSize(securityPolicy, channel->channelContext);
  365. /* Hide a byte needed for padding */
  366. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  367. mc->buf_end -= 2;
  368. }
  369. static UA_StatusCode
  370. sendSymmetricChunk(UA_MessageContext *mc) {
  371. UA_StatusCode res = UA_STATUSCODE_GOOD;
  372. UA_SecureChannel *const channel = mc->channel;
  373. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  374. UA_Connection *const connection = channel->connection;
  375. if(!connection)
  376. return UA_STATUSCODE_BADINTERNALERROR;
  377. /* Will this chunk surpass the capacity of the SecureChannel for the message? */
  378. UA_Byte *buf_body_start = mc->messageBuffer.data + UA_SECURE_MESSAGE_HEADER_LENGTH;
  379. const UA_Byte *buf_body_end = mc->buf_pos;
  380. size_t bodyLength = (uintptr_t) buf_body_end - (uintptr_t) buf_body_start;
  381. mc->messageSizeSoFar += bodyLength;
  382. mc->chunksSoFar++;
  383. if(mc->messageSizeSoFar > connection->remoteConf.maxMessageSize &&
  384. connection->remoteConf.maxMessageSize != 0)
  385. res = UA_STATUSCODE_BADRESPONSETOOLARGE;
  386. if(mc->chunksSoFar > connection->remoteConf.maxChunkCount &&
  387. connection->remoteConf.maxChunkCount != 0)
  388. res = UA_STATUSCODE_BADRESPONSETOOLARGE;
  389. if(res != UA_STATUSCODE_GOOD) {
  390. connection->releaseSendBuffer(channel->connection, &mc->messageBuffer);
  391. return res;
  392. }
  393. /* Pad the message. The bytes for the padding and signature were removed
  394. * from buf_end before encoding the payload. So we don't check here. */
  395. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  396. size_t bytesToWrite = bodyLength + UA_SEQUENCE_HEADER_LENGTH;
  397. UA_Byte paddingSize = 0;
  398. UA_Byte extraPaddingSize = 0;
  399. UA_UInt16 totalPaddingSize =
  400. calculatePaddingSym(securityPolicy, channel->channelContext,
  401. bytesToWrite, &paddingSize, &extraPaddingSize);
  402. // This is <= because the paddingSize byte also has to be written.
  403. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  404. *mc->buf_pos = paddingSize;
  405. ++(mc->buf_pos);
  406. }
  407. if(extraPaddingSize > 0) {
  408. *mc->buf_pos = extraPaddingSize;
  409. ++(mc->buf_pos);
  410. }
  411. }
  412. /* The total message length */
  413. size_t pre_sig_length = (uintptr_t) (mc->buf_pos) - (uintptr_t) mc->messageBuffer.data;
  414. size_t total_length = pre_sig_length;
  415. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  416. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  417. total_length += securityPolicy->symmetricModule.cryptoModule.
  418. getLocalSignatureSize(securityPolicy, channel->channelContext);
  419. mc->messageBuffer.length = total_length; /* For giving the buffer to the network layer */
  420. /* Encode the chunk headers at the beginning of the buffer */
  421. UA_assert(res == UA_STATUSCODE_GOOD);
  422. UA_Byte *header_pos = mc->messageBuffer.data;
  423. UA_SecureConversationMessageHeader respHeader;
  424. respHeader.secureChannelId = channel->securityToken.channelId;
  425. respHeader.messageHeader.messageTypeAndChunkType = mc->messageType;
  426. respHeader.messageHeader.messageSize = (UA_UInt32)total_length;
  427. if(mc->final)
  428. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  429. else
  430. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  431. res = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  432. &header_pos, &mc->buf_end, NULL, NULL);
  433. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  434. symSecHeader.tokenId = channel->securityToken.tokenId;
  435. res |= UA_encodeBinary(&symSecHeader.tokenId,
  436. &UA_TRANSPORT[UA_TRANSPORT_SYMMETRICALGORITHMSECURITYHEADER],
  437. &header_pos, &mc->buf_end, NULL, NULL);
  438. UA_SequenceHeader seqHeader;
  439. seqHeader.requestId = mc->requestId;
  440. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  441. res |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  442. &header_pos, &mc->buf_end, NULL, NULL);
  443. /* Sign message */
  444. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  445. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  446. UA_ByteString dataToSign = mc->messageBuffer;
  447. dataToSign.length = pre_sig_length;
  448. UA_ByteString signature;
  449. signature.length = securityPolicy->symmetricModule.cryptoModule.
  450. getLocalSignatureSize(securityPolicy, channel->channelContext);
  451. signature.data = mc->buf_pos;
  452. res |= securityPolicy->symmetricModule.cryptoModule.
  453. sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  454. }
  455. /* Encrypt message */
  456. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  457. UA_ByteString dataToEncrypt;
  458. dataToEncrypt.data = mc->messageBuffer.data + UA_SECUREMH_AND_SYMALGH_LENGTH;
  459. dataToEncrypt.length = total_length - UA_SECUREMH_AND_SYMALGH_LENGTH;
  460. res |= securityPolicy->symmetricModule.cryptoModule.
  461. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  462. }
  463. if(res != UA_STATUSCODE_GOOD) {
  464. connection->releaseSendBuffer(channel->connection, &mc->messageBuffer);
  465. return res;
  466. }
  467. /* Send the chunk, the buffer is freed in the network layer */
  468. return connection->send(channel->connection, &mc->messageBuffer);
  469. }
  470. /* Callback from the encoding layer. Send the chunk and replace the buffer. */
  471. static UA_StatusCode
  472. sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
  473. /* Set buf values from encoding in the messagecontext */
  474. UA_MessageContext *mc = (UA_MessageContext*)data;
  475. mc->buf_pos = *buf_pos;
  476. mc->buf_end = *buf_end;
  477. /* Send out */
  478. UA_StatusCode retval = sendSymmetricChunk(mc);
  479. if(retval != UA_STATUSCODE_GOOD)
  480. return retval;
  481. /* Set a new buffer for the next chunk */
  482. UA_Connection *connection = mc->channel->connection;
  483. retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  484. &mc->messageBuffer);
  485. if(retval != UA_STATUSCODE_GOOD)
  486. return retval;
  487. /* Hide bytes for header, padding and signature */
  488. setBufPos(mc);
  489. *buf_pos = mc->buf_pos;
  490. *buf_end = mc->buf_end;
  491. return UA_STATUSCODE_GOOD;
  492. }
  493. UA_StatusCode
  494. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  495. UA_UInt32 requestId, UA_MessageType messageType) {
  496. UA_Connection *connection = channel->connection;
  497. if(!connection)
  498. return UA_STATUSCODE_BADINTERNALERROR;
  499. /* Create the chunking info structure */
  500. mc->channel = channel;
  501. mc->requestId = requestId;
  502. mc->chunksSoFar = 0;
  503. mc->messageSizeSoFar = 0;
  504. mc->final = false;
  505. mc->messageBuffer = UA_BYTESTRING_NULL;
  506. mc->messageType = messageType;
  507. /* Minimum required size */
  508. if(connection->localConf.sendBufferSize <= UA_SECURE_MESSAGE_HEADER_LENGTH)
  509. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  510. /* Allocate the message buffer */
  511. UA_StatusCode retval =
  512. connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  513. &mc->messageBuffer);
  514. if(retval != UA_STATUSCODE_GOOD)
  515. return retval;
  516. /* Hide bytes for header, padding and signature */
  517. setBufPos(mc);
  518. return UA_STATUSCODE_GOOD;
  519. }
  520. UA_StatusCode
  521. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  522. const UA_DataType *contentType) {
  523. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  524. sendSymmetricEncodingCallback, mc);
  525. if(retval != UA_STATUSCODE_GOOD) {
  526. /* TODO: Send the abort message */
  527. if(mc->messageBuffer.length > 0) {
  528. UA_Connection *connection = mc->channel->connection;
  529. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  530. }
  531. }
  532. return retval;
  533. }
  534. UA_StatusCode
  535. UA_MessageContext_finish(UA_MessageContext *mc) {
  536. mc->final = true;
  537. return sendSymmetricChunk(mc);
  538. }
  539. void
  540. UA_MessageContext_abort(UA_MessageContext *mc) {
  541. UA_Connection *connection = mc->channel->connection;
  542. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  543. }
  544. UA_StatusCode
  545. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  546. UA_MessageType messageType, void *payload,
  547. const UA_DataType *payloadType) {
  548. UA_MessageContext mc;
  549. UA_StatusCode retval;
  550. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  551. retval = UA_MessageContext_begin(&mc, channel, requestId, UA_MESSAGETYPE_MSG);
  552. if(retval != UA_STATUSCODE_GOOD)
  553. return retval;
  554. /* Assert's required for clang-analyzer */
  555. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  556. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  557. retval |= UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  558. if(retval != UA_STATUSCODE_GOOD)
  559. return retval;
  560. retval |= UA_MessageContext_encode(&mc, payload, payloadType);
  561. if(retval != UA_STATUSCODE_GOOD)
  562. return retval;
  563. return UA_MessageContext_finish(&mc);
  564. }
  565. /*****************************/
  566. /* Assemble Complete Message */
  567. /*****************************/
  568. static void
  569. UA_SecureChannel_removeChunks(UA_SecureChannel *channel, UA_UInt32 requestId) {
  570. struct ChunkEntry *ch;
  571. LIST_FOREACH(ch, &channel->chunks, pointers) {
  572. if(ch->requestId == requestId) {
  573. UA_ByteString_deleteMembers(&ch->bytes);
  574. LIST_REMOVE(ch, pointers);
  575. UA_free(ch);
  576. return;
  577. }
  578. }
  579. }
  580. static UA_StatusCode
  581. appendChunk(struct ChunkEntry *chunkEntry, const UA_ByteString *chunkBody) {
  582. UA_Byte *new_bytes = (UA_Byte *)
  583. UA_realloc(chunkEntry->bytes.data, chunkEntry->bytes.length + chunkBody->length);
  584. if(!new_bytes) {
  585. UA_ByteString_deleteMembers(&chunkEntry->bytes);
  586. return UA_STATUSCODE_BADOUTOFMEMORY;
  587. }
  588. chunkEntry->bytes.data = new_bytes;
  589. memcpy(&chunkEntry->bytes.data[chunkEntry->bytes.length], chunkBody->data, chunkBody->length);
  590. chunkEntry->bytes.length += chunkBody->length;
  591. return UA_STATUSCODE_GOOD;
  592. }
  593. static UA_StatusCode
  594. UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  595. const UA_ByteString *chunkBody) {
  596. struct ChunkEntry *ch;
  597. LIST_FOREACH(ch, &channel->chunks, pointers) {
  598. if(ch->requestId == requestId)
  599. break;
  600. }
  601. /* No chunkentry on the channel, create one */
  602. if(!ch) {
  603. ch = (struct ChunkEntry *) UA_malloc(sizeof(struct ChunkEntry));
  604. if(!ch)
  605. return UA_STATUSCODE_BADOUTOFMEMORY;
  606. ch->requestId = requestId;
  607. UA_ByteString_init(&ch->bytes);
  608. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  609. }
  610. return appendChunk(ch, chunkBody);
  611. }
  612. static UA_StatusCode
  613. UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  614. const UA_ByteString *chunkBody, UA_MessageType messageType,
  615. UA_ProcessMessageCallback callback, void *application) {
  616. struct ChunkEntry *chunkEntry;
  617. LIST_FOREACH(chunkEntry, &channel->chunks, pointers) {
  618. if(chunkEntry->requestId == requestId)
  619. break;
  620. }
  621. UA_ByteString bytes;
  622. if(!chunkEntry) {
  623. bytes = *chunkBody;
  624. } else {
  625. UA_StatusCode retval = appendChunk(chunkEntry, chunkBody);
  626. if(retval != UA_STATUSCODE_GOOD)
  627. return retval;
  628. bytes = chunkEntry->bytes;
  629. LIST_REMOVE(chunkEntry, pointers);
  630. UA_free(chunkEntry);
  631. }
  632. UA_StatusCode retval = callback(application, channel, messageType, requestId, &bytes);
  633. if(chunkEntry)
  634. UA_ByteString_deleteMembers(&bytes);
  635. return retval;
  636. }
  637. /****************************/
  638. /* Process a received Chunk */
  639. /****************************/
  640. static UA_StatusCode
  641. decryptChunk(UA_SecureChannel *channel, const UA_SecurityPolicyCryptoModule *cryptoModule,
  642. UA_ByteString *chunk, size_t offset, UA_UInt32 *requestId, UA_UInt32 *sequenceNumber,
  643. UA_ByteString *payload, UA_MessageType messageType) {
  644. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  645. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  646. size_t chunkSizeAfterDecryption = chunk->length;
  647. /* Decrypt the chunk. Always decrypt opn messages if mode not none */
  648. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  649. messageType == UA_MESSAGETYPE_OPN) {
  650. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  651. size_t sizeBeforeDecryption = cipherText.length;
  652. retval = cryptoModule->decrypt(securityPolicy, channel->channelContext, &cipherText);
  653. chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  654. if(retval != UA_STATUSCODE_GOOD)
  655. return retval;
  656. }
  657. /* Verify the chunk signature */
  658. size_t sigsize = 0;
  659. size_t paddingSize = 0;
  660. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  661. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  662. messageType == UA_MESSAGETYPE_OPN) {
  663. /* Compute the padding size */
  664. sigsize = cryptoModule-> getRemoteSignatureSize(securityPolicy, channel->channelContext);
  665. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  666. (messageType == UA_MESSAGETYPE_OPN &&
  667. channel->securityMode != UA_MESSAGESECURITYMODE_NONE)) {
  668. paddingSize = chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  669. size_t keyLength = cryptoModule->
  670. getRemoteEncryptionKeyLength(securityPolicy, channel->channelContext);
  671. if(keyLength > 2048) {
  672. paddingSize <<= 8; /* Extra padding size */
  673. paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  674. }
  675. }
  676. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  677. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  678. /* Verify the signature */
  679. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  680. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  681. retval = cryptoModule->verify(securityPolicy, channel->channelContext,
  682. &chunkDataToVerify, &signature);
  683. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  684. retval |= decrypt_verifySignatureFailure;
  685. #endif
  686. if(retval != UA_STATUSCODE_GOOD)
  687. return retval;
  688. }
  689. /* Decode the sequence header */
  690. UA_SequenceHeader sequenceHeader;
  691. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  692. if(retval != UA_STATUSCODE_GOOD)
  693. return retval;
  694. if(offset + paddingSize + sigsize >= chunk->length)
  695. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  696. *requestId = sequenceHeader.requestId;
  697. *sequenceNumber = sequenceHeader.sequenceNumber;
  698. payload->data = chunk->data + offset;
  699. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  700. return UA_STATUSCODE_GOOD;
  701. }
  702. typedef UA_StatusCode(*UA_SequenceNumberCallback)(UA_SecureChannel *channel,
  703. UA_UInt32 sequenceNumber);
  704. static UA_StatusCode
  705. processSequenceNumberAsym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  706. channel->receiveSequenceNumber = sequenceNumber;
  707. return UA_STATUSCODE_GOOD;
  708. }
  709. static UA_StatusCode
  710. processSequenceNumberSym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  711. /* Failure mode hook for unit tests */
  712. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  713. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  714. return processSym_seqNumberFailure;
  715. #endif
  716. /* Does the sequence number match? */
  717. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  718. /* FIXME: Remove magic numbers :( */
  719. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  720. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  721. else
  722. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  723. }
  724. ++channel->receiveSequenceNumber;
  725. return UA_STATUSCODE_GOOD;
  726. }
  727. static UA_StatusCode
  728. checkAsymHeader(UA_SecureChannel *const channel,
  729. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  730. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  731. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  732. if(!UA_ByteString_equal(&securityPolicy->policyUri, &asymHeader->securityPolicyUri)) {
  733. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  734. }
  735. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  736. /* Something like this
  737. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  738. if(retval != UA_STATUSCODE_GOOD)
  739. return retval;
  740. */
  741. retval = securityPolicy->asymmetricModule.
  742. compareCertificateThumbprint(securityPolicy, &asymHeader->receiverCertificateThumbprint);
  743. if(retval != UA_STATUSCODE_GOOD) {
  744. return retval;
  745. }
  746. return UA_STATUSCODE_GOOD;
  747. }
  748. static UA_StatusCode
  749. checkSymHeader(UA_SecureChannel *const channel,
  750. const UA_UInt32 tokenId) {
  751. if(tokenId != channel->securityToken.tokenId) {
  752. if(tokenId != channel->nextSecurityToken.tokenId)
  753. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  754. return UA_SecureChannel_revolveTokens(channel);
  755. }
  756. return UA_STATUSCODE_GOOD;
  757. }
  758. UA_StatusCode
  759. UA_SecureChannel_processChunk(UA_SecureChannel *channel, UA_ByteString *chunk,
  760. UA_ProcessMessageCallback callback,
  761. void *application) {
  762. /* Decode message header */
  763. size_t offset = 0;
  764. UA_SecureConversationMessageHeader messageHeader;
  765. UA_StatusCode retval =
  766. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  767. if(retval != UA_STATUSCODE_GOOD)
  768. return retval;
  769. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  770. /* The wrong ChannelId. Non-opened channels have the id zero. */
  771. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  772. channel->state != UA_SECURECHANNELSTATE_FRESH)
  773. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  774. #endif
  775. UA_MessageType messageType = (UA_MessageType)
  776. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  777. UA_ChunkType chunkType = (UA_ChunkType)
  778. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  779. /* ERR message (not encrypted) */
  780. UA_UInt32 requestId = 0;
  781. UA_UInt32 sequenceNumber = 0;
  782. UA_ByteString chunkPayload;
  783. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  784. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  785. switch(messageType) {
  786. case UA_MESSAGETYPE_ERR: {
  787. if(chunkType != UA_CHUNKTYPE_FINAL)
  788. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  789. chunkPayload.length = chunk->length - offset;
  790. chunkPayload.data = chunk->data + offset;
  791. return callback(application, channel, messageType, requestId, &chunkPayload);
  792. }
  793. case UA_MESSAGETYPE_MSG:
  794. case UA_MESSAGETYPE_CLO: {
  795. /* Decode and check the symmetric security header (tokenId) */
  796. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  797. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  798. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  799. &symmetricSecurityHeader);
  800. if(retval != UA_STATUSCODE_GOOD)
  801. return retval;
  802. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  803. /* Help fuzzing by always setting the correct tokenId */
  804. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  805. #endif
  806. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId);
  807. if(retval != UA_STATUSCODE_GOOD)
  808. return retval;
  809. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  810. sequenceNumberCallback = processSequenceNumberSym;
  811. break;
  812. }
  813. case UA_MESSAGETYPE_OPN: {
  814. /* Chunking not allowed for OPN */
  815. if(chunkType != UA_CHUNKTYPE_FINAL)
  816. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  817. /* Decode the asymmetric algorithm security header and call the callback
  818. * to perform checks. */
  819. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  820. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  821. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  822. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  823. if(retval != UA_STATUSCODE_GOOD)
  824. return retval;
  825. retval = checkAsymHeader(channel, &asymHeader);
  826. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  827. if(retval != UA_STATUSCODE_GOOD)
  828. return retval;
  829. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  830. sequenceNumberCallback = processSequenceNumberAsym;
  831. break;
  832. }
  833. default:
  834. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  835. }
  836. /* Decrypt message */
  837. UA_assert(cryptoModule != NULL);
  838. retval = decryptChunk(channel, cryptoModule, chunk, offset, &requestId,
  839. &sequenceNumber, &chunkPayload, messageType);
  840. if(retval != UA_STATUSCODE_GOOD)
  841. return retval;
  842. /* Check the sequence number */
  843. if(sequenceNumberCallback == NULL)
  844. return UA_STATUSCODE_BADINTERNALERROR;
  845. retval = sequenceNumberCallback(channel, sequenceNumber);
  846. /* Skip sequence number checking for fuzzer to improve coverage */
  847. if(retval != UA_STATUSCODE_GOOD) {
  848. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  849. return retval;
  850. #else
  851. retval = UA_STATUSCODE_GOOD;
  852. #endif
  853. }
  854. /* Process the payload */
  855. if(chunkType == UA_CHUNKTYPE_FINAL) {
  856. retval = UA_SecureChannel_finalizeChunk(channel, requestId, &chunkPayload,
  857. messageType, callback, application);
  858. } else if(chunkType == UA_CHUNKTYPE_INTERMEDIATE) {
  859. retval = UA_SecureChannel_appendChunk(channel, requestId, &chunkPayload);
  860. } else if(chunkType == UA_CHUNKTYPE_ABORT) {
  861. UA_SecureChannel_removeChunks(channel, requestId);
  862. } else {
  863. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  864. }
  865. return retval;
  866. }