ua_securechannel.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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
  30. UA_SECURITY_POLICY_NONE_URI = {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. UA_StatusCode
  37. UA_SecureChannel_init(UA_SecureChannel *channel,
  38. const UA_SecurityPolicy *securityPolicy,
  39. const UA_ByteString *remoteCertificate) {
  40. if(channel == NULL || securityPolicy == NULL || remoteCertificate == NULL)
  41. return UA_STATUSCODE_BADINTERNALERROR;
  42. /* Linked lists are also initialized by zeroing out */
  43. memset(channel, 0, sizeof(UA_SecureChannel));
  44. channel->state = UA_SECURECHANNELSTATE_FRESH;
  45. channel->securityPolicy = securityPolicy;
  46. UA_StatusCode retval;
  47. if(channel->securityPolicy->certificateVerification != NULL) {
  48. retval = channel->securityPolicy->certificateVerification->
  49. verifyCertificate(channel->securityPolicy->certificateVerification->context, remoteCertificate);
  50. if(retval != UA_STATUSCODE_GOOD)
  51. return retval;
  52. } else {
  53. UA_LOG_WARNING(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURITYPOLICY, "No PKI plugin set. "
  54. "Accepting all certificates");
  55. }
  56. retval = securityPolicy->channelModule.
  57. newContext(securityPolicy, remoteCertificate, &channel->channelContext);
  58. if(retval != UA_STATUSCODE_GOOD)
  59. return retval;
  60. retval = UA_ByteString_copy(remoteCertificate, &channel->remoteCertificate);
  61. if(retval != UA_STATUSCODE_GOOD)
  62. return retval;
  63. UA_ByteString remoteCertificateThumbprint = {20, channel->remoteCertificateThumbprint};
  64. retval = securityPolicy->asymmetricModule.
  65. makeCertificateThumbprint(securityPolicy, &channel->remoteCertificate,
  66. &remoteCertificateThumbprint);
  67. return retval;
  68. }
  69. void
  70. UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel) {
  71. /* Delete members */
  72. UA_ByteString_deleteMembers(&channel->remoteCertificate);
  73. UA_ByteString_deleteMembers(&channel->localNonce);
  74. UA_ByteString_deleteMembers(&channel->remoteNonce);
  75. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  76. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  77. /* Delete the channel context for the security policy */
  78. if(channel->securityPolicy)
  79. channel->securityPolicy->channelModule.deleteContext(channel->channelContext);
  80. /* Detach from the connection and close the connection */
  81. if(channel->connection) {
  82. if(channel->connection->state != UA_CONNECTION_CLOSED)
  83. channel->connection->close(channel->connection);
  84. UA_Connection_detachSecureChannel(channel->connection);
  85. }
  86. /* Remove session pointers (not the sessions) and NULL the pointers back to
  87. * the SecureChannel in the Session */
  88. UA_SessionHeader *sh, *temp;
  89. LIST_FOREACH_SAFE(sh, &channel->sessions, pointers, temp) {
  90. sh->channel = NULL;
  91. LIST_REMOVE(sh, pointers);
  92. }
  93. /* Remove the buffered chunks */
  94. struct MessageEntry *me, *temp_me;
  95. LIST_FOREACH_SAFE(me, &channel->chunks, pointers, temp_me) {
  96. struct ChunkPayload *cp, *temp_cp;
  97. SIMPLEQ_FOREACH_SAFE(cp, &me->chunkPayload, pointers, temp_cp) {
  98. UA_ByteString_deleteMembers(&cp->bytes);
  99. UA_free(cp);
  100. }
  101. LIST_REMOVE(me, pointers);
  102. UA_free(me);
  103. }
  104. }
  105. UA_StatusCode
  106. UA_SecureChannel_generateLocalNonce(UA_SecureChannel *channel) {
  107. if(!channel->securityPolicy)
  108. return UA_STATUSCODE_BADINTERNALERROR;
  109. /* Is the length of the previous nonce correct? */
  110. size_t nonceLength = channel->securityPolicy->symmetricModule.secureChannelNonceLength;
  111. if(channel->localNonce.length != nonceLength) {
  112. UA_ByteString_deleteMembers(&channel->localNonce);
  113. UA_StatusCode retval = UA_ByteString_allocBuffer(&channel->localNonce, nonceLength);
  114. if(retval != UA_STATUSCODE_GOOD)
  115. return retval;
  116. }
  117. return channel->securityPolicy->symmetricModule.
  118. generateNonce(channel->securityPolicy, &channel->localNonce);
  119. }
  120. static UA_StatusCode
  121. UA_SecureChannel_generateLocalKeys(const UA_SecureChannel *const channel,
  122. const UA_SecurityPolicy *const securityPolicy) {
  123. const UA_SecurityPolicyChannelModule *channelModule = &securityPolicy->channelModule;
  124. const UA_SecurityPolicySymmetricModule *symmetricModule = &securityPolicy->symmetricModule;
  125. const UA_SecurityPolicyCryptoModule *const cryptoModule = &securityPolicy->symmetricModule.cryptoModule;
  126. /* Symmetric key length */
  127. size_t encryptionKeyLength =
  128. cryptoModule->encryptionAlgorithm.getLocalKeyLength(securityPolicy, channel->channelContext);
  129. size_t encryptionBlockSize =
  130. cryptoModule->encryptionAlgorithm.getLocalBlockSize(securityPolicy, channel->channelContext);
  131. size_t signingKeyLength =
  132. cryptoModule->signatureAlgorithm.getLocalKeyLength(securityPolicy, channel->channelContext);
  133. const size_t bufSize = encryptionBlockSize + signingKeyLength + encryptionKeyLength;
  134. UA_STACKARRAY(UA_Byte, bufBytes, bufSize);
  135. UA_ByteString buffer = {bufSize, bufBytes};
  136. /* Local keys */
  137. UA_StatusCode retval = symmetricModule->generateKey(securityPolicy, &channel->remoteNonce,
  138. &channel->localNonce, &buffer);
  139. if(retval != UA_STATUSCODE_GOOD)
  140. return retval;
  141. const UA_ByteString localSigningKey = {signingKeyLength, buffer.data};
  142. const UA_ByteString localEncryptingKey = {encryptionKeyLength,
  143. buffer.data + signingKeyLength};
  144. const UA_ByteString localIv = {encryptionBlockSize,
  145. buffer.data + signingKeyLength +
  146. encryptionKeyLength};
  147. retval = channelModule->setLocalSymSigningKey(channel->channelContext, &localSigningKey);
  148. retval |= channelModule->setLocalSymEncryptingKey(channel->channelContext, &localEncryptingKey);
  149. retval |= channelModule->setLocalSymIv(channel->channelContext, &localIv);
  150. return retval;
  151. }
  152. static UA_StatusCode
  153. UA_SecureChannel_generateRemoteKeys(const UA_SecureChannel *const channel,
  154. const UA_SecurityPolicy *const securityPolicy) {
  155. const UA_SecurityPolicyChannelModule *channelModule = &securityPolicy->channelModule;
  156. const UA_SecurityPolicySymmetricModule *symmetricModule = &securityPolicy->symmetricModule;
  157. const UA_SecurityPolicyCryptoModule *const cryptoModule = &securityPolicy->symmetricModule.cryptoModule;
  158. /* Symmetric key length */
  159. size_t encryptionKeyLength =
  160. cryptoModule->encryptionAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  161. size_t encryptionBlockSize =
  162. cryptoModule->encryptionAlgorithm.getRemoteBlockSize(securityPolicy, channel->channelContext);
  163. size_t signingKeyLength =
  164. cryptoModule->signatureAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  165. const size_t bufSize = encryptionBlockSize + signingKeyLength + encryptionKeyLength;
  166. UA_STACKARRAY(UA_Byte, bufBytes, bufSize);
  167. UA_ByteString buffer = {bufSize, bufBytes};
  168. /* Remote keys */
  169. UA_StatusCode retval = symmetricModule->generateKey(securityPolicy, &channel->localNonce,
  170. &channel->remoteNonce, &buffer);
  171. if(retval != UA_STATUSCODE_GOOD)
  172. return retval;
  173. const UA_ByteString remoteSigningKey = {signingKeyLength, buffer.data};
  174. const UA_ByteString remoteEncryptingKey = {encryptionKeyLength,
  175. buffer.data + signingKeyLength};
  176. const UA_ByteString remoteIv = {encryptionBlockSize,
  177. buffer.data + signingKeyLength +
  178. encryptionKeyLength};
  179. retval = channelModule->setRemoteSymSigningKey(channel->channelContext, &remoteSigningKey);
  180. retval |= channelModule->setRemoteSymEncryptingKey(channel->channelContext, &remoteEncryptingKey);
  181. retval |= channelModule->setRemoteSymIv(channel->channelContext, &remoteIv);
  182. if(retval != UA_STATUSCODE_GOOD)
  183. return retval;
  184. return retval;
  185. }
  186. UA_StatusCode
  187. UA_SecureChannel_generateNewKeys(UA_SecureChannel *channel) {
  188. UA_StatusCode retval = UA_SecureChannel_generateLocalKeys(channel, channel->securityPolicy);
  189. if(retval != UA_STATUSCODE_GOOD)
  190. return retval;
  191. retval = UA_SecureChannel_generateRemoteKeys(channel, channel->securityPolicy);
  192. if(retval != UA_STATUSCODE_GOOD)
  193. return retval;
  194. return retval;
  195. }
  196. UA_SessionHeader *
  197. UA_SecureChannel_getSession(UA_SecureChannel *channel,
  198. const UA_NodeId *authenticationToken) {
  199. struct UA_SessionHeader *sh;
  200. LIST_FOREACH(sh, &channel->sessions, pointers) {
  201. if(UA_NodeId_equal(&sh->authenticationToken, authenticationToken))
  202. break;
  203. }
  204. return sh;
  205. }
  206. UA_StatusCode
  207. UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  208. if(channel->nextSecurityToken.tokenId == 0) // no security token issued
  209. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  210. //FIXME: not thread-safe
  211. memcpy(&channel->securityToken, &channel->nextSecurityToken,
  212. sizeof(UA_ChannelSecurityToken));
  213. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  214. return UA_SecureChannel_generateNewKeys(channel);
  215. }
  216. /***************************/
  217. /* Send Asymmetric Message */
  218. /***************************/
  219. static UA_UInt16
  220. calculatePaddingAsym(const UA_SecurityPolicy *securityPolicy, const void *channelContext,
  221. size_t bytesToWrite, UA_Byte *paddingSize, UA_Byte *extraPaddingSize) {
  222. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  223. getRemotePlainTextBlockSize(securityPolicy, channelContext);
  224. size_t signatureSize = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  225. getLocalSignatureSize(securityPolicy, channelContext);
  226. size_t paddingBytes = 1;
  227. if(securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  228. getRemoteKeyLength(securityPolicy, channelContext) > 2048)
  229. ++paddingBytes;
  230. size_t padding = (plainTextBlockSize - ((bytesToWrite + signatureSize + paddingBytes) %
  231. plainTextBlockSize));
  232. *paddingSize = (UA_Byte)(padding & 0xff);
  233. *extraPaddingSize = (UA_Byte)(padding >> 8);
  234. return (UA_UInt16)padding;
  235. }
  236. static size_t
  237. calculateAsymAlgSecurityHeaderLength(const UA_SecureChannel *channel) {
  238. size_t asymHeaderLength = UA_ASYMMETRIC_ALG_SECURITY_HEADER_FIXED_LENGTH +
  239. channel->securityPolicy->policyUri.length;
  240. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  241. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  242. /* OPN is always encrypted even if mode sign only */
  243. asymHeaderLength += 20; /* Thumbprints are always 20 byte long */
  244. asymHeaderLength += channel->securityPolicy->localCertificate.length;
  245. }
  246. return asymHeaderLength;
  247. }
  248. static void
  249. hideBytesAsym(const UA_SecureChannel *channel, UA_Byte **buf_start, const UA_Byte **buf_end) {
  250. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  251. *buf_start += UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + UA_SEQUENCE_HEADER_LENGTH;
  252. /* Add the SecurityHeaderLength */
  253. *buf_start += calculateAsymAlgSecurityHeaderLength(channel);
  254. size_t potentialEncryptionMaxSize = (size_t)(*buf_end - *buf_start) + UA_SEQUENCE_HEADER_LENGTH;
  255. /* Hide bytes for signature and padding */
  256. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  257. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  258. *buf_end -= securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  259. getLocalSignatureSize(securityPolicy, channel->channelContext);
  260. *buf_end -= 2; /* padding byte and extraPadding byte */
  261. /* Add some overhead length due to RSA implementations adding a signature themselves */
  262. *buf_end -= UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(securityPolicy,
  263. channel->channelContext,
  264. potentialEncryptionMaxSize);
  265. }
  266. }
  267. /* Sends an OPN message using asymmetric encryption if defined */
  268. UA_StatusCode
  269. UA_SecureChannel_sendAsymmetricOPNMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  270. const void *content, const UA_DataType *contentType) {
  271. if(channel->securityMode == UA_MESSAGESECURITYMODE_INVALID)
  272. return UA_STATUSCODE_BADSECURITYMODEREJECTED;
  273. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  274. UA_Connection *connection = channel->connection;
  275. if(!connection)
  276. return UA_STATUSCODE_BADINTERNALERROR;
  277. /* Allocate the message buffer */
  278. UA_ByteString buf = UA_BYTESTRING_NULL;
  279. UA_StatusCode retval =
  280. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &buf);
  281. if(retval != UA_STATUSCODE_GOOD)
  282. return retval;
  283. /* Restrict buffer to the available space for the payload */
  284. UA_Byte *buf_pos = buf.data;
  285. const UA_Byte *buf_end = &buf.data[buf.length];
  286. hideBytesAsym(channel, &buf_pos, &buf_end);
  287. /* Encode the message type and content */
  288. UA_NodeId typeId = UA_NODEID_NUMERIC(0, contentType->binaryEncodingId);
  289. retval = UA_encodeBinary(&typeId, &UA_TYPES[UA_TYPES_NODEID], &buf_pos, &buf_end, NULL, NULL);
  290. retval |= UA_encodeBinary(content, contentType, &buf_pos, &buf_end, NULL, NULL);
  291. if(retval != UA_STATUSCODE_GOOD) {
  292. connection->releaseSendBuffer(connection, &buf);
  293. return retval;
  294. }
  295. /* Compute the length of the asym header */
  296. const size_t securityHeaderLength = calculateAsymAlgSecurityHeaderLength(channel);
  297. /* Pad the message. Also if securitymode is only sign, since we are using
  298. * asymmetric communication to exchange keys and thus need to encrypt. */
  299. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  300. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  301. const UA_Byte *buf_body_start =
  302. &buf.data[UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH +
  303. UA_SEQUENCE_HEADER_LENGTH + securityHeaderLength];
  304. const size_t bytesToWrite =
  305. (uintptr_t)buf_pos - (uintptr_t)buf_body_start + UA_SEQUENCE_HEADER_LENGTH;
  306. UA_Byte paddingSize = 0;
  307. UA_Byte extraPaddingSize = 0;
  308. UA_UInt16 totalPaddingSize =
  309. calculatePaddingAsym(securityPolicy, channel->channelContext,
  310. bytesToWrite, &paddingSize, &extraPaddingSize);
  311. // This is <= because the paddingSize byte also has to be written.
  312. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  313. *buf_pos = paddingSize;
  314. ++buf_pos;
  315. }
  316. if(securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  317. getRemoteKeyLength(securityPolicy, channel->channelContext) > 2048) {
  318. *buf_pos = extraPaddingSize;
  319. ++buf_pos;
  320. }
  321. }
  322. /* The total message length */
  323. size_t pre_sig_length = (uintptr_t)buf_pos - (uintptr_t)buf.data;
  324. size_t total_length = pre_sig_length;
  325. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  326. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  327. total_length += securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  328. getLocalSignatureSize(securityPolicy, channel->channelContext);
  329. /* Encode the headers at the beginning of the message */
  330. UA_Byte *header_pos = buf.data;
  331. size_t dataToEncryptLength =
  332. total_length - (UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength);
  333. UA_SecureConversationMessageHeader respHeader;
  334. respHeader.messageHeader.messageTypeAndChunkType = UA_MESSAGETYPE_OPN + UA_CHUNKTYPE_FINAL;
  335. respHeader.messageHeader.messageSize = (UA_UInt32)
  336. (total_length + UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(securityPolicy,
  337. channel->channelContext,
  338. dataToEncryptLength));
  339. respHeader.secureChannelId = channel->securityToken.channelId;
  340. retval = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  341. &header_pos, &buf_end, NULL, NULL);
  342. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  343. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  344. asymHeader.securityPolicyUri = channel->securityPolicy->policyUri;
  345. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  346. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  347. asymHeader.senderCertificate = channel->securityPolicy->localCertificate;
  348. asymHeader.receiverCertificateThumbprint.length = 20;
  349. asymHeader.receiverCertificateThumbprint.data = channel->remoteCertificateThumbprint;
  350. }
  351. retval |= UA_encodeBinary(&asymHeader, &UA_TRANSPORT[UA_TRANSPORT_ASYMMETRICALGORITHMSECURITYHEADER],
  352. &header_pos, &buf_end, NULL, NULL);
  353. UA_SequenceHeader seqHeader;
  354. seqHeader.requestId = requestId;
  355. seqHeader.sequenceNumber = UA_atomic_addUInt32(&channel->sendSequenceNumber, 1);
  356. retval |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  357. &header_pos, &buf_end, NULL, NULL);
  358. /* Did encoding the header succeed? */
  359. if(retval != UA_STATUSCODE_GOOD) {
  360. connection->releaseSendBuffer(connection, &buf);
  361. return retval;
  362. }
  363. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  364. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  365. /* Sign message */
  366. const UA_ByteString dataToSign = {pre_sig_length, buf.data};
  367. size_t sigsize = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  368. getLocalSignatureSize(securityPolicy, channel->channelContext);
  369. UA_ByteString signature = {sigsize, buf.data + pre_sig_length};
  370. retval = securityPolicy->asymmetricModule.cryptoModule.signatureAlgorithm.
  371. sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  372. if(retval != UA_STATUSCODE_GOOD) {
  373. connection->releaseSendBuffer(connection, &buf);
  374. return retval;
  375. }
  376. /* Specification part 6, 6.7.4: The OpenSecureChannel Messages are
  377. * signed and encrypted if the SecurityMode is not None (even if the
  378. * SecurityMode is SignOnly). */
  379. size_t unencrypted_length =
  380. UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH + securityHeaderLength;
  381. UA_ByteString dataToEncrypt = {total_length - unencrypted_length,
  382. &buf.data[unencrypted_length]};
  383. retval = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  384. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  385. if(retval != UA_STATUSCODE_GOOD) {
  386. connection->releaseSendBuffer(connection, &buf);
  387. return retval;
  388. }
  389. }
  390. /* Send the message, the buffer is freed in the network layer */
  391. buf.length = respHeader.messageHeader.messageSize;
  392. retval = connection->send(connection, &buf);
  393. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  394. retval |= sendAsym_sendFailure
  395. #endif
  396. return retval;
  397. }
  398. /**************************/
  399. /* Send Symmetric Message */
  400. /**************************/
  401. static UA_UInt16
  402. calculatePaddingSym(const UA_SecurityPolicy *securityPolicy, const void *channelContext,
  403. size_t bytesToWrite, UA_Byte *paddingSize, UA_Byte *extraPaddingSize) {
  404. size_t encryptionBlockSize = securityPolicy->symmetricModule.cryptoModule.encryptionAlgorithm.
  405. getLocalBlockSize(securityPolicy, channelContext);
  406. size_t signatureSize = securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  407. getLocalSignatureSize(securityPolicy, channelContext);
  408. UA_UInt16 padding = (UA_UInt16)(encryptionBlockSize - ((bytesToWrite + signatureSize + 1) % encryptionBlockSize));
  409. *paddingSize = (UA_Byte)padding;
  410. *extraPaddingSize = (UA_Byte)(padding >> 8);
  411. return padding;
  412. }
  413. static void
  414. setBufPos(UA_MessageContext *mc) {
  415. const UA_SecureChannel *channel = mc->channel;
  416. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  417. /* Forward the data pointer so that the payload is encoded after the
  418. * message header */
  419. mc->buf_pos = &mc->messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  420. mc->buf_end = &mc->messageBuffer.data[mc->messageBuffer.length];
  421. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  422. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  423. mc->buf_end -= securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  424. getLocalSignatureSize(securityPolicy, channel->channelContext);
  425. /* Hide a byte needed for padding */
  426. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  427. mc->buf_end -= 2;
  428. }
  429. static UA_StatusCode
  430. sendSymmetricChunk(UA_MessageContext *mc) {
  431. UA_StatusCode res = UA_STATUSCODE_GOOD;
  432. UA_SecureChannel *const channel = mc->channel;
  433. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  434. UA_Connection *const connection = channel->connection;
  435. if(!connection)
  436. return UA_STATUSCODE_BADINTERNALERROR;
  437. /* Will this chunk surpass the capacity of the SecureChannel for the message? */
  438. UA_Byte *buf_body_start = mc->messageBuffer.data + UA_SECURE_MESSAGE_HEADER_LENGTH;
  439. const UA_Byte *buf_body_end = mc->buf_pos;
  440. size_t bodyLength = (uintptr_t)buf_body_end - (uintptr_t)buf_body_start;
  441. mc->messageSizeSoFar += bodyLength;
  442. mc->chunksSoFar++;
  443. if(mc->messageSizeSoFar > connection->remoteConf.maxMessageSize &&
  444. connection->remoteConf.maxMessageSize != 0)
  445. res = UA_STATUSCODE_BADRESPONSETOOLARGE;
  446. if(mc->chunksSoFar > connection->remoteConf.maxChunkCount &&
  447. connection->remoteConf.maxChunkCount != 0)
  448. res = UA_STATUSCODE_BADRESPONSETOOLARGE;
  449. if(res != UA_STATUSCODE_GOOD) {
  450. connection->releaseSendBuffer(channel->connection, &mc->messageBuffer);
  451. return res;
  452. }
  453. /* Pad the message. The bytes for the padding and signature were removed
  454. * from buf_end before encoding the payload. So we don't check here. */
  455. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  456. size_t bytesToWrite = bodyLength + UA_SEQUENCE_HEADER_LENGTH;
  457. UA_Byte paddingSize = 0;
  458. UA_Byte extraPaddingSize = 0;
  459. UA_UInt16 totalPaddingSize =
  460. calculatePaddingSym(securityPolicy, channel->channelContext,
  461. bytesToWrite, &paddingSize, &extraPaddingSize);
  462. // This is <= because the paddingSize byte also has to be written.
  463. for(UA_UInt16 i = 0; i <= totalPaddingSize; ++i) {
  464. *mc->buf_pos = paddingSize;
  465. ++(mc->buf_pos);
  466. }
  467. if(extraPaddingSize > 0) {
  468. *mc->buf_pos = extraPaddingSize;
  469. ++(mc->buf_pos);
  470. }
  471. }
  472. /* The total message length */
  473. size_t pre_sig_length = (uintptr_t)(mc->buf_pos) - (uintptr_t)mc->messageBuffer.data;
  474. size_t total_length = pre_sig_length;
  475. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  476. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  477. total_length += securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  478. getLocalSignatureSize(securityPolicy, channel->channelContext);
  479. mc->messageBuffer.length = total_length; /* For giving the buffer to the network layer */
  480. /* Encode the chunk headers at the beginning of the buffer */
  481. UA_assert(res == UA_STATUSCODE_GOOD);
  482. UA_Byte *header_pos = mc->messageBuffer.data;
  483. UA_SecureConversationMessageHeader respHeader;
  484. respHeader.secureChannelId = channel->securityToken.channelId;
  485. respHeader.messageHeader.messageTypeAndChunkType = mc->messageType;
  486. respHeader.messageHeader.messageSize = (UA_UInt32)total_length;
  487. if(mc->final)
  488. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  489. else
  490. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  491. res = UA_encodeBinary(&respHeader, &UA_TRANSPORT[UA_TRANSPORT_SECURECONVERSATIONMESSAGEHEADER],
  492. &header_pos, &mc->buf_end, NULL, NULL);
  493. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  494. symSecHeader.tokenId = channel->securityToken.tokenId;
  495. res |= UA_encodeBinary(&symSecHeader.tokenId,
  496. &UA_TRANSPORT[UA_TRANSPORT_SYMMETRICALGORITHMSECURITYHEADER],
  497. &header_pos, &mc->buf_end, NULL, NULL);
  498. UA_SequenceHeader seqHeader;
  499. seqHeader.requestId = mc->requestId;
  500. seqHeader.sequenceNumber = UA_atomic_addUInt32(&channel->sendSequenceNumber, 1);
  501. res |= UA_encodeBinary(&seqHeader, &UA_TRANSPORT[UA_TRANSPORT_SEQUENCEHEADER],
  502. &header_pos, &mc->buf_end, NULL, NULL);
  503. /* Sign message */
  504. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  505. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  506. UA_ByteString dataToSign = mc->messageBuffer;
  507. dataToSign.length = pre_sig_length;
  508. UA_ByteString signature;
  509. signature.length = securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  510. getLocalSignatureSize(securityPolicy, channel->channelContext);
  511. signature.data = mc->buf_pos;
  512. res |= securityPolicy->symmetricModule.cryptoModule.signatureAlgorithm.
  513. sign(securityPolicy, channel->channelContext, &dataToSign, &signature);
  514. }
  515. /* Encrypt message */
  516. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  517. UA_ByteString dataToEncrypt;
  518. dataToEncrypt.data = mc->messageBuffer.data + UA_SECUREMH_AND_SYMALGH_LENGTH;
  519. dataToEncrypt.length = total_length - UA_SECUREMH_AND_SYMALGH_LENGTH;
  520. res |= securityPolicy->symmetricModule.cryptoModule.encryptionAlgorithm.
  521. encrypt(securityPolicy, channel->channelContext, &dataToEncrypt);
  522. }
  523. if(res != UA_STATUSCODE_GOOD) {
  524. connection->releaseSendBuffer(channel->connection, &mc->messageBuffer);
  525. return res;
  526. }
  527. /* Send the chunk, the buffer is freed in the network layer */
  528. return connection->send(channel->connection, &mc->messageBuffer);
  529. }
  530. /* Callback from the encoding layer. Send the chunk and replace the buffer. */
  531. static UA_StatusCode
  532. sendSymmetricEncodingCallback(void *data, UA_Byte **buf_pos, const UA_Byte **buf_end) {
  533. /* Set buf values from encoding in the messagecontext */
  534. UA_MessageContext *mc = (UA_MessageContext *)data;
  535. mc->buf_pos = *buf_pos;
  536. mc->buf_end = *buf_end;
  537. /* Send out */
  538. UA_StatusCode retval = sendSymmetricChunk(mc);
  539. if(retval != UA_STATUSCODE_GOOD)
  540. return retval;
  541. /* Set a new buffer for the next chunk */
  542. UA_Connection *connection = mc->channel->connection;
  543. retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  544. &mc->messageBuffer);
  545. if(retval != UA_STATUSCODE_GOOD)
  546. return retval;
  547. /* Hide bytes for header, padding and signature */
  548. setBufPos(mc);
  549. *buf_pos = mc->buf_pos;
  550. *buf_end = mc->buf_end;
  551. return UA_STATUSCODE_GOOD;
  552. }
  553. UA_StatusCode
  554. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  555. UA_UInt32 requestId, UA_MessageType messageType) {
  556. UA_Connection *connection = channel->connection;
  557. if(!connection)
  558. return UA_STATUSCODE_BADINTERNALERROR;
  559. if(messageType != UA_MESSAGETYPE_MSG && messageType != UA_MESSAGETYPE_CLO)
  560. return UA_STATUSCODE_BADINTERNALERROR;
  561. /* Create the chunking info structure */
  562. mc->channel = channel;
  563. mc->requestId = requestId;
  564. mc->chunksSoFar = 0;
  565. mc->messageSizeSoFar = 0;
  566. mc->final = false;
  567. mc->messageBuffer = UA_BYTESTRING_NULL;
  568. mc->messageType = messageType;
  569. /* Minimum required size */
  570. if(connection->localConf.sendBufferSize <= UA_SECURE_MESSAGE_HEADER_LENGTH)
  571. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  572. /* Allocate the message buffer */
  573. UA_StatusCode retval =
  574. connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  575. &mc->messageBuffer);
  576. if(retval != UA_STATUSCODE_GOOD)
  577. return retval;
  578. /* Hide bytes for header, padding and signature */
  579. setBufPos(mc);
  580. return UA_STATUSCODE_GOOD;
  581. }
  582. UA_StatusCode
  583. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  584. const UA_DataType *contentType) {
  585. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  586. sendSymmetricEncodingCallback, mc);
  587. if(retval != UA_STATUSCODE_GOOD) {
  588. /* TODO: Send the abort message */
  589. if(mc->messageBuffer.length > 0) {
  590. UA_Connection *connection = mc->channel->connection;
  591. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  592. }
  593. }
  594. return retval;
  595. }
  596. UA_StatusCode
  597. UA_MessageContext_finish(UA_MessageContext *mc) {
  598. mc->final = true;
  599. return sendSymmetricChunk(mc);
  600. }
  601. void
  602. UA_MessageContext_abort(UA_MessageContext *mc) {
  603. UA_Connection *connection = mc->channel->connection;
  604. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  605. }
  606. UA_StatusCode
  607. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  608. UA_MessageType messageType, void *payload,
  609. const UA_DataType *payloadType) {
  610. if(!channel || !payload || !payloadType)
  611. return UA_STATUSCODE_BADINTERNALERROR;
  612. if(channel->connection) {
  613. if(channel->connection->state == UA_CONNECTION_CLOSED)
  614. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  615. }
  616. UA_MessageContext mc;
  617. UA_StatusCode retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
  618. if(retval != UA_STATUSCODE_GOOD)
  619. return retval;
  620. /* Assert's required for clang-analyzer */
  621. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  622. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  623. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  624. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  625. if(retval != UA_STATUSCODE_GOOD)
  626. return retval;
  627. retval = UA_MessageContext_encode(&mc, payload, payloadType);
  628. if(retval != UA_STATUSCODE_GOOD)
  629. return retval;
  630. return UA_MessageContext_finish(&mc);
  631. }
  632. /*****************************/
  633. /* Assemble Complete Message */
  634. /*****************************/
  635. static void
  636. UA_SecureChannel_removeChunks(UA_SecureChannel *channel, UA_UInt32 requestId) {
  637. struct MessageEntry *me;
  638. LIST_FOREACH(me, &channel->chunks, pointers) {
  639. if(me->requestId == requestId) {
  640. struct ChunkPayload *cp, *temp_cp;
  641. SIMPLEQ_FOREACH_SAFE(cp, &me->chunkPayload, pointers, temp_cp) {
  642. UA_ByteString_deleteMembers(&cp->bytes);
  643. UA_free(cp);
  644. }
  645. LIST_REMOVE(me, pointers);
  646. UA_free(me);
  647. return;
  648. }
  649. }
  650. }
  651. static UA_StatusCode
  652. appendChunk(struct MessageEntry *messageEntry, const UA_ByteString *chunkBody) {
  653. struct ChunkPayload* cp = (struct ChunkPayload*)UA_malloc(sizeof(struct ChunkPayload));
  654. UA_StatusCode retval = UA_ByteString_copy(chunkBody, &cp->bytes);
  655. if (retval != UA_STATUSCODE_GOOD)
  656. return retval;
  657. SIMPLEQ_INSERT_TAIL(&messageEntry->chunkPayload, cp, pointers);
  658. messageEntry->chunkPayloadSize += chunkBody->length;
  659. return UA_STATUSCODE_GOOD;
  660. }
  661. static UA_StatusCode
  662. UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  663. const UA_ByteString *chunkBody) {
  664. struct MessageEntry *me;
  665. LIST_FOREACH(me, &channel->chunks, pointers) {
  666. if(me->requestId == requestId)
  667. break;
  668. }
  669. /* No chunkentry on the channel, create one */
  670. if(!me) {
  671. me = (struct MessageEntry *)UA_malloc(sizeof(struct MessageEntry));
  672. if(!me)
  673. return UA_STATUSCODE_BADOUTOFMEMORY;
  674. memset(me, 0, sizeof(struct MessageEntry));
  675. me->requestId = requestId;
  676. SIMPLEQ_INIT(&me->chunkPayload);
  677. LIST_INSERT_HEAD(&channel->chunks, me, pointers);
  678. }
  679. return appendChunk(me, chunkBody);
  680. }
  681. static UA_StatusCode
  682. UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  683. const UA_ByteString *chunkBody, UA_MessageType messageType,
  684. UA_ProcessMessageCallback callback, void *application) {
  685. struct MessageEntry *messageEntry;
  686. LIST_FOREACH(messageEntry, &channel->chunks, pointers) {
  687. if(messageEntry->requestId == requestId)
  688. break;
  689. }
  690. UA_ByteString bytes;
  691. if(!messageEntry) {
  692. bytes = *chunkBody;
  693. } else {
  694. UA_StatusCode retval = appendChunk(messageEntry, chunkBody);
  695. if(retval != UA_STATUSCODE_GOOD)
  696. return retval;
  697. UA_ByteString_init(&bytes);
  698. bytes.data = (UA_Byte*) UA_malloc(messageEntry->chunkPayloadSize);
  699. if (!bytes.data)
  700. return UA_STATUSCODE_BADOUTOFMEMORY;
  701. struct ChunkPayload *cp, *temp_cp;
  702. size_t curPos = 0;
  703. SIMPLEQ_FOREACH_SAFE(cp, &messageEntry->chunkPayload, pointers, temp_cp) {
  704. memcpy(&bytes.data[curPos], cp->bytes.data, cp->bytes.length);
  705. curPos += cp->bytes.length;
  706. UA_ByteString_deleteMembers(&cp->bytes);
  707. UA_free(cp);
  708. }
  709. bytes.length = messageEntry->chunkPayloadSize;
  710. LIST_REMOVE(messageEntry, pointers);
  711. UA_free(messageEntry);
  712. }
  713. UA_StatusCode retval = callback(application, channel, messageType, requestId, &bytes);
  714. if(messageEntry)
  715. UA_ByteString_deleteMembers(&bytes);
  716. return retval;
  717. }
  718. /****************************/
  719. /* Process a received Chunk */
  720. /****************************/
  721. static UA_StatusCode
  722. decryptChunk(UA_SecureChannel *channel, const UA_SecurityPolicyCryptoModule *cryptoModule,
  723. UA_ByteString *chunk, size_t offset, UA_UInt32 *requestId, UA_UInt32 *sequenceNumber,
  724. UA_ByteString *payload, UA_MessageType messageType) {
  725. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  726. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  727. size_t chunkSizeAfterDecryption = chunk->length;
  728. /* Decrypt the chunk. Always decrypt opn messages if mode not none */
  729. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  730. messageType == UA_MESSAGETYPE_OPN) {
  731. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  732. size_t sizeBeforeDecryption = cipherText.length;
  733. retval = cryptoModule->encryptionAlgorithm.decrypt(securityPolicy, channel->channelContext, &cipherText);
  734. chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  735. if(retval != UA_STATUSCODE_GOOD)
  736. return retval;
  737. }
  738. /* Verify the chunk signature */
  739. size_t sigsize = 0;
  740. size_t paddingSize = 0;
  741. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  742. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  743. messageType == UA_MESSAGETYPE_OPN) {
  744. /* Compute the padding size */
  745. sigsize = cryptoModule->signatureAlgorithm.getRemoteSignatureSize(securityPolicy, channel->channelContext);
  746. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  747. (messageType == UA_MESSAGETYPE_OPN &&
  748. channel->securityMode > UA_MESSAGESECURITYMODE_NONE)) {
  749. paddingSize = (size_t)chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  750. size_t keyLength =
  751. cryptoModule->encryptionAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  752. if(keyLength > 2048) {
  753. paddingSize <<= 8; /* Extra padding size */
  754. paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  755. // see comment below but for extraPaddingSize
  756. paddingSize += 1;
  757. }
  758. // we need to add one to the padding size since the paddingSize byte itself need to be removed as well.
  759. // TODO: write unit test for correct padding calculation
  760. paddingSize += 1;
  761. }
  762. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  763. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  764. /* Verify the signature */
  765. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  766. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  767. retval = cryptoModule->signatureAlgorithm.verify(securityPolicy, channel->channelContext,
  768. &chunkDataToVerify, &signature);
  769. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  770. retval |= decrypt_verifySignatureFailure;
  771. #endif
  772. if(retval != UA_STATUSCODE_GOOD)
  773. return retval;
  774. }
  775. /* Decode the sequence header */
  776. UA_SequenceHeader sequenceHeader;
  777. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  778. if(retval != UA_STATUSCODE_GOOD)
  779. return retval;
  780. if(offset + paddingSize + sigsize >= chunk->length)
  781. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  782. *requestId = sequenceHeader.requestId;
  783. *sequenceNumber = sequenceHeader.sequenceNumber;
  784. payload->data = chunk->data + offset;
  785. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  786. return UA_STATUSCODE_GOOD;
  787. }
  788. typedef UA_StatusCode(*UA_SequenceNumberCallback)(UA_SecureChannel *channel,
  789. UA_UInt32 sequenceNumber);
  790. static UA_StatusCode
  791. processSequenceNumberAsym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  792. channel->receiveSequenceNumber = sequenceNumber;
  793. return UA_STATUSCODE_GOOD;
  794. }
  795. static UA_StatusCode
  796. processSequenceNumberSym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  797. /* Failure mode hook for unit tests */
  798. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  799. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  800. return processSym_seqNumberFailure;
  801. #endif
  802. /* Does the sequence number match? */
  803. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  804. /* FIXME: Remove magic numbers :( */
  805. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  806. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  807. else
  808. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  809. }
  810. ++channel->receiveSequenceNumber;
  811. return UA_STATUSCODE_GOOD;
  812. }
  813. static UA_StatusCode
  814. checkAsymHeader(UA_SecureChannel *const channel,
  815. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  816. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  817. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  818. if(!UA_ByteString_equal(&securityPolicy->policyUri, &asymHeader->securityPolicyUri)) {
  819. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  820. }
  821. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  822. /* Something like this
  823. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  824. if(retval != UA_STATUSCODE_GOOD)
  825. return retval;
  826. */
  827. retval = securityPolicy->asymmetricModule.
  828. compareCertificateThumbprint(securityPolicy, &asymHeader->receiverCertificateThumbprint);
  829. if(retval != UA_STATUSCODE_GOOD) {
  830. return retval;
  831. }
  832. return UA_STATUSCODE_GOOD;
  833. }
  834. static UA_StatusCode
  835. checkSymHeader(UA_SecureChannel *const channel,
  836. const UA_UInt32 tokenId) {
  837. if(tokenId != channel->securityToken.tokenId) {
  838. if(tokenId != channel->nextSecurityToken.tokenId)
  839. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  840. return UA_SecureChannel_revolveTokens(channel);
  841. }
  842. return UA_STATUSCODE_GOOD;
  843. }
  844. UA_StatusCode
  845. UA_SecureChannel_processChunk(UA_SecureChannel *channel, UA_ByteString *chunk,
  846. UA_ProcessMessageCallback callback,
  847. void *application) {
  848. /* Decode message header */
  849. size_t offset = 0;
  850. UA_SecureConversationMessageHeader messageHeader;
  851. UA_StatusCode retval =
  852. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  853. if(retval != UA_STATUSCODE_GOOD)
  854. return retval;
  855. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  856. /* The wrong ChannelId. Non-opened channels have the id zero. */
  857. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  858. channel->state != UA_SECURECHANNELSTATE_FRESH)
  859. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  860. #endif
  861. UA_MessageType messageType = (UA_MessageType)
  862. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  863. UA_ChunkType chunkType = (UA_ChunkType)
  864. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  865. /* ERR message (not encrypted) */
  866. UA_UInt32 requestId = 0;
  867. UA_UInt32 sequenceNumber = 0;
  868. UA_ByteString chunkPayload;
  869. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  870. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  871. switch(messageType) {
  872. case UA_MESSAGETYPE_ERR: {
  873. if(chunkType != UA_CHUNKTYPE_FINAL)
  874. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  875. chunkPayload.length = chunk->length - offset;
  876. chunkPayload.data = chunk->data + offset;
  877. return callback(application, channel, messageType, requestId, &chunkPayload);
  878. }
  879. case UA_MESSAGETYPE_MSG:
  880. case UA_MESSAGETYPE_CLO: {
  881. /* Decode and check the symmetric security header (tokenId) */
  882. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  883. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  884. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  885. &symmetricSecurityHeader);
  886. if(retval != UA_STATUSCODE_GOOD)
  887. return retval;
  888. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  889. /* Help fuzzing by always setting the correct tokenId */
  890. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  891. #endif
  892. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId);
  893. if(retval != UA_STATUSCODE_GOOD)
  894. return retval;
  895. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  896. sequenceNumberCallback = processSequenceNumberSym;
  897. break;
  898. }
  899. case UA_MESSAGETYPE_OPN: {
  900. /* Chunking not allowed for OPN */
  901. if(chunkType != UA_CHUNKTYPE_FINAL)
  902. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  903. /* Decode the asymmetric algorithm security header and call the callback
  904. * to perform checks. */
  905. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  906. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  907. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  908. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  909. if(retval != UA_STATUSCODE_GOOD)
  910. return retval;
  911. retval = checkAsymHeader(channel, &asymHeader);
  912. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  913. if(retval != UA_STATUSCODE_GOOD)
  914. return retval;
  915. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  916. sequenceNumberCallback = processSequenceNumberAsym;
  917. break;
  918. }
  919. default:return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  920. }
  921. /* Decrypt message */
  922. UA_assert(cryptoModule != NULL);
  923. retval = decryptChunk(channel, cryptoModule, chunk, offset, &requestId,
  924. &sequenceNumber, &chunkPayload, messageType);
  925. if(retval != UA_STATUSCODE_GOOD)
  926. return retval;
  927. /* Check the sequence number */
  928. if(sequenceNumberCallback == NULL)
  929. return UA_STATUSCODE_BADINTERNALERROR;
  930. retval = sequenceNumberCallback(channel, sequenceNumber);
  931. /* Skip sequence number checking for fuzzer to improve coverage */
  932. if(retval != UA_STATUSCODE_GOOD) {
  933. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  934. return retval;
  935. #else
  936. retval = UA_STATUSCODE_GOOD;
  937. #endif
  938. }
  939. /* Process the payload */
  940. if(chunkType == UA_CHUNKTYPE_FINAL) {
  941. retval = UA_SecureChannel_finalizeChunk(channel, requestId, &chunkPayload,
  942. messageType, callback, application);
  943. } else if(chunkType == UA_CHUNKTYPE_INTERMEDIATE) {
  944. retval = UA_SecureChannel_appendChunk(channel, requestId, &chunkPayload);
  945. } else if(chunkType == UA_CHUNKTYPE_ABORT) {
  946. UA_SecureChannel_removeChunks(channel, requestId);
  947. } else {
  948. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  949. }
  950. return retval;
  951. }
  952. /* Functionality used by both the SecureChannel and the SecurityPolicy */
  953. size_t
  954. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(const UA_SecurityPolicy *securityPolicy,
  955. const void *channelContext,
  956. size_t maxEncryptionLength) {
  957. if(maxEncryptionLength == 0)
  958. return 0;
  959. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  960. getRemotePlainTextBlockSize(securityPolicy, channelContext);
  961. size_t encryptedBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  962. getRemoteBlockSize(securityPolicy, channelContext);
  963. if(plainTextBlockSize == 0)
  964. return 0;
  965. size_t maxNumberOfBlocks = maxEncryptionLength / plainTextBlockSize;
  966. return maxNumberOfBlocks * (encryptedBlockSize - plainTextBlockSize);
  967. }