ua_securechannel.c 43 KB

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