ua_securechannel.c 62 KB

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