ua_securechannel.c 42 KB

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