ua_securechannel.c 40 KB

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