ua_securechannel.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2014, 2016-2017 (c) Florian Palm
  7. * Copyright 2015-2016 (c) Sten Grüner
  8. * Copyright 2015 (c) Oleksiy Vasylyev
  9. * Copyright 2016 (c) TorbenD
  10. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  11. * Copyright 2017-2018 (c) Mark Giraud, Fraunhofer IOSB
  12. */
  13. #include "ua_securechannel.h"
  14. #include <open62541/plugin/securitypolicy.h>
  15. #include <open62541/transport_generated_encoding_binary.h>
  16. #include <open62541/transport_generated_handling.h>
  17. #include <open62541/types_generated_encoding_binary.h>
  18. #include <open62541/types_generated_handling.h>
  19. #include "ua_types_encoding_binary.h"
  20. #include "ua_util_internal.h"
  21. #define UA_BITMASK_MESSAGETYPE 0x00ffffffu
  22. #define UA_BITMASK_CHUNKTYPE 0xff000000u
  23. #define UA_ASYMMETRIC_ALG_SECURITY_HEADER_FIXED_LENGTH 12
  24. #define UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH 4
  25. #define UA_SEQUENCE_HEADER_LENGTH 8
  26. #define UA_SECUREMH_AND_SYMALGH_LENGTH \
  27. (UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + \
  28. UA_SYMMETRIC_ALG_SECURITY_HEADER_LENGTH)
  29. const UA_ByteString UA_SECURITY_POLICY_NONE_URI =
  30. {47, (UA_Byte *)"http://opcfoundation.org/UA/SecurityPolicy#None"};
  31. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  32. UA_StatusCode decrypt_verifySignatureFailure;
  33. UA_StatusCode sendAsym_sendFailure;
  34. UA_StatusCode processSym_seqNumberFailure;
  35. #endif
  36. void
  37. UA_SecureChannel_init(UA_SecureChannel *channel) {
  38. /* Linked lists are also initialized by zeroing out */
  39. memset(channel, 0, sizeof(UA_SecureChannel));
  40. channel->state = UA_SECURECHANNELSTATE_FRESH;
  41. TAILQ_INIT(&channel->messages);
  42. }
  43. UA_StatusCode
  44. UA_SecureChannel_setSecurityPolicy(UA_SecureChannel *channel,
  45. const UA_SecurityPolicy *securityPolicy,
  46. const UA_ByteString *remoteCertificate) {
  47. /* Is a policy already configured? */
  48. if(channel->securityPolicy) {
  49. UA_LOG_ERROR(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  50. "Security policy already configured");
  51. return UA_STATUSCODE_BADINTERNALERROR;
  52. }
  53. UA_StatusCode retval;
  54. if(securityPolicy->certificateVerification != NULL) {
  55. retval = securityPolicy->certificateVerification->
  56. verifyCertificate(securityPolicy->certificateVerification->context,
  57. remoteCertificate);
  58. if(retval != UA_STATUSCODE_GOOD)
  59. return retval;
  60. } else {
  61. UA_LOG_WARNING(securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY,
  62. "Security policy None is used to create SecureChannel. 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 & 0xffu);
  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 >> 8u);
  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 >> 8u);
  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 >> 8u) ? 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_SecureChannel *const channel = messageContext->channel;
  652. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  653. UA_Connection *const connection = channel->connection;
  654. if(!connection)
  655. return UA_STATUSCODE_BADINTERNALERROR;
  656. size_t bodyLength = 0;
  657. UA_StatusCode res = checkLimitsSym(messageContext, &bodyLength);
  658. if(res != UA_STATUSCODE_GOOD)
  659. goto error;
  660. /* Add padding */
  661. #ifdef UA_ENABLE_ENCRYPTION
  662. padChunkSym(messageContext, bodyLength);
  663. #endif
  664. /* The total message length */
  665. size_t pre_sig_length = (uintptr_t)(messageContext->buf_pos) -
  666. (uintptr_t)messageContext->messageBuffer.data;
  667. size_t total_length = pre_sig_length;
  668. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  669. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  670. total_length += securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  671. getLocalSignatureSize(securityPolicy, channel->channelContext);
  672. /* Space for the padding and the signature have been reserved in setBufPos() */
  673. UA_assert(total_length <= connection->config.sendBufferSize);
  674. /* For giving the buffer to the network layer */
  675. messageContext->messageBuffer.length = total_length;
  676. UA_assert(res == UA_STATUSCODE_GOOD);
  677. res = encodeHeadersSym(messageContext, total_length);
  678. if(res != UA_STATUSCODE_GOOD)
  679. goto error;
  680. #ifdef UA_ENABLE_ENCRYPTION
  681. res = signChunkSym(messageContext, pre_sig_length);
  682. if(res != UA_STATUSCODE_GOOD)
  683. goto error;
  684. res = encryptChunkSym(messageContext, total_length);
  685. if(res != UA_STATUSCODE_GOOD)
  686. goto error;
  687. #endif
  688. /* Send the chunk, the buffer is freed in the network layer */
  689. return connection->send(channel->connection, &messageContext->messageBuffer);
  690. error:
  691. connection->releaseSendBuffer(channel->connection, &messageContext->messageBuffer);
  692. return res;
  693. }
  694. /* Callback from the encoding layer. Send the chunk and replace the buffer. */
  695. static UA_StatusCode
  696. sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
  697. /* Set buf values from encoding in the messagecontext */
  698. UA_MessageContext *mc = (UA_MessageContext *)data;
  699. mc->buf_pos = *buf_pos;
  700. mc->buf_end = *buf_end;
  701. /* Send out */
  702. UA_StatusCode retval = sendSymmetricChunk(mc);
  703. if(retval != UA_STATUSCODE_GOOD)
  704. return retval;
  705. /* Set a new buffer for the next chunk */
  706. UA_Connection *connection = mc->channel->connection;
  707. if(!connection)
  708. return UA_STATUSCODE_BADINTERNALERROR;
  709. retval = connection->getSendBuffer(connection, connection->config.sendBufferSize,
  710. &mc->messageBuffer);
  711. if(retval != UA_STATUSCODE_GOOD)
  712. return retval;
  713. /* Hide bytes for header, padding and signature */
  714. setBufPos(mc);
  715. *buf_pos = mc->buf_pos;
  716. *buf_end = mc->buf_end;
  717. return UA_STATUSCODE_GOOD;
  718. }
  719. UA_StatusCode
  720. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  721. UA_UInt32 requestId, UA_MessageType messageType) {
  722. UA_Connection *connection = channel->connection;
  723. if(!connection)
  724. return UA_STATUSCODE_BADINTERNALERROR;
  725. if(messageType != UA_MESSAGETYPE_MSG && messageType != UA_MESSAGETYPE_CLO)
  726. return UA_STATUSCODE_BADINTERNALERROR;
  727. /* Create the chunking info structure */
  728. mc->channel = channel;
  729. mc->requestId = requestId;
  730. mc->chunksSoFar = 0;
  731. mc->messageSizeSoFar = 0;
  732. mc->final = false;
  733. mc->messageBuffer = UA_BYTESTRING_NULL;
  734. mc->messageType = messageType;
  735. /* Allocate the message buffer */
  736. UA_StatusCode retval =
  737. connection->getSendBuffer(connection, connection->config.sendBufferSize,
  738. &mc->messageBuffer);
  739. if(retval != UA_STATUSCODE_GOOD)
  740. return retval;
  741. /* Hide bytes for header, padding and signature */
  742. setBufPos(mc);
  743. return UA_STATUSCODE_GOOD;
  744. }
  745. UA_StatusCode
  746. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  747. const UA_DataType *contentType) {
  748. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  749. sendSymmetricEncodingCallback, mc);
  750. if(retval != UA_STATUSCODE_GOOD && mc->messageBuffer.length > 0)
  751. UA_MessageContext_abort(mc);
  752. return retval;
  753. }
  754. UA_StatusCode
  755. UA_MessageContext_finish(UA_MessageContext *mc) {
  756. mc->final = true;
  757. return sendSymmetricChunk(mc);
  758. }
  759. void
  760. UA_MessageContext_abort(UA_MessageContext *mc) {
  761. UA_Connection *connection = mc->channel->connection;
  762. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  763. }
  764. UA_StatusCode
  765. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  766. UA_MessageType messageType, void *payload,
  767. const UA_DataType *payloadType) {
  768. if(!channel || !channel->connection || !payload || !payloadType)
  769. return UA_STATUSCODE_BADINTERNALERROR;
  770. if(channel->connection->state == UA_CONNECTION_CLOSED)
  771. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  772. UA_MessageContext mc;
  773. UA_StatusCode retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
  774. if(retval != UA_STATUSCODE_GOOD)
  775. return retval;
  776. /* Assert's required for clang-analyzer */
  777. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  778. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  779. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  780. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  781. if(retval != UA_STATUSCODE_GOOD)
  782. return retval;
  783. retval = UA_MessageContext_encode(&mc, payload, payloadType);
  784. if(retval != UA_STATUSCODE_GOOD)
  785. return retval;
  786. return UA_MessageContext_finish(&mc);
  787. }
  788. /*****************************/
  789. /* Assemble Complete Message */
  790. /*****************************/
  791. static UA_StatusCode
  792. addChunkPayload(UA_SecureChannel *channel, UA_UInt32 requestId,
  793. UA_MessageType messageType, UA_ByteString *chunkPayload,
  794. UA_Boolean final) {
  795. UA_Message *latest = TAILQ_LAST(&channel->messages, UA_MessageQueue);
  796. if(latest) {
  797. if(latest->requestId != requestId) {
  798. /* Start of a new message */
  799. if(!latest->final)
  800. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  801. latest = NULL;
  802. } else {
  803. if(latest->messageType != messageType) /* MessageType mismatch */
  804. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  805. if(latest->final) /* Correct message, but already finalized */
  806. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  807. }
  808. }
  809. /* Create a new message entry */
  810. if(!latest) {
  811. latest = (UA_Message *)UA_malloc(sizeof(UA_Message));
  812. if(!latest)
  813. return UA_STATUSCODE_BADOUTOFMEMORY;
  814. memset(latest, 0, sizeof(UA_Message));
  815. latest->requestId = requestId;
  816. latest->messageType = messageType;
  817. SIMPLEQ_INIT(&latest->chunkPayloads);
  818. TAILQ_INSERT_TAIL(&channel->messages, latest, pointers);
  819. }
  820. /* Test against the connection settings */
  821. const UA_ConnectionConfig *config = &channel->connection->config;
  822. UA_assert(config != NULL); /* clang-analyzer false positive */
  823. if(config->maxChunkCount > 0 &&
  824. config->maxChunkCount <= latest->chunkPayloadsSize)
  825. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  826. if(config->maxMessageSize > 0 &&
  827. config->maxMessageSize < latest->messageSize + chunkPayload->length)
  828. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  829. /* Create a new chunk entry */
  830. UA_ChunkPayload *cp = (UA_ChunkPayload *)UA_malloc(sizeof(UA_ChunkPayload));
  831. if(!cp)
  832. return UA_STATUSCODE_BADOUTOFMEMORY;
  833. cp->bytes = *chunkPayload;
  834. cp->copied = false;
  835. /* Add the chunk */
  836. SIMPLEQ_INSERT_TAIL(&latest->chunkPayloads, cp, pointers);
  837. latest->chunkPayloadsSize += 1;
  838. latest->messageSize += chunkPayload->length;
  839. latest->final = final;
  840. return UA_STATUSCODE_GOOD;
  841. }
  842. static UA_StatusCode
  843. processMessage(UA_SecureChannel *channel, const UA_Message *message,
  844. void *application, UA_ProcessMessageCallback callback) {
  845. if(message->chunkPayloadsSize == 1) {
  846. /* No need to combine chunks */
  847. UA_ChunkPayload *cp = SIMPLEQ_FIRST(&message->chunkPayloads);
  848. callback(application, channel, message->messageType, message->requestId, &cp->bytes);
  849. } else {
  850. /* Allocate memory */
  851. UA_ByteString bytes;
  852. bytes.data = (UA_Byte *)UA_malloc(message->messageSize);
  853. if(!bytes.data) {
  854. UA_LOG_ERROR(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURECHANNEL,
  855. "Could not allocate the memory to assemble the message");
  856. return UA_STATUSCODE_BADOUTOFMEMORY;
  857. }
  858. bytes.length = message->messageSize;
  859. /* Assemble the full message */
  860. size_t curPos = 0;
  861. UA_ChunkPayload *cp;
  862. SIMPLEQ_FOREACH(cp, &message->chunkPayloads, pointers) {
  863. memcpy(&bytes.data[curPos], cp->bytes.data, cp->bytes.length);
  864. curPos += cp->bytes.length;
  865. }
  866. /* Process the message */
  867. callback(application, channel, message->messageType, message->requestId, &bytes);
  868. UA_ByteString_deleteMembers(&bytes);
  869. }
  870. return UA_STATUSCODE_GOOD;
  871. }
  872. UA_StatusCode
  873. UA_SecureChannel_processCompleteMessages(UA_SecureChannel *channel, void *application,
  874. UA_ProcessMessageCallback callback) {
  875. UA_Message *message, *tmp_message;
  876. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  877. TAILQ_FOREACH_SAFE(message, &channel->messages, pointers, tmp_message) {
  878. /* Stop at the first incomplete message */
  879. if(!message->final)
  880. break;
  881. /* Has the channel been closed (during the last message)? */
  882. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  883. break;
  884. /* Remove the current message before processing */
  885. TAILQ_REMOVE(&channel->messages, message, pointers);
  886. /* Process */
  887. retval = processMessage(channel, message, application, callback);
  888. if(retval != UA_STATUSCODE_GOOD)
  889. break;
  890. /* Clean up the message */
  891. UA_ChunkPayload *payload;
  892. while((payload = SIMPLEQ_FIRST(&message->chunkPayloads))) {
  893. if(payload->copied)
  894. UA_ByteString_deleteMembers(&payload->bytes);
  895. SIMPLEQ_REMOVE_HEAD(&message->chunkPayloads, pointers);
  896. UA_free(payload);
  897. }
  898. UA_free(message);
  899. }
  900. return retval;
  901. }
  902. /****************************/
  903. /* Process a received Chunk */
  904. /****************************/
  905. static UA_StatusCode
  906. decryptChunk(const UA_SecureChannel *const channel,
  907. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  908. UA_MessageType const messageType, const UA_ByteString *const chunk,
  909. size_t const offset, size_t *const chunkSizeAfterDecryption) {
  910. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel, "Decrypting chunk");
  911. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  912. size_t sizeBeforeDecryption = cipherText.length;
  913. size_t chunkSizeBeforeDecryption = *chunkSizeAfterDecryption;
  914. /* Always decrypt opn messages if mode not none */
  915. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  916. messageType == UA_MESSAGETYPE_OPN) {
  917. UA_StatusCode retval = cryptoModule->encryptionAlgorithm.
  918. decrypt(channel->securityPolicy, channel->channelContext, &cipherText);
  919. *chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  920. if(retval != UA_STATUSCODE_GOOD) {
  921. return retval;
  922. }
  923. }
  924. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  925. "Chunk size before and after decryption: %lu, %lu",
  926. (long unsigned int)chunkSizeBeforeDecryption,
  927. (long unsigned int)*chunkSizeAfterDecryption);
  928. return UA_STATUSCODE_GOOD;
  929. }
  930. static UA_UInt16
  931. decodeChunkPaddingSize(const UA_SecureChannel *const channel,
  932. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  933. UA_MessageType const messageType, const UA_ByteString *const chunk,
  934. size_t const chunkSizeAfterDecryption, size_t sigsize) {
  935. /* Is padding used? */
  936. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT &&
  937. !(messageType == UA_MESSAGETYPE_OPN && channel->securityMode > UA_MESSAGESECURITYMODE_NONE))
  938. return 0;
  939. size_t paddingSize = chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  940. /* Extra padding size */
  941. size_t keyLength = cryptoModule->encryptionAlgorithm.
  942. getRemoteKeyLength(channel->securityPolicy, channel->channelContext);
  943. if(keyLength > 2048) {
  944. paddingSize <<= 8u;
  945. paddingSize += 1;
  946. paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  947. }
  948. /* We need to add one to the padding size since the paddingSize byte itself
  949. * need to be removed as well. */
  950. paddingSize += 1;
  951. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  952. "Calculated padding size to be %lu",
  953. (long unsigned int)paddingSize);
  954. return (UA_UInt16)paddingSize;
  955. }
  956. static UA_StatusCode
  957. verifyChunk(const UA_SecureChannel *const channel,
  958. const UA_SecurityPolicyCryptoModule *const cryptoModule,
  959. const UA_ByteString *const chunk,
  960. size_t const chunkSizeAfterDecryption, size_t sigsize) {
  961. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  962. "Verifying chunk signature");
  963. /* Verify the signature */
  964. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  965. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  966. UA_StatusCode retval = cryptoModule->signatureAlgorithm.
  967. verify(channel->securityPolicy, channel->channelContext, &chunkDataToVerify, &signature);
  968. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  969. retval |= decrypt_verifySignatureFailure;
  970. #endif
  971. return retval;
  972. }
  973. /* Sets the payload to a pointer inside the chunk buffer. Returns the requestId
  974. * and the sequenceNumber */
  975. static UA_StatusCode
  976. decryptAndVerifyChunk(const UA_SecureChannel *channel,
  977. const UA_SecurityPolicyCryptoModule *cryptoModule,
  978. UA_MessageType messageType, const UA_ByteString *chunk,
  979. size_t offset, UA_UInt32 *requestId,
  980. UA_UInt32 *sequenceNumber, UA_ByteString *payload) {
  981. size_t chunkSizeAfterDecryption = chunk->length;
  982. UA_StatusCode retval = decryptChunk(channel, cryptoModule, messageType,
  983. chunk, offset, &chunkSizeAfterDecryption);
  984. if(retval != UA_STATUSCODE_GOOD)
  985. return retval;
  986. /* Verify the chunk signature */
  987. size_t sigsize = 0;
  988. size_t paddingSize = 0;
  989. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  990. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  991. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  992. messageType == UA_MESSAGETYPE_OPN) {
  993. sigsize = cryptoModule->signatureAlgorithm.
  994. getRemoteSignatureSize(securityPolicy, channel->channelContext);
  995. paddingSize = decodeChunkPaddingSize(channel, cryptoModule, messageType, chunk,
  996. chunkSizeAfterDecryption, sigsize);
  997. if(retval != UA_STATUSCODE_GOOD)
  998. return retval;
  999. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  1000. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  1001. retval = verifyChunk(channel, cryptoModule, chunk, chunkSizeAfterDecryption, sigsize);
  1002. if(retval != UA_STATUSCODE_GOOD)
  1003. return retval;
  1004. }
  1005. /* Decode the sequence header */
  1006. UA_SequenceHeader sequenceHeader;
  1007. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  1008. if(retval != UA_STATUSCODE_GOOD)
  1009. return retval;
  1010. if(offset + paddingSize + sigsize >= chunk->length)
  1011. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  1012. *requestId = sequenceHeader.requestId;
  1013. *sequenceNumber = sequenceHeader.sequenceNumber;
  1014. payload->data = chunk->data + offset;
  1015. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  1016. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1017. "Decrypted and verified chunk with request id %u and "
  1018. "sequence number %u", *requestId, *sequenceNumber);
  1019. return UA_STATUSCODE_GOOD;
  1020. }
  1021. typedef UA_StatusCode
  1022. (*UA_SequenceNumberCallback)(UA_SecureChannel *channel, UA_UInt32 sequenceNumber);
  1023. static UA_StatusCode
  1024. processSequenceNumberAsym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  1025. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1026. "Sequence Number processed: %i", sequenceNumber);
  1027. channel->receiveSequenceNumber = sequenceNumber;
  1028. return UA_STATUSCODE_GOOD;
  1029. }
  1030. static UA_StatusCode
  1031. processSequenceNumberSym(UA_SecureChannel *channel, UA_UInt32 sequenceNumber) {
  1032. /* Failure mode hook for unit tests */
  1033. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  1034. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  1035. return processSym_seqNumberFailure;
  1036. #endif
  1037. UA_LOG_TRACE_CHANNEL(channel->securityPolicy->logger, channel,
  1038. "Sequence Number processed: %i", sequenceNumber);
  1039. /* Does the sequence number match? */
  1040. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  1041. /* FIXME: Remove magic numbers :( */
  1042. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  1043. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  1044. else
  1045. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  1046. }
  1047. ++channel->receiveSequenceNumber;
  1048. return UA_STATUSCODE_GOOD;
  1049. }
  1050. static UA_StatusCode
  1051. checkAsymHeader(UA_SecureChannel *const channel,
  1052. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  1053. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  1054. if(!UA_ByteString_equal(&securityPolicy->policyUri,
  1055. &asymHeader->securityPolicyUri)) {
  1056. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  1057. }
  1058. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  1059. /* Something like this
  1060. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  1061. if(retval != UA_STATUSCODE_GOOD)
  1062. return retval;
  1063. */
  1064. UA_StatusCode retval = securityPolicy->asymmetricModule.
  1065. compareCertificateThumbprint(securityPolicy,
  1066. &asymHeader->receiverCertificateThumbprint);
  1067. if(retval != UA_STATUSCODE_GOOD) {
  1068. return retval;
  1069. }
  1070. return UA_STATUSCODE_GOOD;
  1071. }
  1072. static UA_StatusCode
  1073. checkPreviousToken(UA_SecureChannel *const channel, const UA_UInt32 tokenId) {
  1074. if(tokenId != channel->previousSecurityToken.tokenId)
  1075. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1076. UA_DateTime timeout = channel->previousSecurityToken.createdAt +
  1077. (UA_DateTime)((UA_Double)channel->previousSecurityToken.revisedLifetime *
  1078. (UA_Double)UA_DATETIME_MSEC * 1.25);
  1079. if(timeout < UA_DateTime_nowMonotonic())
  1080. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1081. return UA_STATUSCODE_GOOD;
  1082. }
  1083. static UA_StatusCode
  1084. checkSymHeader(UA_SecureChannel *const channel,
  1085. const UA_UInt32 tokenId, UA_Boolean allowPreviousToken) {
  1086. /* If the message uses the currently active token, check if it is still valid */
  1087. if(tokenId == channel->securityToken.tokenId) {
  1088. if(channel->state == UA_SECURECHANNELSTATE_OPEN &&
  1089. (channel->securityToken.createdAt +
  1090. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  1091. < UA_DateTime_nowMonotonic()) {
  1092. UA_SecureChannel_close(channel);
  1093. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1094. }
  1095. }
  1096. /* If the message uses a different token, check if it is the next token. */
  1097. if(tokenId != channel->securityToken.tokenId) {
  1098. /* If it isn't the next token, we might be dealing with a message, that
  1099. * still uses the old token, so check if the old one is still valid.*/
  1100. if(tokenId != channel->nextSecurityToken.tokenId) {
  1101. if(allowPreviousToken)
  1102. return checkPreviousToken(channel, tokenId);
  1103. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  1104. }
  1105. /* If the token is indeed the next token, revolve the tokens */
  1106. UA_StatusCode retval = UA_SecureChannel_revolveTokens(channel);
  1107. if(retval != UA_STATUSCODE_GOOD)
  1108. return retval;
  1109. /* If the message now uses the currently active token also generate
  1110. * new remote keys to correctly decrypt. */
  1111. if(channel->securityToken.tokenId == tokenId) {
  1112. retval = UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  1113. UA_ChannelSecurityToken_deleteMembers(&channel->previousSecurityToken);
  1114. return retval;
  1115. }
  1116. }
  1117. /* It is possible that the sent messages already use the new token, but
  1118. * the received messages still use the old token. If we receive a message
  1119. * with the new token, we will need to generate the keys and discard the
  1120. * old token now*/
  1121. if(channel->previousSecurityToken.tokenId != 0) {
  1122. UA_StatusCode retval =
  1123. UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  1124. UA_ChannelSecurityToken_deleteMembers(&channel->previousSecurityToken);
  1125. return retval;
  1126. }
  1127. return UA_STATUSCODE_GOOD;
  1128. }
  1129. static UA_StatusCode
  1130. putPayload(UA_SecureChannel *const channel, UA_UInt32 const requestId,
  1131. UA_MessageType const messageType, UA_ChunkType const chunkType,
  1132. UA_ByteString *chunkPayload) {
  1133. switch(chunkType) {
  1134. case UA_CHUNKTYPE_INTERMEDIATE:
  1135. case UA_CHUNKTYPE_FINAL:
  1136. return addChunkPayload(channel, requestId, messageType,
  1137. chunkPayload, chunkType == UA_CHUNKTYPE_FINAL);
  1138. case UA_CHUNKTYPE_ABORT:
  1139. deleteLatestMessage(channel, requestId);
  1140. return UA_STATUSCODE_GOOD;
  1141. default:
  1142. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1143. }
  1144. }
  1145. /* The chunk body begins after the SecureConversationMessageHeader */
  1146. static UA_StatusCode
  1147. decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk,
  1148. UA_Boolean allowPreviousToken) {
  1149. /* Decode the MessageHeader */
  1150. size_t offset = 0;
  1151. UA_SecureConversationMessageHeader messageHeader;
  1152. UA_StatusCode retval =
  1153. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  1154. if(retval != UA_STATUSCODE_GOOD)
  1155. return retval;
  1156. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1157. /* The wrong ChannelId. Non-opened channels have the id zero. */
  1158. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  1159. channel->state != UA_SECURECHANNELSTATE_FRESH)
  1160. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  1161. #endif
  1162. UA_MessageType messageType = (UA_MessageType)
  1163. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  1164. UA_ChunkType chunkType = (UA_ChunkType)
  1165. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  1166. UA_UInt32 requestId = 0;
  1167. UA_UInt32 sequenceNumber = 0;
  1168. UA_ByteString chunkPayload;
  1169. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  1170. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  1171. switch(messageType) {
  1172. /* ERR message (not encrypted) */
  1173. case UA_MESSAGETYPE_ERR:
  1174. if(chunkType != UA_CHUNKTYPE_FINAL)
  1175. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1176. chunkPayload.length = chunk->length - offset;
  1177. chunkPayload.data = chunk->data + offset;
  1178. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1179. /* MSG and CLO: Symmetric encryption */
  1180. case UA_MESSAGETYPE_MSG:
  1181. case UA_MESSAGETYPE_CLO: {
  1182. /* Decode and check the symmetric security header (tokenId) */
  1183. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  1184. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  1185. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  1186. &symmetricSecurityHeader);
  1187. if(retval != UA_STATUSCODE_GOOD)
  1188. return retval;
  1189. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1190. /* Help fuzzing by always setting the correct tokenId */
  1191. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  1192. #endif
  1193. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId, allowPreviousToken);
  1194. if(retval != UA_STATUSCODE_GOOD)
  1195. return retval;
  1196. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  1197. sequenceNumberCallback = processSequenceNumberSym;
  1198. break;
  1199. }
  1200. /* OPN: Asymmetric encryption */
  1201. case UA_MESSAGETYPE_OPN: {
  1202. /* Chunking not allowed for OPN */
  1203. if(chunkType != UA_CHUNKTYPE_FINAL)
  1204. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1205. /* Decode the asymmetric algorithm security header and call the callback
  1206. * to perform checks. */
  1207. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  1208. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  1209. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  1210. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  1211. if(retval != UA_STATUSCODE_GOOD)
  1212. return retval;
  1213. retval = checkAsymHeader(channel, &asymHeader);
  1214. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  1215. if(retval != UA_STATUSCODE_GOOD)
  1216. return retval;
  1217. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  1218. sequenceNumberCallback = processSequenceNumberAsym;
  1219. break;
  1220. }
  1221. /* Invalid message type */
  1222. default:return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1223. }
  1224. UA_assert(cryptoModule != NULL);
  1225. retval = decryptAndVerifyChunk(channel, cryptoModule, messageType, chunk, offset,
  1226. &requestId, &sequenceNumber, &chunkPayload);
  1227. if(retval != UA_STATUSCODE_GOOD)
  1228. return retval;
  1229. /* Check the sequence number. Skip sequence number checking for fuzzer to
  1230. * improve coverage */
  1231. if(sequenceNumberCallback == NULL)
  1232. return UA_STATUSCODE_BADINTERNALERROR;
  1233. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  1234. retval = UA_STATUSCODE_GOOD;
  1235. #else
  1236. retval = sequenceNumberCallback(channel, sequenceNumber);
  1237. #endif
  1238. if(retval != UA_STATUSCODE_GOOD)
  1239. return retval;
  1240. return putPayload(channel, requestId, messageType, chunkType, &chunkPayload);
  1241. }
  1242. UA_StatusCode
  1243. UA_SecureChannel_decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk,
  1244. UA_Boolean allowPreviousToken) {
  1245. /* Has the SecureChannel timed out? */
  1246. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  1247. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1248. /* Is the SecureChannel configured? */
  1249. if(!channel->connection)
  1250. return UA_STATUSCODE_BADINTERNALERROR;
  1251. UA_StatusCode retval = decryptAddChunk(channel, chunk, allowPreviousToken);
  1252. if(retval != UA_STATUSCODE_GOOD)
  1253. UA_SecureChannel_close(channel);
  1254. return retval;
  1255. }
  1256. UA_StatusCode
  1257. UA_SecureChannel_persistIncompleteMessages(UA_SecureChannel *channel) {
  1258. UA_Message *me;
  1259. TAILQ_FOREACH(me, &channel->messages, pointers) {
  1260. UA_ChunkPayload *cp;
  1261. SIMPLEQ_FOREACH(cp, &me->chunkPayloads, pointers) {
  1262. if(cp->copied)
  1263. continue;
  1264. UA_ByteString copy;
  1265. UA_StatusCode retval = UA_ByteString_copy(&cp->bytes, &copy);
  1266. if(retval != UA_STATUSCODE_GOOD) {
  1267. UA_SecureChannel_close(channel);
  1268. return retval;
  1269. }
  1270. cp->bytes = copy;
  1271. cp->copied = true;
  1272. }
  1273. }
  1274. return UA_STATUSCODE_GOOD;
  1275. }
  1276. /* Functionality used by both the SecureChannel and the SecurityPolicy */
  1277. size_t
  1278. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(const UA_SecurityPolicy *securityPolicy,
  1279. const void *channelContext,
  1280. size_t maxEncryptionLength) {
  1281. if(maxEncryptionLength == 0)
  1282. return 0;
  1283. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.
  1284. encryptionAlgorithm.getRemotePlainTextBlockSize(securityPolicy, channelContext);
  1285. size_t encryptedBlockSize = securityPolicy->asymmetricModule.cryptoModule.
  1286. encryptionAlgorithm.getRemoteBlockSize(securityPolicy, channelContext);
  1287. if(plainTextBlockSize == 0)
  1288. return 0;
  1289. size_t maxNumberOfBlocks = maxEncryptionLength / plainTextBlockSize;
  1290. return maxNumberOfBlocks * (encryptedBlockSize - plainTextBlockSize);
  1291. }