ua_securechannel.c 50 KB

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