ua_securechannel.c 62 KB

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