ua_securechannel.c 59 KB

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