ua_securechannel.c 60 KB

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