ua_securechannel.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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 = 0;
  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. /* Reserve space for the message footer at the end of the chunk if the chunk
  496. * is signed and/or encrypted. The footer includes the fields PaddingSize,
  497. * Padding, ExtraPadding and Signature. The padding fields are only present
  498. * if the chunk is encrypted. */
  499. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  500. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  501. mc->buf_end -= securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  502. getLocalSignatureSize(securityPolicy, channel->channelContext);
  503. /* The size of the padding depends on the amount of data that shall be sent
  504. * and is unknown at this point. Reserve space for the PaddingSize byte,
  505. * the maximum amount of Padding which equals the block size of the
  506. * symmetric encryption algorithm and last 1 byte for the ExtraPaddingSize
  507. * field that is present if the encryption key is larger than 2048 bits.
  508. * The actual padding size is later calculated by the function
  509. * calculatePaddingSym(). */
  510. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  511. {
  512. /* PaddingSize and ExtraPaddingSize fields */
  513. size_t encryptionBlockSize = securityPolicy->symmetricModule.cryptoModule.encryptionAlgorithm.
  514. getLocalBlockSize(securityPolicy, channel->channelContext );
  515. mc->buf_end -= 1 + ((encryptionBlockSize >> 8) ? 1 : 0);
  516. /* Reduce the message body size with the remainder of the operation
  517. * maxEncryptedDataSize modulo EncryptionBlockSize to get a whole
  518. * number of blocks to encrypt later. Also reserve one byte for
  519. * padding (1 <= paddingSize <= encryptionBlockSize).
  520. */
  521. size_t maxEncryptDataSize = mc->messageBuffer.length-UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH-UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH;
  522. mc->buf_end -= (maxEncryptDataSize % encryptionBlockSize) + 1;
  523. }
  524. }
  525. static UA_StatusCode
  526. checkLimitsSym(UA_MessageContext *const messageContext, size_t *const bodyLength) {
  527. /* Will this chunk surpass the capacity of the SecureChannel for the message? */
  528. UA_Connection *const connection = messageContext->channel->connection;
  529. if(!connection)
  530. return UA_STATUSCODE_BADINTERNALERROR;
  531. UA_Byte *buf_body_start = messageContext->messageBuffer.data + UA_SECURE_MESSAGE_HEADER_LENGTH;
  532. const UA_Byte *buf_body_end = messageContext->buf_pos;
  533. *bodyLength = (uintptr_t)buf_body_end - (uintptr_t)buf_body_start;
  534. messageContext->messageSizeSoFar += *bodyLength;
  535. messageContext->chunksSoFar++;
  536. if(messageContext->messageSizeSoFar > connection->config.maxMessageSize &&
  537. connection->config.maxMessageSize != 0)
  538. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  539. if(messageContext->chunksSoFar > connection->config.maxChunkCount &&
  540. connection->config.maxChunkCount != 0)
  541. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  542. return UA_STATUSCODE_GOOD;
  543. }
  544. static UA_StatusCode
  545. padChunkSym(UA_MessageContext *messageContext, size_t bodyLength) {
  546. /* The bytes for the padding and signature were removed
  547. * from buf_end before encoding the payload. So we don't check here. */
  548. if(messageContext->channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  549. size_t bytesToWrite = bodyLength + UA_SEQUENCE_HEADER_LENGTH;
  550. UA_Byte paddingSize = 0;
  551. UA_Byte extraPaddingSize = 0;
  552. UA_UInt16 totalPaddingSize =
  553. calculatePaddingSym(messageContext->channel->securityPolicy,
  554. messageContext->channel->channelContext,
  555. bytesToWrite, &paddingSize, &extraPaddingSize);
  556. // This is <= because the paddingSize byte also has to be written.
  557. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  558. *messageContext->buf_pos = paddingSize;
  559. ++(messageContext->buf_pos);
  560. }
  561. if(extraPaddingSize > 0) {
  562. *messageContext->buf_pos = extraPaddingSize;
  563. ++(messageContext->buf_pos);
  564. }
  565. }
  566. return UA_STATUSCODE_GOOD;
  567. }
  568. static UA_StatusCode
  569. encodeHeadersSym(UA_MessageContext *const messageContext, size_t totalLength) {
  570. UA_StatusCode res = UA_STATUSCODE_GOOD;
  571. UA_SecureChannel *const channel = messageContext->channel;
  572. UA_Byte *header_pos = messageContext->messageBuffer.data;
  573. UA_SecureConversationMessageHeader respHeader;
  574. respHeader.secureChannelId = channel->securityToken.channelId;
  575. respHeader.messageHeader.messageTypeAndChunkType = messageContext->messageType;
  576. respHeader.messageHeader.messageSize = (UA_UInt32)totalLength;
  577. if(messageContext->final)
  578. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  579. else
  580. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  581. res = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  582. &header_pos, &messageContext->buf_end, NULL, NULL);
  583. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  584. symSecHeader.tokenId = channel->securityToken.tokenId;
  585. res |= UA_encodeBinary(&symSecHeader.tokenId,
  586. &UA_TRANSPORT[UA_TRANSPORT_SYMMETRICALGORITHMSECURITYHEADER],
  587. &header_pos, &messageContext->buf_end, NULL, NULL);
  588. UA_SequenceHeader seqHeader;
  589. seqHeader.requestId = messageContext->requestId;
  590. seqHeader.sequenceNumber = UA_atomic_addUInt32(&channel->sendSequenceNumber, 1);
  591. res |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  592. &header_pos, &messageContext->buf_end, NULL, NULL);
  593. return res;
  594. }
  595. static UA_StatusCode
  596. signChunkSym(UA_MessageContext *const messageContext, size_t preSigLength) {
  597. UA_SecureChannel *const channel = messageContext->channel;
  598. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  599. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  600. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  601. UA_ByteString dataToSign = messageContext->messageBuffer;
  602. dataToSign.length = preSigLength;
  603. UA_ByteString signature;
  604. signature.length = securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  605. getLocalSignatureSize(securityPolicy, channel->channelContext);
  606. signature.data = messageContext->buf_pos;
  607. return securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm
  608. .sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  609. }
  610. return UA_STATUSCODE_GOOD;
  611. }
  612. static UA_StatusCode
  613. encryptChunkSym(UA_MessageContext *const messageContext, size_t totalLength) {
  614. UA_SecureChannel *const channel = messageContext->channel;
  615. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  616. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  617. UA_ByteString dataToEncrypt;
  618. dataToEncrypt.data = messageContext->messageBuffer.data + UA_SECUREMH_AND_SYMALGH_LENGTH;
  619. dataToEncrypt.length = totalLength - UA_SECUREMH_AND_SYMALGH_LENGTH;
  620. return securityPolicy->symmetricModule.cryptoModule.encryptionAlgorithm.
  621. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  622. }
  623. return UA_STATUSCODE_GOOD;
  624. }
  625. static UA_StatusCode
  626. sendSymmetricChunk(UA_MessageContext *messageContext) {
  627. UA_StatusCode res = UA_STATUSCODE_GOOD;
  628. UA_SecureChannel *const channel = messageContext->channel;
  629. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  630. UA_Connection *const connection = channel->connection;
  631. if(!connection)
  632. return UA_STATUSCODE_BADINTERNALERROR;
  633. size_t bodyLength = 0;
  634. res = checkLimitsSym(messageContext, &bodyLength);
  635. if(res != UA_STATUSCODE_GOOD)
  636. goto error;
  637. res = padChunkSym(messageContext, bodyLength);
  638. if(res != UA_STATUSCODE_GOOD)
  639. goto error;
  640. /* The total message length */
  641. size_t pre_sig_length = (uintptr_t)(messageContext->buf_pos) - (uintptr_t)messageContext->messageBuffer.data;
  642. size_t total_length = pre_sig_length;
  643. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  644. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  645. total_length += securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  646. getLocalSignatureSize(securityPolicy, channel->channelContext);
  647. /* Space for the padding and the signature have been reserved in setBufPos() */
  648. UA_assert(total_length<=connection->config.sendBufferSize);
  649. messageContext->messageBuffer.length = total_length; /* For giving the buffer to the network layer */
  650. UA_assert(res == UA_STATUSCODE_GOOD);
  651. res = encodeHeadersSym(messageContext, total_length);
  652. if(res != UA_STATUSCODE_GOOD)
  653. goto error;
  654. res = signChunkSym(messageContext, pre_sig_length);
  655. if(res != UA_STATUSCODE_GOOD)
  656. goto error;
  657. res = encryptChunkSym(messageContext, total_length);
  658. if(res != UA_STATUSCODE_GOOD)
  659. goto error;
  660. /* Send the chunk, the buffer is freed in the network layer */
  661. return connection->send(channel->connection, &messageContext->messageBuffer);
  662. error:
  663. connection->releaseSendBuffer(channel->connection, &messageContext->messageBuffer);
  664. return res;
  665. }
  666. /* Callback from the encoding layer. Send the chunk and replace the buffer. */
  667. static UA_StatusCode
  668. sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
  669. /* Set buf values from encoding in the messagecontext */
  670. UA_MessageContext *mc = (UA_MessageContext *)data;
  671. mc->buf_pos = *buf_pos;
  672. mc->buf_end = *buf_end;
  673. /* Send out */
  674. UA_StatusCode retval = sendSymmetricChunk(mc);
  675. if(retval != UA_STATUSCODE_GOOD)
  676. return retval;
  677. /* Set a new buffer for the next chunk */
  678. UA_Connection *connection = mc->channel->connection;
  679. if(!connection)
  680. return UA_STATUSCODE_BADINTERNALERROR;
  681. retval = connection->getSendBuffer(connection, connection->config.sendBufferSize,
  682. &mc->messageBuffer);
  683. if(retval != UA_STATUSCODE_GOOD)
  684. return retval;
  685. /* Hide bytes for header, padding and signature */
  686. setBufPos(mc);
  687. *buf_pos = mc->buf_pos;
  688. *buf_end = mc->buf_end;
  689. return UA_STATUSCODE_GOOD;
  690. }
  691. UA_StatusCode
  692. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  693. UA_UInt32 requestId, UA_MessageType messageType) {
  694. UA_Connection *connection = channel->connection;
  695. if(!connection)
  696. return UA_STATUSCODE_BADINTERNALERROR;
  697. if(messageType != UA_MESSAGETYPE_MSG && messageType != UA_MESSAGETYPE_CLO)
  698. return UA_STATUSCODE_BADINTERNALERROR;
  699. /* Create the chunking info structure */
  700. mc->channel = channel;
  701. mc->requestId = requestId;
  702. mc->chunksSoFar = 0;
  703. mc->messageSizeSoFar = 0;
  704. mc->final = false;
  705. mc->messageBuffer = UA_BYTESTRING_NULL;
  706. mc->messageType = messageType;
  707. /* Allocate the message buffer */
  708. UA_StatusCode retval =
  709. connection->getSendBuffer(connection, connection->config.sendBufferSize,
  710. &mc->messageBuffer);
  711. if(retval != UA_STATUSCODE_GOOD)
  712. return retval;
  713. /* Hide bytes for header, padding and signature */
  714. setBufPos(mc);
  715. return UA_STATUSCODE_GOOD;
  716. }
  717. UA_StatusCode
  718. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  719. const UA_DataType *contentType) {
  720. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  721. sendSymmetricEncodingCallback, mc);
  722. if(retval != UA_STATUSCODE_GOOD) {
  723. /* TODO: Send the abort message */
  724. if(mc->messageBuffer.length > 0) {
  725. UA_Connection *connection = mc->channel->connection;
  726. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  727. }
  728. }
  729. return retval;
  730. }
  731. UA_StatusCode
  732. UA_MessageContext_finish(UA_MessageContext *mc) {
  733. mc->final = true;
  734. return sendSymmetricChunk(mc);
  735. }
  736. void
  737. UA_MessageContext_abort(UA_MessageContext *mc) {
  738. UA_Connection *connection = mc->channel->connection;
  739. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  740. }
  741. UA_StatusCode
  742. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  743. UA_MessageType messageType, void *payload,
  744. const UA_DataType *payloadType) {
  745. if(!channel || !channel->connection || !payload || !payloadType)
  746. return UA_STATUSCODE_BADINTERNALERROR;
  747. if(channel->connection->state == UA_CONNECTION_CLOSED)
  748. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  749. UA_MessageContext mc;
  750. UA_StatusCode retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
  751. if(retval != UA_STATUSCODE_GOOD)
  752. return retval;
  753. /* Assert's required for clang-analyzer */
  754. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  755. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  756. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  757. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  758. if(retval != UA_STATUSCODE_GOOD)
  759. return retval;
  760. retval = UA_MessageContext_encode(&mc, payload, payloadType);
  761. if(retval != UA_STATUSCODE_GOOD)
  762. return retval;
  763. return UA_MessageContext_finish(&mc);
  764. }
  765. /*****************************/
  766. /* Assemble Complete Message */
  767. /*****************************/
  768. static UA_StatusCode
  769. addChunkPayload(UA_SecureChannel *channel, UA_UInt32 requestId,
  770. UA_MessageType messageType, UA_ByteString *chunkPayload,
  771. UA_Boolean final) {
  772. UA_Message *latest = TAILQ_LAST(&channel->messages, UA_MessageQueue);
  773. if(latest) {
  774. if(latest->requestId != requestId) {
  775. /* Start of a new message */
  776. if(!latest->final)
  777. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  778. latest = NULL;
  779. } else {
  780. if(latest->messageType != messageType) /* MessageType mismatch */
  781. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  782. if(latest->final) /* Correct message, but already finalized */
  783. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  784. }
  785. }
  786. /* Create a new message entry */
  787. if(!latest) {
  788. latest = (UA_Message *)UA_malloc(sizeof(UA_Message));
  789. if(!latest)
  790. return UA_STATUSCODE_BADOUTOFMEMORY;
  791. memset(latest, 0, sizeof(UA_Message));
  792. latest->requestId = requestId;
  793. latest->messageType = messageType;
  794. SIMPLEQ_INIT(&latest->chunkPayloads);
  795. TAILQ_INSERT_TAIL(&channel->messages, latest, pointers);
  796. }
  797. /* Test against the connection settings */
  798. const UA_ConnectionConfig *config = &channel->connection->config;
  799. UA_assert(config != NULL); /* clang-analyzer false positive */
  800. if(config->maxChunkCount > 0 &&
  801. config->maxChunkCount <= latest->chunkPayloadsSize)
  802. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  803. if(config->maxMessageSize > 0 && config->maxMessageSize < latest->messageSize + chunkPayload->length)
  804. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  805. /* Create a new chunk entry */
  806. UA_ChunkPayload *cp = (UA_ChunkPayload *)UA_malloc(sizeof(UA_ChunkPayload));
  807. if(!cp)
  808. return UA_STATUSCODE_BADOUTOFMEMORY;
  809. cp->bytes = *chunkPayload;
  810. cp->copied = false;
  811. /* Add the chunk */
  812. SIMPLEQ_INSERT_TAIL(&latest->chunkPayloads, cp, pointers);
  813. latest->chunkPayloadsSize += 1;
  814. latest->messageSize += chunkPayload->length;
  815. latest->final = final;
  816. return UA_STATUSCODE_GOOD;
  817. }
  818. static UA_StatusCode
  819. processMessage(UA_SecureChannel *channel, const UA_Message *message,
  820. void *application, UA_ProcessMessageCallback callback) {
  821. if(message->chunkPayloadsSize == 1) {
  822. /* No need to combine chunks */
  823. UA_ChunkPayload *cp = SIMPLEQ_FIRST(&message->chunkPayloads);
  824. callback(application, channel, message->messageType, message->requestId, &cp->bytes);
  825. } else {
  826. /* Allocate memory */
  827. UA_ByteString bytes;
  828. bytes.data = (UA_Byte *)UA_malloc(message->messageSize);
  829. if(!bytes.data) {
  830. UA_LOG_ERROR(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURECHANNEL,
  831. "Could not allocate the memory to assemble the message");
  832. return UA_STATUSCODE_BADOUTOFMEMORY;
  833. }
  834. bytes.length = message->messageSize;
  835. /* Assemble the full message */
  836. size_t curPos = 0;
  837. UA_ChunkPayload *cp;
  838. SIMPLEQ_FOREACH(cp, &message->chunkPayloads, pointers) {
  839. memcpy(&bytes.data[curPos], cp->bytes.data, cp->bytes.length);
  840. curPos += cp->bytes.length;
  841. }
  842. /* Process the message */
  843. callback(application, channel, message->messageType, message->requestId, &bytes);
  844. UA_ByteString_deleteMembers(&bytes);
  845. }
  846. return UA_STATUSCODE_GOOD;
  847. }
  848. UA_StatusCode
  849. UA_SecureChannel_processCompleteMessages(UA_SecureChannel *channel, void *application,
  850. UA_ProcessMessageCallback callback) {
  851. UA_Message *message, *tmp_message;
  852. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  853. TAILQ_FOREACH_SAFE(message, &channel->messages, pointers, tmp_message) {
  854. /* Stop at the first incomplete message */
  855. if(!message->final)
  856. break;
  857. /* Has the channel been closed (during the last message)? */
  858. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  859. break;
  860. /* Remove the current message before processing */
  861. TAILQ_REMOVE(&channel->messages, message, pointers);
  862. /* Process */
  863. retval = processMessage(channel, message, application, callback);
  864. if(retval != UA_STATUSCODE_GOOD)
  865. break;
  866. /* Clean up the message */
  867. UA_ChunkPayload *payload;
  868. while((payload = SIMPLEQ_FIRST(&message->chunkPayloads))) {
  869. if(payload->copied)
  870. UA_ByteString_deleteMembers(&payload->bytes);
  871. SIMPLEQ_REMOVE_HEAD(&message->chunkPayloads, pointers);
  872. UA_free(payload);
  873. }
  874. UA_free(message);
  875. }
  876. return retval;
  877. }
  878. /****************************/
  879. /* Process a received Chunk */
  880. /****************************/
  881. static UA_StatusCode
  882. decryptChunk(const UA_SecureChannel *const channel, const UA_SecurityPolicyCryptoModule *const cryptoModule,
  883. UA_MessageType const messageType, const UA_ByteString *const chunk, size_t const offset,
  884. size_t *const chunkSizeAfterDecryption) {
  885. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Decrypting chunk");
  886. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  887. size_t sizeBeforeDecryption = cipherText.length;
  888. size_t chunkSizeBeforeDecryption = *chunkSizeAfterDecryption;
  889. /* Always decrypt opn messages if mode not none */
  890. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  891. messageType == UA_MESSAGETYPE_OPN) {
  892. UA_StatusCode retval = cryptoModule->encryptionAlgorithm
  893. .decrypt(channel->securityPolicy, channel->channelContext, &cipherText);
  894. *chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  895. if(retval != UA_STATUSCODE_GOOD) {
  896. return retval;
  897. }
  898. }
  899. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  900. "Chunk size before and after decryption: %lu, %lu",
  901. (long unsigned int)chunkSizeBeforeDecryption, (long unsigned int)*chunkSizeAfterDecryption);
  902. return UA_STATUSCODE_GOOD;
  903. }
  904. static UA_StatusCode
  905. getPaddingSize(const UA_SecureChannel *const channel, const UA_SecurityPolicyCryptoModule *const cryptoModule,
  906. UA_MessageType const messageType, const UA_ByteString *const chunk,
  907. size_t const chunkSizeAfterDecryption, size_t sigsize, size_t *const paddingSize) {
  908. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  909. (messageType == UA_MESSAGETYPE_OPN &&
  910. channel->securityMode > UA_MESSAGESECURITYMODE_NONE)) {
  911. *paddingSize = (size_t)chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  912. size_t keyLength =
  913. cryptoModule->encryptionAlgorithm.getRemoteKeyLength(channel->securityPolicy, channel->channelContext);
  914. if(keyLength > 2048) {
  915. *paddingSize <<= 8; /* Extra padding size */
  916. *paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  917. // see comment below but for extraPaddingSize
  918. *paddingSize += 1;
  919. }
  920. // we need to add one to the padding size since the paddingSize byte itself need to be removed as well.
  921. // TODO: write unit test for correct padding calculation
  922. *paddingSize += 1;
  923. }
  924. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  925. "Calculated padding size to be %lu",
  926. (long unsigned int)*paddingSize);
  927. return UA_STATUSCODE_GOOD;
  928. }
  929. static UA_StatusCode
  930. verifyChunk(const UA_SecureChannel *const channel, const UA_SecurityPolicyCryptoModule *const cryptoModule,
  931. const UA_ByteString *const chunk, size_t const chunkSizeAfterDecryption, size_t sigsize) {
  932. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Verifying chunk signature");
  933. /* Verify the signature */
  934. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  935. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  936. UA_StatusCode retval = cryptoModule->signatureAlgorithm.verify(channel->securityPolicy, channel->channelContext,
  937. &chunkDataToVerify, &signature);
  938. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  939. retval |= decrypt_verifySignatureFailure;
  940. #endif
  941. return retval;
  942. }
  943. /* Sets the payload to a pointer inside the chunk buffer. Returns the requestId
  944. * and the sequenceNumber */
  945. static UA_StatusCode
  946. decryptAndVerifyChunk(const UA_SecureChannel *channel, const UA_SecurityPolicyCryptoModule *cryptoModule,
  947. UA_MessageType messageType, const UA_ByteString *chunk, size_t offset,
  948. UA_UInt32 *requestId, UA_UInt32 *sequenceNumber, UA_ByteString *payload) {
  949. UA_StatusCode retval;
  950. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  951. size_t chunkSizeAfterDecryption = chunk->length;
  952. retval = decryptChunk(channel, cryptoModule, messageType, chunk, offset, &chunkSizeAfterDecryption);
  953. if(retval != UA_STATUSCODE_GOOD)
  954. return retval;
  955. /* Verify the chunk signature */
  956. size_t sigsize = 0;
  957. size_t paddingSize = 0;
  958. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  959. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  960. messageType == UA_MESSAGETYPE_OPN) {
  961. sigsize = cryptoModule->signatureAlgorithm.getRemoteSignatureSize(securityPolicy, channel->channelContext);
  962. retval = getPaddingSize(channel, cryptoModule, messageType, chunk,
  963. chunkSizeAfterDecryption, sigsize, &paddingSize);
  964. if(retval != UA_STATUSCODE_GOOD)
  965. return retval;
  966. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  967. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  968. retval = verifyChunk(channel, cryptoModule, chunk, chunkSizeAfterDecryption, sigsize);
  969. if(retval != UA_STATUSCODE_GOOD)
  970. return retval;
  971. }
  972. /* Decode the sequence header */
  973. UA_SequenceHeader sequenceHeader;
  974. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  975. if(retval != UA_STATUSCODE_GOOD)
  976. return retval;
  977. if(offset + paddingSize + sigsize >= chunk->length)
  978. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  979. *requestId = sequenceHeader.requestId;
  980. *sequenceNumber = sequenceHeader.sequenceNumber;
  981. payload->data = chunk->data + offset;
  982. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  983. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  984. "Decrypted and verified chunk with request id %u and sequence number %u",
  985. *requestId, *sequenceNumber);
  986. return UA_STATUSCODE_GOOD;
  987. }
  988. typedef UA_StatusCode(*UA_SequenceNumberCallback)(UA_SecureChannel *channel,
  989. UA_UInt32 sequenceNumber);
  990. static UA_StatusCode
  991. processSequenceNumberAsym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  992. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Sequence Number processed: %i", sequenceNumber);
  993. channel->receiveSequenceNumber = sequenceNumber;
  994. return UA_STATUSCODE_GOOD;
  995. }
  996. static UA_StatusCode
  997. processSequenceNumberSym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  998. /* Failure mode hook for unit tests */
  999. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  1000. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  1001. return processSym_seqNumberFailure;
  1002. #endif
  1003. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Sequence Number processed: %i", sequenceNumber);
  1004. /* Does the sequence number match? */
  1005. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  1006. /* FIXME: Remove magic numbers :( */
  1007. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  1008. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  1009. else
  1010. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  1011. }
  1012. ++channel->receiveSequenceNumber;
  1013. return UA_STATUSCODE_GOOD;
  1014. }
  1015. static UA_StatusCode
  1016. checkAsymHeader(UA_SecureChannel *const channel,
  1017. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  1018. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1019. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  1020. if(!UA_ByteString_equal(&securityPolicy->policyUri, &asymHeader->securityPolicyUri)) {
  1021. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  1022. }
  1023. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  1024. /* Something like this
  1025. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  1026. if(retval != UA_STATUSCODE_GOOD)
  1027. return retval;
  1028. */
  1029. retval = securityPolicy->asymmetricModule.
  1030. compareCertificateThumbprint(securityPolicy, &asymHeader->receiverCertificateThumbprint);
  1031. if(retval != UA_STATUSCODE_GOOD) {
  1032. return retval;
  1033. }
  1034. return UA_STATUSCODE_GOOD;
  1035. }
  1036. static UA_StatusCode
  1037. checkPreviousToken(UA_SecureChannel *const channel, const UA_UInt32 tokenId) {
  1038. if(tokenId != channel->previousSecurityToken.tokenId)
  1039. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1040. UA_DateTime timeout = channel->previousSecurityToken.createdAt +
  1041. (UA_DateTime)((UA_Double)channel->previousSecurityToken.revisedLifetime *
  1042. (UA_Double)UA_DATETIME_MSEC *
  1043. 1.25);
  1044. if(timeout < UA_DateTime_nowMonotonic()) {
  1045. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1046. }
  1047. return UA_STATUSCODE_GOOD;
  1048. }
  1049. static UA_StatusCode
  1050. checkSymHeader(UA_SecureChannel *const channel,
  1051. const UA_UInt32 tokenId, UA_Boolean allowPreviousToken) {
  1052. if(tokenId == channel->securityToken.tokenId) {
  1053. if(channel->state == UA_SECURECHANNELSTATE_OPEN &&
  1054. (channel->securityToken.createdAt +
  1055. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  1056. < UA_DateTime_nowMonotonic()) {
  1057. UA_SecureChannel_close(channel);
  1058. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1059. }
  1060. }
  1061. if(tokenId != channel->securityToken.tokenId) {
  1062. if(tokenId != channel->nextSecurityToken.tokenId) {
  1063. if(allowPreviousToken)
  1064. return checkPreviousToken(channel, tokenId);
  1065. else
  1066. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1067. }
  1068. return UA_SecureChannel_revolveTokens(channel);
  1069. }
  1070. if(channel->previousSecurityToken.tokenId != 0) {
  1071. UA_StatusCode retval = UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  1072. UA_ChannelSecurityToken_deleteMembers(&channel->previousSecurityToken);
  1073. return retval;
  1074. }
  1075. return UA_STATUSCODE_GOOD;
  1076. }
  1077. static UA_StatusCode
  1078. putPayload(UA_SecureChannel *const channel, UA_UInt32 const requestId, UA_MessageType const messageType,
  1079. UA_ChunkType const chunkType, UA_ByteString *chunkPayload) {
  1080. switch(chunkType) {
  1081. case UA_CHUNKTYPE_INTERMEDIATE:
  1082. case UA_CHUNKTYPE_FINAL:
  1083. return addChunkPayload(channel, requestId, messageType,
  1084. chunkPayload, chunkType == UA_CHUNKTYPE_FINAL);
  1085. case UA_CHUNKTYPE_ABORT:
  1086. deleteLatestMessage(channel, requestId);
  1087. return UA_STATUSCODE_GOOD;
  1088. default:
  1089. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1090. }
  1091. }
  1092. /* The chunk body begins after the SecureConversationMessageHeader */
  1093. static UA_StatusCode
  1094. decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk, UA_Boolean allowPreviousToken) {
  1095. /* Decode the MessageHeader */
  1096. size_t offset = 0;
  1097. UA_SecureConversationMessageHeader messageHeader;
  1098. UA_StatusCode retval =
  1099. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  1100. if(retval != UA_STATUSCODE_GOOD)
  1101. return retval;
  1102. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1103. /* The wrong ChannelId. Non-opened channels have the id zero. */
  1104. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  1105. channel->state != UA_SECURECHANNELSTATE_FRESH)
  1106. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  1107. #endif
  1108. UA_MessageType messageType = (UA_MessageType)
  1109. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  1110. UA_ChunkType chunkType = (UA_ChunkType)
  1111. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  1112. UA_UInt32 requestId = 0;
  1113. UA_UInt32 sequenceNumber = 0;
  1114. UA_ByteString chunkPayload;
  1115. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  1116. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  1117. switch(messageType) {
  1118. /* ERR message (not encrypted) */
  1119. case UA_MESSAGETYPE_ERR:
  1120. if(chunkType != UA_CHUNKTYPE_FINAL)
  1121. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1122. chunkPayload.length = chunk->length - offset;
  1123. chunkPayload.data = chunk->data + offset;
  1124. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1125. /* MSG and CLO: Symmetric encryption */
  1126. case UA_MESSAGETYPE_MSG:
  1127. case UA_MESSAGETYPE_CLO: {
  1128. /* Decode and check the symmetric security header (tokenId) */
  1129. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  1130. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  1131. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  1132. &symmetricSecurityHeader);
  1133. if(retval != UA_STATUSCODE_GOOD)
  1134. return retval;
  1135. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1136. /* Help fuzzing by always setting the correct tokenId */
  1137. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  1138. #endif
  1139. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId, allowPreviousToken);
  1140. if(retval != UA_STATUSCODE_GOOD)
  1141. return retval;
  1142. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  1143. sequenceNumberCallback = processSequenceNumberSym;
  1144. break;
  1145. }
  1146. /* OPN: Asymmetric encryption */
  1147. case UA_MESSAGETYPE_OPN: {
  1148. /* Chunking not allowed for OPN */
  1149. if(chunkType != UA_CHUNKTYPE_FINAL)
  1150. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1151. /* Decode the asymmetric algorithm security header and call the callback
  1152. * to perform checks. */
  1153. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  1154. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  1155. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  1156. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  1157. if(retval != UA_STATUSCODE_GOOD)
  1158. return retval;
  1159. retval = checkAsymHeader(channel, &asymHeader);
  1160. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  1161. if(retval != UA_STATUSCODE_GOOD)
  1162. return retval;
  1163. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  1164. sequenceNumberCallback = processSequenceNumberAsym;
  1165. break;
  1166. }
  1167. /* Invalid message type */
  1168. default:return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1169. }
  1170. UA_assert(cryptoModule != NULL);
  1171. retval = decryptAndVerifyChunk(channel, cryptoModule, messageType, chunk, offset,
  1172. &requestId, &sequenceNumber, &chunkPayload);
  1173. if(retval != UA_STATUSCODE_GOOD)
  1174. return retval;
  1175. /* Check the sequence number. Skip sequence number checking for fuzzer to
  1176. * improve coverage */
  1177. if(sequenceNumberCallback == NULL)
  1178. return UA_STATUSCODE_BADINTERNALERROR;
  1179. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1180. retval = UA_STATUSCODE_GOOD;
  1181. #else
  1182. retval = sequenceNumberCallback(channel, sequenceNumber);
  1183. #endif
  1184. if(retval != UA_STATUSCODE_GOOD)
  1185. return retval;
  1186. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1187. }
  1188. UA_StatusCode
  1189. UA_SecureChannel_decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk,
  1190. UA_Boolean allowPreviousToken) {
  1191. /* Has the SecureChannel timed out? */
  1192. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  1193. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1194. /* Is the SecureChannel configured? */
  1195. if(!channel->connection)
  1196. return UA_STATUSCODE_BADINTERNALERROR;
  1197. UA_StatusCode retval = decryptAddChunk(channel, chunk, allowPreviousToken);
  1198. if(retval != UA_STATUSCODE_GOOD)
  1199. UA_SecureChannel_close(channel);
  1200. return retval;
  1201. }
  1202. UA_StatusCode
  1203. UA_SecureChannel_persistIncompleteMessages(UA_SecureChannel *channel) {
  1204. UA_Message *me;
  1205. TAILQ_FOREACH(me, &channel->messages, pointers) {
  1206. UA_ChunkPayload *cp;
  1207. SIMPLEQ_FOREACH(cp, &me->chunkPayloads, pointers) {
  1208. if(cp->copied)
  1209. continue;
  1210. UA_ByteString copy;
  1211. UA_StatusCode retval = UA_ByteString_copy(&cp->bytes, &copy);
  1212. if(retval != UA_STATUSCODE_GOOD) {
  1213. UA_SecureChannel_close(channel);
  1214. return retval;
  1215. }
  1216. cp->bytes = copy;
  1217. cp->copied = true;
  1218. }
  1219. }
  1220. return UA_STATUSCODE_GOOD;
  1221. }
  1222. /* Functionality used by both the SecureChannel and the SecurityPolicy */
  1223. size_t
  1224. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(const UA_SecurityPolicy *securityPolicy,
  1225. const void *channelContext,
  1226. size_t maxEncryptionLength) {
  1227. if(maxEncryptionLength == 0)
  1228. return 0;
  1229. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  1230. getRemotePlainTextBlockSize(securityPolicy, channelContext);
  1231. size_t encryptedBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  1232. getRemoteBlockSize(securityPolicy, channelContext);
  1233. if(plainTextBlockSize == 0)
  1234. return 0;
  1235. size_t maxNumberOfBlocks = maxEncryptionLength / plainTextBlockSize;
  1236. return maxNumberOfBlocks * (encryptedBlockSize - plainTextBlockSize);
  1237. }