ua_securechannel.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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->localConf.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->remoteConf.maxMessageSize &&
  468. connection->remoteConf.maxMessageSize != 0)
  469. res = UA_STATUSCODE_BADRESPONSETOOLARGE;
  470. if(mc->chunksSoFar > connection->remoteConf.maxChunkCount &&
  471. connection->remoteConf.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->localConf.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. /* Minimum required size */
  594. if(connection->localConf.sendBufferSize <= UA_SECURE_MESSAGE_HEADER_LENGTH)
  595. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  596. /* Allocate the message buffer */
  597. UA_StatusCode retval =
  598. connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  599. &mc->messageBuffer);
  600. if(retval != UA_STATUSCODE_GOOD)
  601. return retval;
  602. /* Hide bytes for header, padding and signature */
  603. setBufPos(mc);
  604. return UA_STATUSCODE_GOOD;
  605. }
  606. UA_StatusCode
  607. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  608. const UA_DataType *contentType) {
  609. UA_StatusCode retval = UA_encodeBinary(content, contentType, &mc->buf_pos, &mc->buf_end,
  610. sendSymmetricEncodingCallback, mc);
  611. if(retval != UA_STATUSCODE_GOOD) {
  612. /* TODO: Send the abort message */
  613. if(mc->messageBuffer.length > 0) {
  614. UA_Connection *connection = mc->channel->connection;
  615. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  616. }
  617. }
  618. return retval;
  619. }
  620. UA_StatusCode
  621. UA_MessageContext_finish(UA_MessageContext *mc) {
  622. mc->final = true;
  623. return sendSymmetricChunk(mc);
  624. }
  625. void
  626. UA_MessageContext_abort(UA_MessageContext *mc) {
  627. UA_Connection *connection = mc->channel->connection;
  628. connection->releaseSendBuffer(connection, &mc->messageBuffer);
  629. }
  630. UA_StatusCode
  631. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  632. UA_MessageType messageType, void *payload,
  633. const UA_DataType *payloadType) {
  634. if(!channel || !payload || !payloadType)
  635. return UA_STATUSCODE_BADINTERNALERROR;
  636. if(channel->connection) {
  637. if(channel->connection->state == UA_CONNECTION_CLOSED)
  638. return UA_STATUSCODE_BADCONNECTIONCLOSED;
  639. }
  640. UA_MessageContext mc;
  641. UA_StatusCode retval = UA_MessageContext_begin(&mc, channel, requestId, messageType);
  642. if(retval != UA_STATUSCODE_GOOD)
  643. return retval;
  644. /* Assert's required for clang-analyzer */
  645. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  646. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  647. UA_NodeId typeId = UA_NODEID_NUMERIC(0, payloadType->binaryEncodingId);
  648. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  649. if(retval != UA_STATUSCODE_GOOD)
  650. return retval;
  651. retval = UA_MessageContext_encode(&mc, payload, payloadType);
  652. if(retval != UA_STATUSCODE_GOOD)
  653. return retval;
  654. return UA_MessageContext_finish(&mc);
  655. }
  656. /*****************************/
  657. /* Assemble Complete Message */
  658. /*****************************/
  659. static UA_StatusCode
  660. addChunkPayload(UA_SecureChannel *channel, UA_UInt32 requestId,
  661. UA_MessageType messageType, UA_ByteString *chunkPayload,
  662. UA_Boolean final) {
  663. UA_Message *latest = TAILQ_LAST(&channel->messages, UA_MessageQueue);
  664. if(latest) {
  665. if(latest->requestId != requestId) {
  666. /* Start of a new message */
  667. if(!latest->final)
  668. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  669. latest = NULL;
  670. } else {
  671. if(latest->messageType != messageType) /* MessageType mismatch */
  672. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  673. if(latest->final) /* Correct message, but already finalized */
  674. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  675. }
  676. }
  677. /* Create a new message entry */
  678. if(!latest) {
  679. latest = (UA_Message*)UA_malloc(sizeof(UA_Message));
  680. if(!latest)
  681. return UA_STATUSCODE_BADOUTOFMEMORY;
  682. memset(latest, 0, sizeof(UA_Message));
  683. latest->requestId = requestId;
  684. latest->messageType = messageType;
  685. SIMPLEQ_INIT(&latest->chunkPayloads);
  686. TAILQ_INSERT_TAIL(&channel->messages, latest, pointers);
  687. }
  688. /* Test against the connection settings */
  689. const UA_ConnectionConfig *config = &channel->connection->localConf;
  690. if(config->maxChunkCount > 0 &&
  691. config->maxChunkCount <= latest->chunkPayloadsSize)
  692. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  693. if(config->maxMessageSize > 0 &&
  694. config->maxMessageSize < latest->messageSize + chunkPayload->length)
  695. return UA_STATUSCODE_BADRESPONSETOOLARGE;
  696. /* Create a new chunk entry */
  697. UA_ChunkPayload* cp = (UA_ChunkPayload*)UA_malloc(sizeof(UA_ChunkPayload));
  698. if(!cp)
  699. return UA_STATUSCODE_BADOUTOFMEMORY;
  700. cp->bytes = *chunkPayload;
  701. cp->copied = false;
  702. /* Add the chunk */
  703. SIMPLEQ_INSERT_TAIL(&latest->chunkPayloads, cp, pointers);
  704. latest->chunkPayloadsSize += 1;
  705. latest->messageSize += chunkPayload->length;
  706. latest->final = final;
  707. return UA_STATUSCODE_GOOD;
  708. }
  709. static UA_StatusCode
  710. processMessage(UA_SecureChannel *channel, const UA_Message *message,
  711. void *application, UA_ProcessMessageCallback callback) {
  712. if(message->chunkPayloadsSize == 1) {
  713. /* No need to combine chunks */
  714. UA_ChunkPayload *cp = SIMPLEQ_FIRST(&message->chunkPayloads);
  715. callback(application, channel, message->messageType, message->requestId, &cp->bytes);
  716. } else {
  717. /* Allocate memory */
  718. UA_ByteString bytes;
  719. bytes.data = (UA_Byte*) UA_malloc(message->messageSize);
  720. if(!bytes.data) {
  721. UA_LOG_WARNING(channel->securityPolicy->logger, UA_LOGCATEGORY_SECURECHANNEL,
  722. "Could not allocate the memory to assemble the message");
  723. return UA_STATUSCODE_BADOUTOFMEMORY;
  724. }
  725. bytes.length = message->messageSize;
  726. /* Assemble the full message */
  727. size_t curPos = 0;
  728. UA_ChunkPayload *cp;
  729. SIMPLEQ_FOREACH(cp, &message->chunkPayloads, pointers) {
  730. memcpy(&bytes.data[curPos], cp->bytes.data, cp->bytes.length);
  731. curPos += cp->bytes.length;
  732. }
  733. /* Process the message */
  734. callback(application, channel, message->messageType, message->requestId, &bytes);
  735. UA_ByteString_deleteMembers(&bytes);
  736. }
  737. return UA_STATUSCODE_GOOD;
  738. }
  739. UA_StatusCode
  740. UA_SecureChannel_processCompleteMessages(UA_SecureChannel *channel, void *application,
  741. UA_ProcessMessageCallback callback) {
  742. UA_Message *me, *me_tmp;
  743. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  744. TAILQ_FOREACH_SAFE(me, &channel->messages, pointers, me_tmp) {
  745. /* Stop at the first incomplete message */
  746. if(!me->final)
  747. break;
  748. /* Remove the current message before processing */
  749. TAILQ_REMOVE(&channel->messages, me, pointers);
  750. /* Process */
  751. retval = processMessage(channel, me, application, callback);
  752. if(retval != UA_STATUSCODE_GOOD)
  753. break;
  754. /* Clean up the message */
  755. UA_ChunkPayload *cp;
  756. while((cp = SIMPLEQ_FIRST(&me->chunkPayloads))) {
  757. if(cp->copied)
  758. UA_ByteString_deleteMembers(&cp->bytes);
  759. SIMPLEQ_REMOVE_HEAD(&me->chunkPayloads, pointers);
  760. UA_free(cp);
  761. }
  762. UA_free(me);
  763. }
  764. return retval;
  765. }
  766. /****************************/
  767. /* Process a received Chunk */
  768. /****************************/
  769. /* Sets the payload to a pointer inside the chunk buffer. Returns the requestId
  770. * and the sequenceNumber */
  771. static UA_StatusCode
  772. decryptChunk(const UA_SecureChannel *channel, const UA_SecurityPolicyCryptoModule *cryptoModule,
  773. UA_MessageType messageType, const UA_ByteString *chunk, size_t offset,
  774. UA_UInt32 *requestId, UA_UInt32 *sequenceNumber, UA_ByteString *payload) {
  775. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  776. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  777. size_t chunkSizeAfterDecryption = chunk->length;
  778. /* Decrypt the chunk. Always decrypt opn messages if mode not none */
  779. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  780. messageType == UA_MESSAGETYPE_OPN) {
  781. UA_ByteString cipherText = {chunk->length - offset, chunk->data + offset};
  782. size_t sizeBeforeDecryption = cipherText.length;
  783. retval = cryptoModule->encryptionAlgorithm.decrypt(securityPolicy, channel->channelContext, &cipherText);
  784. chunkSizeAfterDecryption -= (sizeBeforeDecryption - cipherText.length);
  785. if(retval != UA_STATUSCODE_GOOD)
  786. return retval;
  787. }
  788. /* Verify the chunk signature */
  789. size_t sigsize = 0;
  790. size_t paddingSize = 0;
  791. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  792. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  793. messageType == UA_MESSAGETYPE_OPN) {
  794. /* Compute the padding size */
  795. sigsize = cryptoModule->signatureAlgorithm.getRemoteSignatureSize(securityPolicy, channel->channelContext);
  796. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT ||
  797. (messageType == UA_MESSAGETYPE_OPN &&
  798. channel->securityMode > UA_MESSAGESECURITYMODE_NONE)) {
  799. paddingSize = (size_t)chunk->data[chunkSizeAfterDecryption - sigsize - 1];
  800. size_t keyLength =
  801. cryptoModule->encryptionAlgorithm.getRemoteKeyLength(securityPolicy, channel->channelContext);
  802. if(keyLength > 2048) {
  803. paddingSize <<= 8; /* Extra padding size */
  804. paddingSize += chunk->data[chunkSizeAfterDecryption - sigsize - 2];
  805. // see comment below but for extraPaddingSize
  806. paddingSize += 1;
  807. }
  808. // we need to add one to the padding size since the paddingSize byte itself need to be removed as well.
  809. // TODO: write unit test for correct padding calculation
  810. paddingSize += 1;
  811. }
  812. if(offset + paddingSize + sigsize >= chunkSizeAfterDecryption)
  813. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  814. /* Verify the signature */
  815. const UA_ByteString chunkDataToVerify = {chunkSizeAfterDecryption - sigsize, chunk->data};
  816. const UA_ByteString signature = {sigsize, chunk->data + chunkSizeAfterDecryption - sigsize};
  817. retval = cryptoModule->signatureAlgorithm.verify(securityPolicy, channel->channelContext,
  818. &chunkDataToVerify, &signature);
  819. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  820. retval |= decrypt_verifySignatureFailure;
  821. #endif
  822. if(retval != UA_STATUSCODE_GOOD)
  823. return retval;
  824. }
  825. /* Decode the sequence header */
  826. UA_SequenceHeader sequenceHeader;
  827. retval = UA_SequenceHeader_decodeBinary(chunk, &offset, &sequenceHeader);
  828. if(retval != UA_STATUSCODE_GOOD)
  829. return retval;
  830. if(offset + paddingSize + sigsize >= chunk->length)
  831. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  832. *requestId = sequenceHeader.requestId;
  833. *sequenceNumber = sequenceHeader.sequenceNumber;
  834. payload->data = chunk->data + offset;
  835. payload->length = chunkSizeAfterDecryption - offset - sigsize - paddingSize;
  836. return UA_STATUSCODE_GOOD;
  837. }
  838. typedef UA_StatusCode(*UA_SequenceNumberCallback)(UA_SecureChannel *channel,
  839. UA_UInt32 sequenceNumber);
  840. static UA_StatusCode
  841. processSequenceNumberAsym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  842. channel->receiveSequenceNumber = sequenceNumber;
  843. return UA_STATUSCODE_GOOD;
  844. }
  845. static UA_StatusCode
  846. processSequenceNumberSym(UA_SecureChannel *const channel, UA_UInt32 sequenceNumber) {
  847. /* Failure mode hook for unit tests */
  848. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  849. if(processSym_seqNumberFailure != UA_STATUSCODE_GOOD)
  850. return processSym_seqNumberFailure;
  851. #endif
  852. /* Does the sequence number match? */
  853. if(sequenceNumber != channel->receiveSequenceNumber + 1) {
  854. /* FIXME: Remove magic numbers :( */
  855. if(channel->receiveSequenceNumber + 1 > 4294966271 && sequenceNumber < 1024)
  856. channel->receiveSequenceNumber = sequenceNumber - 1; /* Roll over */
  857. else
  858. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  859. }
  860. ++channel->receiveSequenceNumber;
  861. return UA_STATUSCODE_GOOD;
  862. }
  863. static UA_StatusCode
  864. checkAsymHeader(UA_SecureChannel *const channel,
  865. UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  866. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  867. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  868. if(!UA_ByteString_equal(&securityPolicy->policyUri, &asymHeader->securityPolicyUri)) {
  869. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  870. }
  871. // TODO: Verify certificate using certificate plugin. This will come with a new PR
  872. /* Something like this
  873. retval = certificateManager->verify(certificateStore??, &asymHeader->senderCertificate);
  874. if(retval != UA_STATUSCODE_GOOD)
  875. return retval;
  876. */
  877. retval = securityPolicy->asymmetricModule.
  878. compareCertificateThumbprint(securityPolicy, &asymHeader->receiverCertificateThumbprint);
  879. if(retval != UA_STATUSCODE_GOOD) {
  880. return retval;
  881. }
  882. return UA_STATUSCODE_GOOD;
  883. }
  884. static UA_StatusCode
  885. checkSymHeader(UA_SecureChannel *const channel,
  886. const UA_UInt32 tokenId) {
  887. if(tokenId != channel->securityToken.tokenId) {
  888. if(tokenId != channel->nextSecurityToken.tokenId)
  889. return UA_STATUSCODE_BADSECURECHANNELTOKENUNKNOWN;
  890. return UA_SecureChannel_revolveTokens(channel);
  891. }
  892. return UA_STATUSCODE_GOOD;
  893. }
  894. /* The chunk body begins after the SecureConversationMessageHeader */
  895. static UA_StatusCode
  896. decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk) {
  897. /* Decode the MessageHeader */
  898. size_t offset = 0;
  899. UA_SecureConversationMessageHeader messageHeader;
  900. UA_StatusCode retval =
  901. UA_SecureConversationMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  902. if(retval != UA_STATUSCODE_GOOD)
  903. return retval;
  904. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  905. /* The wrong ChannelId. Non-opened channels have the id zero. */
  906. if(messageHeader.secureChannelId != channel->securityToken.channelId &&
  907. channel->state != UA_SECURECHANNELSTATE_FRESH)
  908. return UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  909. #endif
  910. UA_MessageType messageType = (UA_MessageType)
  911. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  912. UA_ChunkType chunkType = (UA_ChunkType)
  913. (messageHeader.messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  914. UA_UInt32 requestId = 0;
  915. UA_UInt32 sequenceNumber = 0;
  916. UA_ByteString chunkPayload;
  917. const UA_SecurityPolicyCryptoModule *cryptoModule = NULL;
  918. UA_SequenceNumberCallback sequenceNumberCallback = NULL;
  919. switch(messageType) {
  920. /* ERR message (not encrypted) */
  921. case UA_MESSAGETYPE_ERR:
  922. if(chunkType != UA_CHUNKTYPE_FINAL)
  923. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  924. chunkPayload.length = chunk->length - offset;
  925. chunkPayload.data = chunk->data + offset;
  926. goto addPayload;
  927. /* MSG and CLO: Symmetric encryption */
  928. case UA_MESSAGETYPE_MSG:
  929. case UA_MESSAGETYPE_CLO: {
  930. /* Decode and check the symmetric security header (tokenId) */
  931. UA_SymmetricAlgorithmSecurityHeader symmetricSecurityHeader;
  932. UA_SymmetricAlgorithmSecurityHeader_init(&symmetricSecurityHeader);
  933. retval = UA_SymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset,
  934. &symmetricSecurityHeader);
  935. if(retval != UA_STATUSCODE_GOOD)
  936. return retval;
  937. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  938. /* Help fuzzing by always setting the correct tokenId */
  939. symmetricSecurityHeader.tokenId = channel->securityToken.tokenId;
  940. #endif
  941. retval = checkSymHeader(channel, symmetricSecurityHeader.tokenId);
  942. if(retval != UA_STATUSCODE_GOOD)
  943. return retval;
  944. cryptoModule = &channel->securityPolicy->symmetricModule.cryptoModule;
  945. sequenceNumberCallback = processSequenceNumberSym;
  946. break;
  947. }
  948. /* OPN: Asymmetric encryption */
  949. case UA_MESSAGETYPE_OPN: {
  950. /* Chunking not allowed for OPN */
  951. if(chunkType != UA_CHUNKTYPE_FINAL)
  952. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  953. /* Decode the asymmetric algorithm security header and call the callback
  954. * to perform checks. */
  955. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  956. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  957. offset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  958. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(chunk, &offset, &asymHeader);
  959. if(retval != UA_STATUSCODE_GOOD)
  960. return retval;
  961. retval = checkAsymHeader(channel, &asymHeader);
  962. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  963. if(retval != UA_STATUSCODE_GOOD)
  964. return retval;
  965. cryptoModule = &channel->securityPolicy->asymmetricModule.cryptoModule;
  966. sequenceNumberCallback = processSequenceNumberAsym;
  967. break;
  968. }
  969. /* Invalid message type */
  970. default:
  971. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  972. }
  973. /* Decrypt message */
  974. UA_assert(cryptoModule != NULL);
  975. retval = decryptChunk(channel, cryptoModule, messageType, chunk, offset,
  976. &requestId, &sequenceNumber, &chunkPayload);
  977. if(retval != UA_STATUSCODE_GOOD)
  978. return retval;
  979. #if !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
  980. /* Check the sequence number. Skip sequence number checking for fuzzer to
  981. * improve coverage */
  982. if(sequenceNumberCallback == NULL)
  983. return UA_STATUSCODE_BADINTERNALERROR;
  984. retval = sequenceNumberCallback(channel, sequenceNumber);
  985. if(retval != UA_STATUSCODE_GOOD)
  986. return retval;
  987. #endif
  988. /* Add the payload to the (new) message */
  989. addPayload:
  990. switch(chunkType) {
  991. case UA_CHUNKTYPE_INTERMEDIATE:
  992. case UA_CHUNKTYPE_FINAL:
  993. retval = addChunkPayload(channel, requestId, messageType,
  994. &chunkPayload, chunkType == UA_CHUNKTYPE_FINAL);
  995. break;
  996. case UA_CHUNKTYPE_ABORT:
  997. deleteLatestMessage(channel, requestId);
  998. break;
  999. default:
  1000. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  1001. }
  1002. return retval;
  1003. }
  1004. UA_StatusCode
  1005. UA_SecureChannel_decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk) {
  1006. /* Has the SecureChannel timed out? */
  1007. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  1008. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1009. if(channel->state == UA_SECURECHANNELSTATE_OPEN &&
  1010. (channel->securityToken.createdAt +
  1011. (channel->securityToken.revisedLifetime * UA_DATETIME_MSEC))
  1012. < UA_DateTime_nowMonotonic()) {
  1013. UA_SecureChannel_deleteMembersCleanup(channel);
  1014. return UA_STATUSCODE_BADSECURECHANNELCLOSED;
  1015. }
  1016. UA_StatusCode retval = decryptAddChunk(channel, chunk);
  1017. if(retval != UA_STATUSCODE_GOOD)
  1018. UA_SecureChannel_deleteMembersCleanup(channel);
  1019. return retval;
  1020. }
  1021. UA_StatusCode
  1022. UA_SecureChannel_persistIncompleteMessages(UA_SecureChannel *channel) {
  1023. UA_Message *me;
  1024. TAILQ_FOREACH(me, &channel->messages, pointers) {
  1025. UA_ChunkPayload *cp;
  1026. SIMPLEQ_FOREACH(cp, &me->chunkPayloads, pointers) {
  1027. if(cp->copied)
  1028. continue;
  1029. UA_ByteString copy;
  1030. UA_StatusCode retval = UA_ByteString_copy(&cp->bytes, &copy);
  1031. if(retval != UA_STATUSCODE_GOOD) {
  1032. UA_SecureChannel_deleteMembersCleanup(channel);
  1033. return retval;
  1034. }
  1035. cp->bytes = copy;
  1036. cp->copied = true;
  1037. }
  1038. }
  1039. return UA_STATUSCODE_GOOD;
  1040. }
  1041. /* Functionality used by both the SecureChannel and the SecurityPolicy */
  1042. size_t
  1043. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(const UA_SecurityPolicy *securityPolicy,
  1044. const void *channelContext,
  1045. size_t maxEncryptionLength) {
  1046. if(maxEncryptionLength == 0)
  1047. return 0;
  1048. size_t plainTextBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  1049. getRemotePlainTextBlockSize(securityPolicy, channelContext);
  1050. size_t encryptedBlockSize = securityPolicy->asymmetricModule.cryptoModule.encryptionAlgorithm.
  1051. getRemoteBlockSize(securityPolicy, channelContext);
  1052. if(plainTextBlockSize == 0)
  1053. return 0;
  1054. size_t maxNumberOfBlocks = maxEncryptionLength / plainTextBlockSize;
  1055. return maxNumberOfBlocks * (encryptedBlockSize - plainTextBlockSize);
  1056. }