ua_securechannel.c 63 KB

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