ua_securechannel.c 43 KB

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