ua_securechannel.c 42 KB

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