ua_securechannel.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  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) Fraunhofer IOSB (Author: Julius Pfrommer)
  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-2018 (c) Mark Giraud, Fraunhofer IOSB
  12. */
  13. #include "ua_util_internal.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 UA_SECURITY_POLICY_NONE_URI =
  30. {47, (UA_Byte *)"http://opcfoundation.org/UA/SecurityPolicy#None"};
  31. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  32. UA_StatusCode decrypt_verifySignatureFailure;
  33. UA_StatusCode sendAsym_sendFailure;
  34. UA_StatusCode processSym_seqNumberFailure;
  35. #endif
  36. void
  37. UA_SecureChannel_init(UA_SecureChannel *channel) {
  38. /* Linked lists are also initialized by zeroing out */
  39. memset(channel, 0, sizeof(UA_SecureChannel));
  40. channel->state = UA_SECURECHANNELSTATE_FRESH;
  41. TAILQ_INIT(&channel->messages);
  42. }
  43. UA_StatusCode
  44. UA_SecureChannel_setSecurityPolicy(UA_SecureChannel *channel,
  45. const UA_SecurityPolicy *securityPolicy,
  46. const UA_ByteString *remoteCertificate) {
  47. /* Is a policy already configured? */
  48. if(channel->securityPolicy)
  49. return UA_STATUSCODE_BADINTERNALERROR;
  50. channel->securityPolicy = securityPolicy;
  51. UA_StatusCode retval;
  52. if(channel->securityPolicy->certificateVerification != NULL) {
  53. retval = channel->securityPolicy->certificateVerification->
  54. verifyCertificate(channel->securityPolicy->certificateVerification->context,
  55. remoteCertificate);
  56. if(retval != UA_STATUSCODE_GOOD)
  57. return retval;
  58. } else {
  59. UA_LOG_WARNING(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  60. "No PKI plugin set. Accepting all certificates");
  61. }
  62. retval = securityPolicy->channelModule.
  63. newContext(securityPolicy, remoteCertificate, &channel->channelContext);
  64. if(retval != UA_STATUSCODE_GOOD)
  65. return retval;
  66. retval = UA_ByteString_copy(remoteCertificate, &channel->remoteCertificate);
  67. if(retval != UA_STATUSCODE_GOOD)
  68. return retval;
  69. UA_ByteString remoteCertificateThumbprint = {20, channel->remoteCertificateThumbprint};
  70. retval = securityPolicy->asymmetricModule.
  71. makeCertificateThumbprint(securityPolicy, &channel->remoteCertificate,
  72. &remoteCertificateThumbprint);
  73. return retval;
  74. }
  75. static void
  76. deleteMessage(UA_Message *me) {
  77. UA_ChunkPayload *cp;
  78. while((cp = SIMPLEQ_FIRST(&me->chunkPayloads))) {
  79. if(cp->copied)
  80. UA_ByteString_deleteMembers(&cp->bytes);
  81. SIMPLEQ_REMOVE_HEAD(&me->chunkPayloads, pointers);
  82. UA_free(cp);
  83. }
  84. UA_free(me);
  85. }
  86. static void
  87. deleteLatestMessage(UA_SecureChannel *channel, UA_UInt32 requestId) {
  88. UA_Message *me = TAILQ_LAST(&channel->messages, UA_MessageQueue);
  89. if(!me)
  90. return;
  91. if(me->requestId != requestId)
  92. return;
  93. TAILQ_REMOVE(&channel->messages, me, pointers);
  94. deleteMessage(me);
  95. }
  96. void
  97. UA_SecureChannel_deleteMessages(UA_SecureChannel *channel) {
  98. UA_Message *me, *me_tmp;
  99. TAILQ_FOREACH_SAFE(me, &channel->messages, pointers, me_tmp) {
  100. TAILQ_REMOVE(&channel->messages, me, pointers);
  101. deleteMessage(me);
  102. }
  103. }
  104. void
  105. UA_SecureChannel_deleteMembers(UA_SecureChannel *channel) {
  106. /* Delete members */
  107. UA_ByteString_deleteMembers(&channel->remoteCertificate);
  108. UA_ByteString_deleteMembers(&channel->localNonce);
  109. UA_ByteString_deleteMembers(&channel->remoteNonce);
  110. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  111. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  112. /* Delete the channel context for the security policy */
  113. if(channel->securityPolicy)
  114. channel->securityPolicy->channelModule.deleteContext(channel->channelContext);
  115. /* Remove the buffered messages */
  116. UA_SecureChannel_deleteMessages(channel);
  117. }
  118. void
  119. UA_SecureChannel_close(UA_SecureChannel *channel) {
  120. /* Set the status to closed */
  121. channel->state = UA_SECURECHANNELSTATE_CLOSED;
  122. /* Detach from the connection and close the connection */
  123. if(channel->connection) {
  124. if(channel->connection->state != UA_CONNECTION_CLOSED)
  125. channel->connection->close(channel->connection);
  126. UA_Connection_detachSecureChannel(channel->connection);
  127. }
  128. /* Remove session pointers (not the sessions) and NULL the pointers back to
  129. * the SecureChannel in the Session */
  130. UA_SessionHeader *sh, *temp;
  131. LIST_FOREACH_SAFE(sh, &channel->sessions, pointers, temp) {
  132. sh->channel = NULL;
  133. LIST_REMOVE(sh, pointers);
  134. }
  135. }
  136. UA_StatusCode
  137. UA_SecureChannel_generateLocalNonce(UA_SecureChannel *channel) {
  138. if(!channel->securityPolicy)
  139. return UA_STATUSCODE_BADINTERNALERROR;
  140. /* Is the length of the previous nonce correct? */
  141. size_t nonceLength = channel->securityPolicy->symmetricModule.secureChannelNonceLength;
  142. if(channel->localNonce.length != nonceLength) {
  143. UA_ByteString_deleteMembers(&channel->localNonce);
  144. UA_StatusCode retval = UA_ByteString_allocBuffer(&channel->localNonce, nonceLength);
  145. if(retval != UA_STATUSCODE_GOOD)
  146. return retval;
  147. }
  148. return channel->securityPolicy->symmetricModule.
  149. generateNonce(channel->securityPolicy, &channel->localNonce);
  150. }
  151. static UA_StatusCode
  152. UA_SecureChannel_generateLocalKeys(const UA_SecureChannel *const channel,
  153. const UA_SecurityPolicy *const securityPolicy) {
  154. UA_LOG_TRACE_CHANNEL(securityPolicy->logger, channel, "Generating new local keys");
  155. const UA_SecurityPolicyChannelModule *channelModule = &securityPolicy->channelModule;
  156. const UA_SecurityPolicySymmetricModule *symmetricModule = &securityPolicy->symmetricModule;
  157. const UA_SecurityPolicyCryptoModule *const cryptoModule =
  158. &securityPolicy->symmetricModule.cryptoModule;
  159. /* Symmetric key length */
  160. size_t encryptionKeyLength =
  161. cryptoModule->encryptionAlgorithm.getLocalKeyLength(securityPolicy, channel->channelContext);
  162. size_t encryptionBlockSize =
  163. cryptoModule->encryptionAlgorithm.getLocalBlockSize(securityPolicy, channel->channelContext);
  164. size_t signingKeyLength =
  165. cryptoModule->signatureAlgorithm.getLocalKeyLength(securityPolicy, channel->channelContext);
  166. const size_t bufSize = encryptionBlockSize + signingKeyLength + encryptionKeyLength;
  167. UA_STACKARRAY(UA_Byte, bufBytes, bufSize);
  168. UA_ByteString buffer = {bufSize, bufBytes};
  169. /* Local keys */
  170. UA_StatusCode retval = symmetricModule->generateKey(securityPolicy, &channel->remoteNonce,
  171. &channel->localNonce, &buffer);
  172. if(retval != UA_STATUSCODE_GOOD)
  173. return retval;
  174. const UA_ByteString localSigningKey = {signingKeyLength, buffer.data};
  175. const UA_ByteString localEncryptingKey = {encryptionKeyLength,
  176. buffer.data + signingKeyLength};
  177. const UA_ByteString localIv = {encryptionBlockSize,
  178. buffer.data + signingKeyLength +
  179. encryptionKeyLength};
  180. retval = channelModule->setLocalSymSigningKey(channel->channelContext, &localSigningKey);
  181. if(retval != UA_STATUSCODE_GOOD)
  182. return retval;
  183. retval = channelModule->setLocalSymEncryptingKey(channel->channelContext, &localEncryptingKey);
  184. if(retval != UA_STATUSCODE_GOOD)
  185. return retval;
  186. retval = channelModule->setLocalSymIv(channel->channelContext, &localIv);
  187. if(retval != UA_STATUSCODE_GOOD)
  188. return retval;
  189. return retval;
  190. }
  191. static UA_StatusCode
  192. UA_SecureChannel_generateRemoteKeys(const UA_SecureChannel *const channel,
  193. const UA_SecurityPolicy *const securityPolicy) {
  194. UA_LOG_TRACE_CHANNEL(securityPolicy->logger, channel, "Generating new remote keys");
  195. const UA_SecurityPolicyChannelModule *channelModule = &securityPolicy->channelModule;
  196. const UA_SecurityPolicySymmetricModule *symmetricModule = &securityPolicy->symmetricModule;
  197. const UA_SecurityPolicyCryptoModule *const cryptoModule =
  198. &securityPolicy->symmetricModule.cryptoModule;
  199. /* Symmetric key length */
  200. size_t encryptionKeyLength =
  201. cryptoModule->encryptionAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  202. size_t encryptionBlockSize =
  203. cryptoModule->encryptionAlgorithm.getRemoteBlockSize(securityPolicy, channel->channelContext);
  204. size_t signingKeyLength =
  205. cryptoModule->signatureAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  206. const size_t bufSize = encryptionBlockSize + signingKeyLength + encryptionKeyLength;
  207. UA_STACKARRAY(UA_Byte, bufBytes, bufSize);
  208. UA_ByteString buffer = {bufSize, bufBytes};
  209. /* Remote keys */
  210. UA_StatusCode retval = symmetricModule->generateKey(securityPolicy, &channel->localNonce,
  211. &channel->remoteNonce, &buffer);
  212. if(retval != UA_STATUSCODE_GOOD)
  213. return retval;
  214. const UA_ByteString remoteSigningKey = {signingKeyLength, buffer.data};
  215. const UA_ByteString remoteEncryptingKey = {encryptionKeyLength,
  216. buffer.data + signingKeyLength};
  217. const UA_ByteString remoteIv = {encryptionBlockSize,
  218. buffer.data + signingKeyLength +
  219. encryptionKeyLength};
  220. retval = channelModule->setRemoteSymSigningKey(channel->channelContext, &remoteSigningKey);
  221. if(retval != UA_STATUSCODE_GOOD)
  222. return retval;
  223. retval = channelModule->setRemoteSymEncryptingKey(channel->channelContext, &remoteEncryptingKey);
  224. if(retval != UA_STATUSCODE_GOOD)
  225. return retval;
  226. retval = channelModule->setRemoteSymIv(channel->channelContext, &remoteIv);
  227. if(retval != UA_STATUSCODE_GOOD)
  228. return retval;
  229. return retval;
  230. }
  231. UA_StatusCode
  232. UA_SecureChannel_generateNewKeys(UA_SecureChannel *channel) {
  233. UA_StatusCode retval =
  234. UA_SecureChannel_generateLocalKeys(channel, channel->securityPolicy);
  235. if(retval != UA_STATUSCODE_GOOD)
  236. return retval;
  237. retval = UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  238. if(retval != UA_STATUSCODE_GOOD)
  239. return retval;
  240. return retval;
  241. }
  242. UA_SessionHeader *
  243. UA_SecureChannel_getSession(UA_SecureChannel *channel,
  244. const UA_NodeId *authenticationToken) {
  245. UA_SessionHeader *sh;
  246. LIST_FOREACH(sh, &channel->sessions, pointers) {
  247. if(UA_NodeId_equal(&sh->authenticationToken, authenticationToken))
  248. break;
  249. }
  250. return sh;
  251. }
  252. UA_StatusCode
  253. UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  254. if(channel->nextSecurityToken.tokenId == 0) // no security token issued
  255. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  256. //FIXME: not thread-safe ???? Why is this not thread safe?
  257. UA_ChannelSecurityToken_deleteMembers(&channel->previousSecurityToken);
  258. UA_ChannelSecurityToken_copy(&channel->securityToken, &channel->previousSecurityToken);
  259. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  260. UA_ChannelSecurityToken_copy(&channel->nextSecurityToken, &channel->securityToken);
  261. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  262. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  263. /* remote keys are generated later on */
  264. return UA_SecureChannel_generateLocalKeys(channel, channel->securityPolicy);
  265. }
  266. /***************************/
  267. /* Send Asymmetric Message */
  268. /***************************/
  269. static size_t
  270. calculateAsymAlgSecurityHeaderLength(const UA_SecureChannel *channel) {
  271. size_t asymHeaderLength = UA_ASYMMETRIC_ALG_SECURITY_HEADER_FIXED_LENGTH +
  272. channel->securityPolicy->policyUri.length;
  273. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  274. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  275. return asymHeaderLength;
  276. /* OPN is always encrypted even if the mode is sign only */
  277. asymHeaderLength += 20; /* Thumbprints are always 20 byte long */
  278. asymHeaderLength += channel->securityPolicy->localCertificate.length;
  279. return asymHeaderLength;
  280. }
  281. static void
  282. hideBytesAsym(const UA_SecureChannel *channel, UA_Byte **buf_start,
  283. const UA_Byte **buf_end) {
  284. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  285. *buf_start += UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + UA_SEQUENCE_HEADER_LENGTH;
  286. /* Add the SecurityHeaderLength */
  287. *buf_start += calculateAsymAlgSecurityHeaderLength(channel);
  288. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  289. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  290. return;
  291. /* Hide bytes for signature and padding */
  292. size_t potentialEncryptMaxSize = (size_t)(*buf_end - *buf_start) + UA_SEQUENCE_HEADER_LENGTH;
  293. *buf_end -= securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  294. getLocalSignatureSize(securityPolicy, channel->channelContext);
  295. *buf_end -= 2; /* padding byte and extraPadding byte */
  296. /* Add some overhead length due to RSA implementations adding a signature themselves */
  297. *buf_end -= UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(securityPolicy,
  298. channel->channelContext,
  299. potentialEncryptMaxSize);
  300. }
  301. static void
  302. padChunkAsym(UA_SecureChannel *channel, const UA_ByteString *const buf,
  303. size_t securityHeaderLength, UA_Byte **buf_pos) {
  304. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  305. /* Also pad if the securityMode is SIGN_ONLY, since we are using
  306. * asymmetric communication to exchange keys and thus need to encrypt. */
  307. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  308. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  309. return;
  310. const UA_Byte *buf_body_start =
  311. &buf->data[UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH +
  312. UA_SEQUENCE_HEADER_LENGTH + securityHeaderLength];
  313. const size_t bytesToWrite =
  314. (uintptr_t)*buf_pos - (uintptr_t)buf_body_start + UA_SEQUENCE_HEADER_LENGTH;
  315. /* Compute the padding length */
  316. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  317. getRemotePlainTextBlockSize(securityPolicy, channel->channelContext);
  318. size_t signatureSize = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  319. getLocalSignatureSize(securityPolicy, channel->channelContext);
  320. size_t paddingBytes = 1;
  321. if(securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  322. getRemoteKeyLength(securityPolicy, channel->channelContext) > 2048)
  323. ++paddingBytes; /* extra padding */
  324. UA_UInt16 totalPaddingSize =
  325. (plainTextBlockSize - ((bytesToWrite + signatureSize + paddingBytes) % plainTextBlockSize));
  326. /* Write the padding. This is <= because the paddingSize byte also has to be written */
  327. UA_Byte paddingSize = (UA_Byte)(totalPaddingSize & 0xff);
  328. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  329. **buf_pos = paddingSize;
  330. ++*buf_pos;
  331. }
  332. /* Write the extra padding byte if required */
  333. if(securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  334. getRemoteKeyLength(securityPolicy, channel->channelContext) > 2048) {
  335. UA_Byte extraPaddingSize = (UA_Byte)(totalPaddingSize >> 8);
  336. **buf_pos = extraPaddingSize;
  337. ++*buf_pos;
  338. }
  339. }
  340. static UA_StatusCode
  341. prependHeadersAsym(UA_SecureChannel *const channel, UA_Byte *header_pos,
  342. const UA_Byte *buf_end, size_t totalLength,
  343. size_t securityHeaderLength, UA_UInt32 requestId,
  344. size_t *const finalLength) {
  345. UA_StatusCode retval;
  346. size_t dataToEncryptLength =
  347. totalLength - (UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength);
  348. UA_SecureConversationMessageHeader respHeader;
  349. respHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  350. respHeader.messageHeader.messageSize = (UA_UInt32)
  351. (totalLength +
  352. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(channel->securityPolicy,
  353. channel->channelContext,
  354. dataToEncryptLength));
  355. respHeader.secureChannelId = channel->securityToken.channelId;
  356. retval = UA_encodeBinary(&respHeader,
  357. &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  358. &header_pos, &buf_end, NULL, NULL);
  359. if(retval != UA_STATUSCODE_GOOD)
  360. return retval;
  361. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  362. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  363. asymHeader.securityPolicyUri = channel->securityPolicy->policyUri;
  364. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  365. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  366. asymHeader.senderCertificate = channel->securityPolicy->localCertificate;
  367. asymHeader.receiverCertificateThumbprint.length = 20;
  368. asymHeader.receiverCertificateThumbprint.data = channel->remoteCertificateThumbprint;
  369. }
  370. retval = UA_encodeBinary(&asymHeader,
  371. &UA_TRANSPORT[UA_TRANSPORT_ASYMMETRICALGORITHMSECURITYHEADER],
  372. &header_pos, &buf_end, NULL, NULL);
  373. if(retval != UA_STATUSCODE_GOOD)
  374. return retval;
  375. UA_SequenceHeader seqHeader;
  376. seqHeader.requestId = requestId;
  377. seqHeader.sequenceNumber = UA_atomic_addUInt32(&channel->sendSequenceNumber, 1);
  378. retval = UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  379. &header_pos, &buf_end, NULL, NULL);
  380. *finalLength = respHeader.messageHeader.messageSize;
  381. return retval;
  382. }
  383. static UA_StatusCode
  384. signAndEncryptAsym(UA_SecureChannel *const channel, size_t preSignLength,
  385. UA_ByteString *buf, size_t securityHeaderLength,
  386. size_t totalLength) {
  387. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  388. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  389. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  390. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  391. /* Sign message */
  392. const UA_ByteString dataToSign = {preSignLength, buf->data};
  393. size_t sigsize = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  394. getLocalSignatureSize(securityPolicy, channel->channelContext);
  395. UA_ByteString signature = {sigsize, buf->data + preSignLength};
  396. retval = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  397. sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  398. if(retval != UA_STATUSCODE_GOOD)
  399. return retval;
  400. /* Specification part 6, 6.7.4: The OpenSecureChannel Messages are
  401. * signed and encrypted if the SecurityMode is not None (even if the
  402. * SecurityMode is SignOnly). */
  403. size_t unencrypted_length =
  404. UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength;
  405. UA_ByteString dataToEncrypt = {totalLength - unencrypted_length,
  406. &buf->data[unencrypted_length]};
  407. retval = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  408. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  409. if(retval != UA_STATUSCODE_GOOD)
  410. return retval;
  411. }
  412. return retval;
  413. }
  414. /* Sends an OPN message using asymmetric encryption if defined */
  415. UA_StatusCode
  416. UA_SecureChannel_sendAsymmetricOPNMessage(UA_SecureChannel *channel,
  417. UA_UInt32 requestId, const void *content,
  418. const UA_DataType *contentType) {
  419. if(channel->securityMode == UA_MESSAGESECURITYMODE_INVALID)
  420. return UA_STATUSCODE_BADSECURITYMODEREJECTED;
  421. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  422. UA_Connection *connection = channel->connection;
  423. if(!connection)
  424. return UA_STATUSCODE_BADINTERNALERROR;
  425. /* Allocate the message buffer */
  426. UA_ByteString buf = UA_BYTESTRING_NULL;
  427. UA_StatusCode retval =
  428. connection->getSendBuffer(connection, connection->config.sendBufferSize, &buf);
  429. if(retval != UA_STATUSCODE_GOOD)
  430. goto error;
  431. /* Restrict buffer to the available space for the payload */
  432. UA_Byte *buf_pos = buf.data;
  433. const UA_Byte *buf_end = &buf.data[buf.length];
  434. hideBytesAsym(channel, &buf_pos, &buf_end);
  435. /* Encode the message type and content */
  436. UA_NodeId typeId = UA_NODEID_NUMERIC(0, contentType->binaryEncodingId);
  437. retval = UA_encodeBinary(&typeId, &UA_TYPES[UA_TYPES_NODEID],
  438. &buf_pos, &buf_end, NULL, NULL);
  439. if(retval != UA_STATUSCODE_GOOD)
  440. goto error;
  441. retval = UA_encodeBinary(content, contentType,
  442. &buf_pos, &buf_end, NULL, NULL);
  443. if(retval != UA_STATUSCODE_GOOD)
  444. goto error;
  445. const size_t securityHeaderLength = calculateAsymAlgSecurityHeaderLength(channel);
  446. /* Add padding to the chunk */
  447. padChunkAsym(channel, &buf, securityHeaderLength, &buf_pos);
  448. /* The total message length */
  449. size_t pre_sig_length = (uintptr_t)buf_pos - (uintptr_t)buf.data;
  450. size_t total_length = pre_sig_length;
  451. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  452. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  453. total_length += securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  454. getLocalSignatureSize(securityPolicy, channel->channelContext);
  455. /* The total message length is known here which is why we */
  456. /* encode the headers at this step and not earlier. */
  457. size_t finalLength = 0;
  458. retval = prependHeadersAsym(channel, buf.data, buf_end, total_length,
  459. securityHeaderLength, requestId, &finalLength);
  460. if(retval != UA_STATUSCODE_GOOD)
  461. goto error;
  462. retval = signAndEncryptAsym(channel, pre_sig_length, &buf, securityHeaderLength, total_length);
  463. if(retval != UA_STATUSCODE_GOOD)
  464. goto error;
  465. /* Send the message, the buffer is freed in the network layer */
  466. buf.length = finalLength;
  467. retval = connection->send(connection, &buf);
  468. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  469. retval |= sendAsym_sendFailure
  470. #endif
  471. return retval;
  472. error:
  473. connection->releaseSendBuffer(connection, &buf);
  474. return retval;
  475. }
  476. /**************************/
  477. /* Send Symmetric Message */
  478. /**************************/
  479. static UA_UInt16
  480. calculatePaddingSym(const UA_SecurityPolicy *securityPolicy, const void *channelContext,
  481. size_t bytesToWrite, UA_Byte *paddingSize, UA_Byte *extraPaddingSize) {
  482. size_t encryptionBlockSize = securityPolicy->symmetricModule.cryptoModule.
  483. encryptionAlgorithm.getLocalBlockSize(securityPolicy, channelContext);
  484. size_t signatureSize = securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  485. getLocalSignatureSize(securityPolicy, channelContext);
  486. UA_UInt16 padding = (UA_UInt16)
  487. (encryptionBlockSize - ((bytesToWrite + signatureSize + 1) % encryptionBlockSize));
  488. *paddingSize = (UA_Byte)padding;
  489. *extraPaddingSize = (UA_Byte)(padding >> 8);
  490. return padding;
  491. }
  492. static void
  493. setBufPos(UA_MessageContext *mc) {
  494. const UA_SecureChannel *channel = mc->channel;
  495. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  496. /* Forward the data pointer so that the payload is encoded after the
  497. * message header */
  498. mc->buf_pos = &mc->messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  499. mc->buf_end = &mc->messageBuffer.data[mc->messageBuffer.length];
  500. /* Reserve space for the message footer at the end of the chunk if the chunk
  501. * is signed and/or encrypted. The footer includes the fields PaddingSize,
  502. * Padding, ExtraPadding and Signature. The padding fields are only present
  503. * if the chunk is encrypted. */
  504. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  505. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  506. mc->buf_end -= securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  507. getLocalSignatureSize(securityPolicy, channel->channelContext);
  508. /* The size of the padding depends on the amount of data that shall be sent
  509. * and is unknown at this point. Reserve space for the PaddingSize byte,
  510. * the maximum amount of Padding which equals the block size of the
  511. * symmetric encryption algorithm and last 1 byte for the ExtraPaddingSize
  512. * field that is present if the encryption key is larger than 2048 bits.
  513. * The actual padding size is later calculated by the function
  514. * calculatePaddingSym(). */
  515. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  516. /* PaddingSize and ExtraPaddingSize fields */
  517. size_t encryptionBlockSize = securityPolicy->symmetricModule.cryptoModule.
  518. encryptionAlgorithm.getLocalBlockSize(securityPolicy, channel->channelContext);
  519. mc->buf_end -= 1 + ((encryptionBlockSize >> 8) ? 1 : 0);
  520. /* Reduce the message body size with the remainder of the operation
  521. * maxEncryptedDataSize modulo EncryptionBlockSize to get a whole
  522. * number of blocks to encrypt later. Also reserve one byte for
  523. * padding (1 <= paddingSize <= encryptionBlockSize). */
  524. size_t maxEncryptDataSize = mc->messageBuffer.length -
  525. UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH -
  526. UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH;
  527. mc->buf_end -= (maxEncryptDataSize % encryptionBlockSize) + 1;
  528. }
  529. }
  530. static UA_StatusCode
  531. checkLimitsSym(UA_MessageContext *const messageContext, size_t *const bodyLength) {
  532. /* Will this chunk surpass the capacity of the SecureChannel for the message? */
  533. UA_Connection *const connection = messageContext->channel->connection;
  534. if(!connection)
  535. return UA_STATUSCODE_BADINTERNALERROR;
  536. UA_Byte *buf_body_start = messageContext->messageBuffer.data + UA_SECURE_MESSAGE_HEADER_LENGTH;
  537. const UA_Byte *buf_body_end = messageContext->buf_pos;
  538. *bodyLength = (uintptr_t)buf_body_end - (uintptr_t)buf_body_start;
  539. messageContext->messageSizeSoFar += *bodyLength;
  540. messageContext->chunksSoFar++;
  541. if(messageContext->messageSizeSoFar > connection->config.maxMessageSize &&
  542. connection->config.maxMessageSize != 0)
  543. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  544. if(messageContext->chunksSoFar > connection->config.maxChunkCount &&
  545. connection->config.maxChunkCount != 0)
  546. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  547. return UA_STATUSCODE_GOOD;
  548. }
  549. static UA_StatusCode
  550. padChunkSym(UA_MessageContext *messageContext, size_t bodyLength) {
  551. /* The bytes for the padding and signature were removed
  552. * from buf_end before encoding the payload. So we don't check here. */
  553. if(messageContext->channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  554. size_t bytesToWrite = bodyLength + UA_SEQUENCE_HEADER_LENGTH;
  555. UA_Byte paddingSize = 0;
  556. UA_Byte extraPaddingSize = 0;
  557. UA_UInt16 totalPaddingSize =
  558. calculatePaddingSym(messageContext->channel->securityPolicy,
  559. messageContext->channel->channelContext,
  560. bytesToWrite, &paddingSize, &extraPaddingSize);
  561. // This is <= because the paddingSize byte also has to be written.
  562. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  563. *messageContext->buf_pos = paddingSize;
  564. ++(messageContext->buf_pos);
  565. }
  566. if(extraPaddingSize > 0) {
  567. *messageContext->buf_pos = extraPaddingSize;
  568. ++(messageContext->buf_pos);
  569. }
  570. }
  571. return UA_STATUSCODE_GOOD;
  572. }
  573. static UA_StatusCode
  574. encodeHeadersSym(UA_MessageContext *const messageContext, size_t totalLength) {
  575. UA_StatusCode res = UA_STATUSCODE_GOOD;
  576. UA_SecureChannel *const channel = messageContext->channel;
  577. UA_Byte *header_pos = messageContext->messageBuffer.data;
  578. UA_SecureConversationMessageHeader respHeader;
  579. respHeader.secureChannelId = channel->securityToken.channelId;
  580. respHeader.messageHeader.messageTypeAndChunkType = messageContext->messageType;
  581. respHeader.messageHeader.messageSize = (UA_UInt32)totalLength;
  582. if(messageContext->final)
  583. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  584. else
  585. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  586. res = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  587. &header_pos, &messageContext->buf_end, NULL, NULL);
  588. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  589. symSecHeader.tokenId = channel->securityToken.tokenId;
  590. res |= UA_encodeBinary(&symSecHeader.tokenId,
  591. &UA_TRANSPORT[UA_TRANSPORT_SYMMETRICALGORITHMSECURITYHEADER],
  592. &header_pos, &messageContext->buf_end, NULL, NULL);
  593. UA_SequenceHeader seqHeader;
  594. seqHeader.requestId = messageContext->requestId;
  595. seqHeader.sequenceNumber = UA_atomic_addUInt32(&channel->sendSequenceNumber, 1);
  596. res |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  597. &header_pos, &messageContext->buf_end, NULL, NULL);
  598. return res;
  599. }
  600. static UA_StatusCode
  601. signChunkSym(UA_MessageContext *const messageContext, size_t preSigLength) {
  602. UA_SecureChannel *const channel = messageContext->channel;
  603. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  604. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  605. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  606. UA_ByteString dataToSign = messageContext->messageBuffer;
  607. dataToSign.length = preSigLength;
  608. UA_ByteString signature;
  609. signature.length = securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  610. getLocalSignatureSize(securityPolicy, channel->channelContext);
  611. signature.data = messageContext->buf_pos;
  612. return securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm
  613. .sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  614. }
  615. return UA_STATUSCODE_GOOD;
  616. }
  617. static UA_StatusCode
  618. encryptChunkSym(UA_MessageContext *const messageContext, size_t totalLength) {
  619. UA_SecureChannel *const channel = messageContext->channel;
  620. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  621. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  622. UA_ByteString dataToEncrypt;
  623. dataToEncrypt.data = messageContext->messageBuffer.data + UA_SECUREMH_AND_SYMALGH_LENGTH;
  624. dataToEncrypt.length = totalLength - UA_SECUREMH_AND_SYMALGH_LENGTH;
  625. return securityPolicy->symmetricModule.cryptoModule.encryptionAlgorithm.
  626. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  627. }
  628. return UA_STATUSCODE_GOOD;
  629. }
  630. static UA_StatusCode
  631. sendSymmetricChunk(UA_MessageContext *messageContext) {
  632. UA_StatusCode res = UA_STATUSCODE_GOOD;
  633. UA_SecureChannel *const channel = messageContext->channel;
  634. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  635. UA_Connection *const connection = channel->connection;
  636. if(!connection)
  637. return UA_STATUSCODE_BADINTERNALERROR;
  638. size_t bodyLength = 0;
  639. res = checkLimitsSym(messageContext, &bodyLength);
  640. if(res != UA_STATUSCODE_GOOD)
  641. goto error;
  642. res = padChunkSym(messageContext, bodyLength);
  643. if(res != UA_STATUSCODE_GOOD)
  644. goto error;
  645. /* The total message length */
  646. size_t pre_sig_length = (uintptr_t)(messageContext->buf_pos) -
  647. (uintptr_t)messageContext->messageBuffer.data;
  648. size_t total_length = pre_sig_length;
  649. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  650. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  651. total_length += securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  652. getLocalSignatureSize(securityPolicy, channel->channelContext);
  653. /* Space for the padding and the signature have been reserved in setBufPos() */
  654. UA_assert(total_length <= connection->config.sendBufferSize);
  655. /* For giving the buffer to the network layer */
  656. messageContext->messageBuffer.length = total_length;
  657. UA_assert(res == UA_STATUSCODE_GOOD);
  658. res = encodeHeadersSym(messageContext, total_length);
  659. if(res != UA_STATUSCODE_GOOD)
  660. goto error;
  661. res = signChunkSym(messageContext, pre_sig_length);
  662. if(res != UA_STATUSCODE_GOOD)
  663. goto error;
  664. res = encryptChunkSym(messageContext, total_length);
  665. if(res != UA_STATUSCODE_GOOD)
  666. goto error;
  667. /* Send the chunk, the buffer is freed in the network layer */
  668. return connection->send(channel->connection, &messageContext->messageBuffer);
  669. error:
  670. connection->releaseSendBuffer(channel->connection, &messageContext->messageBuffer);
  671. return res;
  672. }
  673. /* Callback from the encoding layer. Send the chunk and replace the buffer. */
  674. static UA_StatusCode
  675. sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
  676. /* Set buf values from encoding in the messagecontext */
  677. UA_MessageContext *mc = (UA_MessageContext *)data;
  678. mc->buf_pos = *buf_pos;
  679. mc->buf_end = *buf_end;
  680. /* Send out */
  681. UA_StatusCode retval = sendSymmetricChunk(mc);
  682. if(retval != UA_STATUSCODE_GOOD)
  683. return retval;
  684. /* Set a new buffer for the next chunk */
  685. UA_Connection *connection = mc->channel->connection;
  686. if(!connection)
  687. return UA_STATUSCODE_BADINTERNALERROR;
  688. retval = connection->getSendBuffer(connection, connection->config.sendBufferSize,
  689. &mc->messageBuffer);
  690. if(retval != UA_STATUSCODE_GOOD)
  691. return retval;
  692. /* Hide bytes for header, padding and signature */
  693. setBufPos(mc);
  694. *buf_pos = mc->buf_pos;
  695. *buf_end = mc->buf_end;
  696. return UA_STATUSCODE_GOOD;
  697. }
  698. UA_StatusCode
  699. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  700. UA_UInt32 requestId, UA_MessageType messageType) {
  701. UA_Connection *connection = channel->connection;
  702. if(!connection)
  703. return UA_STATUSCODE_BADINTERNALERROR;
  704. if(messageType != UA_MESSAGETYPE_MSG && messageType != UA_MESSAGETYPE_CLO)
  705. return UA_STATUSCODE_BADINTERNALERROR;
  706. /* Create the chunking info structure */
  707. mc->channel = channel;
  708. mc->requestId = requestId;
  709. mc->chunksSoFar = 0;
  710. mc->messageSizeSoFar = 0;
  711. mc->final = false;
  712. mc->messageBuffer = UA_BYTESTRING_NULL;
  713. mc->messageType = messageType;
  714. /* Allocate the message buffer */
  715. UA_StatusCode retval =
  716. connection->getSendBuffer(connection, connection->config.sendBufferSize,
  717. &mc->messageBuffer);
  718. if(retval != UA_STATUSCODE_GOOD)
  719. return retval;
  720. /* Hide bytes for header, padding and signature */
  721. setBufPos(mc);
  722. return UA_STATUSCODE_GOOD;
  723. }
  724. UA_StatusCode
  725. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  726. const UA_DataType *contentType) {
  727. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  728. sendSymmetricEncodingCallback, mc);
  729. if(retval != UA_STATUSCODE_GOOD) {
  730. /* TODO: Send the abort message */
  731. if(mc->messageBuffer.length > 0) {
  732. UA_Connection *connection = mc->channel->connection;
  733. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  734. }
  735. }
  736. return retval;
  737. }
  738. UA_StatusCode
  739. UA_MessageContext_finish(UA_MessageContext *mc) {
  740. mc->final = true;
  741. return sendSymmetricChunk(mc);
  742. }
  743. void
  744. UA_MessageContext_abort(UA_MessageContext *mc) {
  745. UA_Connection *connection = mc->channel->connection;
  746. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  747. }
  748. UA_StatusCode
  749. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  750. UA_MessageType messageType, void *payload,
  751. const UA_DataType *payloadType) {
  752. if(!channel || !channel->connection || !payload || !payloadType)
  753. return UA_STATUSCODE_BADINTERNALERROR;
  754. if(channel->connection->state == UA_CONNECTION_CLOSED)
  755. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  756. UA_MessageContext mc;
  757. UA_StatusCode retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
  758. if(retval != UA_STATUSCODE_GOOD)
  759. return retval;
  760. /* Assert's required for clang-analyzer */
  761. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  762. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  763. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  764. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  765. if(retval != UA_STATUSCODE_GOOD)
  766. return retval;
  767. retval = UA_MessageContext_encode(&mc, payload, payloadType);
  768. if(retval != UA_STATUSCODE_GOOD)
  769. return retval;
  770. return UA_MessageContext_finish(&mc);
  771. }
  772. /*****************************/
  773. /* Assemble Complete Message */
  774. /*****************************/
  775. static UA_StatusCode
  776. addChunkPayload(UA_SecureChannel *channel, UA_UInt32 requestId,
  777. UA_MessageType messageType, UA_ByteString *chunkPayload,
  778. UA_Boolean final) {
  779. UA_Message *latest = TAILQ_LAST(&channel->messages, UA_MessageQueue);
  780. if(latest) {
  781. if(latest->requestId != requestId) {
  782. /* Start of a new message */
  783. if(!latest->final)
  784. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  785. latest = NULL;
  786. } else {
  787. if(latest->messageType != messageType) /* MessageType mismatch */
  788. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  789. if(latest->final) /* Correct message, but already finalized */
  790. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  791. }
  792. }
  793. /* Create a new message entry */
  794. if(!latest) {
  795. latest = (UA_Message *)UA_malloc(sizeof(UA_Message));
  796. if(!latest)
  797. return UA_STATUSCODE_BADOUTOFMEMORY;
  798. memset(latest, 0, sizeof(UA_Message));
  799. latest->requestId = requestId;
  800. latest->messageType = messageType;
  801. SIMPLEQ_INIT(&latest->chunkPayloads);
  802. TAILQ_INSERT_TAIL(&channel->messages, latest, pointers);
  803. }
  804. /* Test against the connection settings */
  805. const UA_ConnectionConfig *config = &channel->connection->config;
  806. UA_assert(config != NULL); /* clang-analyzer false positive */
  807. if(config->maxChunkCount > 0 &&
  808. config->maxChunkCount <= latest->chunkPayloadsSize)
  809. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  810. if(config->maxMessageSize > 0 &&
  811. config->maxMessageSize < latest->messageSize + chunkPayload->length)
  812. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  813. /* Create a new chunk entry */
  814. UA_ChunkPayload *cp = (UA_ChunkPayload *)UA_malloc(sizeof(UA_ChunkPayload));
  815. if(!cp)
  816. return UA_STATUSCODE_BADOUTOFMEMORY;
  817. cp->bytes = *chunkPayload;
  818. cp->copied = false;
  819. /* Add the chunk */
  820. SIMPLEQ_INSERT_TAIL(&latest->chunkPayloads, cp, pointers);
  821. latest->chunkPayloadsSize += 1;
  822. latest->messageSize += chunkPayload->length;
  823. latest->final = final;
  824. return UA_STATUSCODE_GOOD;
  825. }
  826. static UA_StatusCode
  827. processMessage(UA_SecureChannel *channel, const UA_Message *message,
  828. void *application, UA_ProcessMessageCallback callback) {
  829. if(message->chunkPayloadsSize == 1) {
  830. /* No need to combine chunks */
  831. UA_ChunkPayload *cp = SIMPLEQ_FIRST(&message->chunkPayloads);
  832. callback(application, channel, message->messageType, message->requestId, &cp->bytes);
  833. } else {
  834. /* Allocate memory */
  835. UA_ByteString bytes;
  836. bytes.data = (UA_Byte *)UA_malloc(message->messageSize);
  837. if(!bytes.data) {
  838. UA_LOG_ERROR(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURECHANNEL,
  839. "Could not allocate the memory to assemble the message");
  840. return UA_STATUSCODE_BADOUTOFMEMORY;
  841. }
  842. bytes.length = message->messageSize;
  843. /* Assemble the full message */
  844. size_t curPos = 0;
  845. UA_ChunkPayload *cp;
  846. SIMPLEQ_FOREACH(cp, &message->chunkPayloads, pointers) {
  847. memcpy(&bytes.data[curPos], cp->bytes.data, cp->bytes.length);
  848. curPos += cp->bytes.length;
  849. }
  850. /* Process the message */
  851. callback(application, channel, message->messageType, message->requestId, &bytes);
  852. UA_ByteString_deleteMembers(&bytes);
  853. }
  854. return UA_STATUSCODE_GOOD;
  855. }
  856. UA_StatusCode
  857. UA_SecureChannel_processCompleteMessages(UA_SecureChannel *channel, void *application,
  858. UA_ProcessMessageCallback callback) {
  859. UA_Message *message, *tmp_message;
  860. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  861. TAILQ_FOREACH_SAFE(message, &channel->messages, pointers, tmp_message) {
  862. /* Stop at the first incomplete message */
  863. if(!message->final)
  864. break;
  865. /* Has the channel been closed (during the last message)? */
  866. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  867. break;
  868. /* Remove the current message before processing */
  869. TAILQ_REMOVE(&channel->messages, message, pointers);
  870. /* Process */
  871. retval = processMessage(channel, message, application, callback);
  872. if(retval != UA_STATUSCODE_GOOD)
  873. break;
  874. /* Clean up the message */
  875. UA_ChunkPayload *payload;
  876. while((payload = SIMPLEQ_FIRST(&message->chunkPayloads))) {
  877. if(payload->copied)
  878. UA_ByteString_deleteMembers(&payload->bytes);
  879. SIMPLEQ_REMOVE_HEAD(&message->chunkPayloads, pointers);
  880. UA_free(payload);
  881. }
  882. UA_free(message);
  883. }
  884. return retval;
  885. }
  886. /****************************/
  887. /* Process a received Chunk */
  888. /****************************/
  889. static UA_StatusCode
  890. decryptChunk(const UA_SecureChannel *const channel,
  891. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  892. UA_MessageType const messageType, const UA_ByteString *const chunk,
  893. size_t const offset, size_t *const chunkSizeAfterDecryption) {
  894. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Decrypting chunk");
  895. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  896. size_t sizeBeforeDecryption = cipherText.length;
  897. size_t chunkSizeBeforeDecryption = *chunkSizeAfterDecryption;
  898. /* Always decrypt opn messages if mode not none */
  899. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  900. messageType == UA_MESSAGETYPE_OPN) {
  901. UA_StatusCode retval = cryptoModule->encryptionAlgorithm.
  902. decrypt(channel->securityPolicy, channel->channelContext, &cipherText);
  903. *chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  904. if(retval != UA_STATUSCODE_GOOD) {
  905. return retval;
  906. }
  907. }
  908. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  909. "Chunk size before and after decryption: %lu, %lu",
  910. (long unsigned int)chunkSizeBeforeDecryption,
  911. (long unsigned int)*chunkSizeAfterDecryption);
  912. return UA_STATUSCODE_GOOD;
  913. }
  914. static UA_StatusCode
  915. getPaddingSize(const UA_SecureChannel *const channel,
  916. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  917. UA_MessageType const messageType, const UA_ByteString *const chunk,
  918. size_t const chunkSizeAfterDecryption, size_t sigsize, size_t *const paddingSize) {
  919. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  920. (messageType == UA_MESSAGETYPE_OPN &&
  921. channel->securityMode > UA_MESSAGESECURITYMODE_NONE)) {
  922. *paddingSize = (size_t)chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  923. size_t keyLength = cryptoModule->encryptionAlgorithm.
  924. getRemoteKeyLength(channel->securityPolicy, channel->channelContext);
  925. if(keyLength > 2048) {
  926. *paddingSize <<= 8; /* Extra padding size */
  927. *paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  928. /* see comment below but for extraPaddingSize */
  929. *paddingSize += 1;
  930. }
  931. /* We need to add one to the padding size since the paddingSize byte
  932. * itself need to be removed as well. */
  933. // TODO: write unit test for correct padding calculation
  934. *paddingSize += 1;
  935. }
  936. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  937. "Calculated padding size to be %lu",
  938. (long unsigned int)*paddingSize);
  939. return UA_STATUSCODE_GOOD;
  940. }
  941. static UA_StatusCode
  942. verifyChunk(const UA_SecureChannel *const channel,
  943. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  944. const UA_ByteString *const chunk,
  945. size_t const chunkSizeAfterDecryption, size_t sigsize) {
  946. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Verifying chunk signature");
  947. /* Verify the signature */
  948. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  949. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  950. UA_StatusCode retval = cryptoModule->signatureAlgorithm.
  951. verify(channel->securityPolicy, channel->channelContext, &chunkDataToVerify, &signature);
  952. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  953. retval |= decrypt_verifySignatureFailure;
  954. #endif
  955. return retval;
  956. }
  957. /* Sets the payload to a pointer inside the chunk buffer. Returns the requestId
  958. * and the sequenceNumber */
  959. static UA_StatusCode
  960. decryptAndVerifyChunk(const UA_SecureChannel *channel,
  961. const UA_SecurityPolicyCryptoModule *cryptoModule,
  962. UA_MessageType messageType, const UA_ByteString *chunk,
  963. size_t offset, UA_UInt32 *requestId,
  964. UA_UInt32 *sequenceNumber, UA_ByteString *payload) {
  965. size_t chunkSizeAfterDecryption = chunk->length;
  966. UA_StatusCode retval = decryptChunk(channel, cryptoModule, messageType,
  967. chunk, offset, &chunkSizeAfterDecryption);
  968. if(retval != UA_STATUSCODE_GOOD)
  969. return retval;
  970. /* Verify the chunk signature */
  971. size_t sigsize = 0;
  972. size_t paddingSize = 0;
  973. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  974. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  975. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  976. messageType == UA_MESSAGETYPE_OPN) {
  977. sigsize = cryptoModule->signatureAlgorithm.
  978. getRemoteSignatureSize(securityPolicy, channel->channelContext);
  979. retval = getPaddingSize(channel, cryptoModule, messageType, chunk,
  980. chunkSizeAfterDecryption, sigsize, &paddingSize);
  981. if(retval != UA_STATUSCODE_GOOD)
  982. return retval;
  983. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  984. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  985. retval = verifyChunk(channel, cryptoModule, chunk, chunkSizeAfterDecryption, sigsize);
  986. if(retval != UA_STATUSCODE_GOOD)
  987. return retval;
  988. }
  989. /* Decode the sequence header */
  990. UA_SequenceHeader sequenceHeader;
  991. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  992. if(retval != UA_STATUSCODE_GOOD)
  993. return retval;
  994. if(offset + paddingSize + sigsize >= chunk->length)
  995. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  996. *requestId = sequenceHeader.requestId;
  997. *sequenceNumber = sequenceHeader.sequenceNumber;
  998. payload->data = chunk->data + offset;
  999. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  1000. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1001. "Decrypted and verified chunk with request id %u and "
  1002. "sequence number %u", *requestId, *sequenceNumber);
  1003. return UA_STATUSCODE_GOOD;
  1004. }
  1005. typedef UA_StatusCode
  1006. (*UA_SequenceNumberCallback)(UA_SecureChannel *channel, UA_UInt32 sequenceNumber);
  1007. static UA_StatusCode
  1008. processSequenceNumberAsym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  1009. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1010. "Sequence Number processed: %i", sequenceNumber);
  1011. channel->receiveSequenceNumber = sequenceNumber;
  1012. return UA_STATUSCODE_GOOD;
  1013. }
  1014. static UA_StatusCode
  1015. processSequenceNumberSym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  1016. /* Failure mode hook for unit tests */
  1017. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  1018. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  1019. return processSym_seqNumberFailure;
  1020. #endif
  1021. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1022. "Sequence Number processed: %i", sequenceNumber);
  1023. /* Does the sequence number match? */
  1024. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  1025. /* FIXME: Remove magic numbers :( */
  1026. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  1027. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  1028. else
  1029. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  1030. }
  1031. ++channel->receiveSequenceNumber;
  1032. return UA_STATUSCODE_GOOD;
  1033. }
  1034. static UA_StatusCode
  1035. checkAsymHeader(UA_SecureChannel *const channel,
  1036. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  1037. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1038. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  1039. if(!UA_ByteString_equal(&securityPolicy->policyUri,
  1040. &asymHeader->securityPolicyUri)) {
  1041. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  1042. }
  1043. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  1044. /* Something like this
  1045. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  1046. if(retval != UA_STATUSCODE_GOOD)
  1047. return retval;
  1048. */
  1049. retval = securityPolicy->asymmetricModule.
  1050. compareCertificateThumbprint(securityPolicy,
  1051. &asymHeader->receiverCertificateThumbprint);
  1052. if(retval != UA_STATUSCODE_GOOD) {
  1053. return retval;
  1054. }
  1055. return UA_STATUSCODE_GOOD;
  1056. }
  1057. static UA_StatusCode
  1058. checkPreviousToken(UA_SecureChannel *const channel, const UA_UInt32 tokenId) {
  1059. if(tokenId != channel->previousSecurityToken.tokenId)
  1060. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1061. UA_DateTime timeout = channel->previousSecurityToken.createdAt +
  1062. (UA_DateTime)((UA_Double)channel->previousSecurityToken.revisedLifetime *
  1063. (UA_Double)UA_DATETIME_MSEC * 1.25);
  1064. if(timeout < UA_DateTime_nowMonotonic())
  1065. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1066. return UA_STATUSCODE_GOOD;
  1067. }
  1068. static UA_StatusCode
  1069. checkSymHeader(UA_SecureChannel *const channel,
  1070. const UA_UInt32 tokenId, UA_Boolean allowPreviousToken) {
  1071. if(tokenId == channel->securityToken.tokenId) {
  1072. if(channel->state == UA_SECURECHANNELSTATE_OPEN &&
  1073. (channel->securityToken.createdAt +
  1074. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  1075. < UA_DateTime_nowMonotonic()) {
  1076. UA_SecureChannel_close(channel);
  1077. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1078. }
  1079. }
  1080. if(tokenId != channel->securityToken.tokenId) {
  1081. if(tokenId != channel->nextSecurityToken.tokenId) {
  1082. if(allowPreviousToken)
  1083. return checkPreviousToken(channel, tokenId);
  1084. else
  1085. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1086. }
  1087. return UA_SecureChannel_revolveTokens(channel);
  1088. }
  1089. if(channel->previousSecurityToken.tokenId != 0) {
  1090. UA_StatusCode retval =
  1091. UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  1092. UA_ChannelSecurityToken_deleteMembers(&channel->previousSecurityToken);
  1093. return retval;
  1094. }
  1095. return UA_STATUSCODE_GOOD;
  1096. }
  1097. static UA_StatusCode
  1098. putPayload(UA_SecureChannel *const channel, UA_UInt32 const requestId,
  1099. UA_MessageType const messageType, UA_ChunkType const chunkType,
  1100. UA_ByteString *chunkPayload) {
  1101. switch(chunkType) {
  1102. case UA_CHUNKTYPE_INTERMEDIATE:
  1103. case UA_CHUNKTYPE_FINAL:
  1104. return addChunkPayload(channel, requestId, messageType,
  1105. chunkPayload, chunkType == UA_CHUNKTYPE_FINAL);
  1106. case UA_CHUNKTYPE_ABORT:
  1107. deleteLatestMessage(channel, requestId);
  1108. return UA_STATUSCODE_GOOD;
  1109. default:
  1110. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1111. }
  1112. }
  1113. /* The chunk body begins after the SecureConversationMessageHeader */
  1114. static UA_StatusCode
  1115. decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk,
  1116. UA_Boolean allowPreviousToken) {
  1117. /* Decode the MessageHeader */
  1118. size_t offset = 0;
  1119. UA_SecureConversationMessageHeader messageHeader;
  1120. UA_StatusCode retval =
  1121. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  1122. if(retval != UA_STATUSCODE_GOOD)
  1123. return retval;
  1124. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1125. /* The wrong ChannelId. Non-opened channels have the id zero. */
  1126. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  1127. channel->state != UA_SECURECHANNELSTATE_FRESH)
  1128. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  1129. #endif
  1130. UA_MessageType messageType = (UA_MessageType)
  1131. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  1132. UA_ChunkType chunkType = (UA_ChunkType)
  1133. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  1134. UA_UInt32 requestId = 0;
  1135. UA_UInt32 sequenceNumber = 0;
  1136. UA_ByteString chunkPayload;
  1137. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  1138. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  1139. switch(messageType) {
  1140. /* ERR message (not encrypted) */
  1141. case UA_MESSAGETYPE_ERR:
  1142. if(chunkType != UA_CHUNKTYPE_FINAL)
  1143. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1144. chunkPayload.length = chunk->length - offset;
  1145. chunkPayload.data = chunk->data + offset;
  1146. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1147. /* MSG and CLO: Symmetric encryption */
  1148. case UA_MESSAGETYPE_MSG:
  1149. case UA_MESSAGETYPE_CLO: {
  1150. /* Decode and check the symmetric security header (tokenId) */
  1151. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  1152. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  1153. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  1154. &symmetricSecurityHeader);
  1155. if(retval != UA_STATUSCODE_GOOD)
  1156. return retval;
  1157. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1158. /* Help fuzzing by always setting the correct tokenId */
  1159. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  1160. #endif
  1161. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId, allowPreviousToken);
  1162. if(retval != UA_STATUSCODE_GOOD)
  1163. return retval;
  1164. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  1165. sequenceNumberCallback = processSequenceNumberSym;
  1166. break;
  1167. }
  1168. /* OPN: Asymmetric encryption */
  1169. case UA_MESSAGETYPE_OPN: {
  1170. /* Chunking not allowed for OPN */
  1171. if(chunkType != UA_CHUNKTYPE_FINAL)
  1172. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1173. /* Decode the asymmetric algorithm security header and call the callback
  1174. * to perform checks. */
  1175. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  1176. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  1177. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  1178. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  1179. if(retval != UA_STATUSCODE_GOOD)
  1180. return retval;
  1181. retval = checkAsymHeader(channel, &asymHeader);
  1182. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  1183. if(retval != UA_STATUSCODE_GOOD)
  1184. return retval;
  1185. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  1186. sequenceNumberCallback = processSequenceNumberAsym;
  1187. break;
  1188. }
  1189. /* Invalid message type */
  1190. default:return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1191. }
  1192. UA_assert(cryptoModule != NULL);
  1193. retval = decryptAndVerifyChunk(channel, cryptoModule, messageType, chunk, offset,
  1194. &requestId, &sequenceNumber, &chunkPayload);
  1195. if(retval != UA_STATUSCODE_GOOD)
  1196. return retval;
  1197. /* Check the sequence number. Skip sequence number checking for fuzzer to
  1198. * improve coverage */
  1199. if(sequenceNumberCallback == NULL)
  1200. return UA_STATUSCODE_BADINTERNALERROR;
  1201. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1202. retval = UA_STATUSCODE_GOOD;
  1203. #else
  1204. retval = sequenceNumberCallback(channel, sequenceNumber);
  1205. #endif
  1206. if(retval != UA_STATUSCODE_GOOD)
  1207. return retval;
  1208. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1209. }
  1210. UA_StatusCode
  1211. UA_SecureChannel_decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk,
  1212. UA_Boolean allowPreviousToken) {
  1213. /* Has the SecureChannel timed out? */
  1214. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  1215. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1216. /* Is the SecureChannel configured? */
  1217. if(!channel->connection)
  1218. return UA_STATUSCODE_BADINTERNALERROR;
  1219. UA_StatusCode retval = decryptAddChunk(channel, chunk, allowPreviousToken);
  1220. if(retval != UA_STATUSCODE_GOOD)
  1221. UA_SecureChannel_close(channel);
  1222. return retval;
  1223. }
  1224. UA_StatusCode
  1225. UA_SecureChannel_persistIncompleteMessages(UA_SecureChannel *channel) {
  1226. UA_Message *me;
  1227. TAILQ_FOREACH(me, &channel->messages, pointers) {
  1228. UA_ChunkPayload *cp;
  1229. SIMPLEQ_FOREACH(cp, &me->chunkPayloads, pointers) {
  1230. if(cp->copied)
  1231. continue;
  1232. UA_ByteString copy;
  1233. UA_StatusCode retval = UA_ByteString_copy(&cp->bytes, &copy);
  1234. if(retval != UA_STATUSCODE_GOOD) {
  1235. UA_SecureChannel_close(channel);
  1236. return retval;
  1237. }
  1238. cp->bytes = copy;
  1239. cp->copied = true;
  1240. }
  1241. }
  1242. return UA_STATUSCODE_GOOD;
  1243. }
  1244. /* Functionality used by both the SecureChannel and the SecurityPolicy */
  1245. size_t
  1246. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(const UA_SecurityPolicy *securityPolicy,
  1247. const void *channelContext,
  1248. size_t maxEncryptionLength) {
  1249. if(maxEncryptionLength == 0)
  1250. return 0;
  1251. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.
  1252. encryptionAlgorithm.getRemotePlainTextBlockSize(securityPolicy, channelContext);
  1253. size_t encryptedBlockSize = securityPolicy->asymmetricModule.cryptoModule.
  1254. encryptionAlgorithm.getRemoteBlockSize(securityPolicy, channelContext);
  1255. if(plainTextBlockSize == 0)
  1256. return 0;
  1257. size_t maxNumberOfBlocks = maxEncryptionLength / plainTextBlockSize;
  1258. return maxNumberOfBlocks * (encryptedBlockSize - plainTextBlockSize);
  1259. }