ua_securechannel.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. #include "ua_util.h"
  5. #include "ua_securechannel.h"
  6. #include "ua_session.h"
  7. #include "ua_types_encoding_binary.h"
  8. #include "ua_types_generated_encoding_binary.h"
  9. #include "ua_transport_generated_encoding_binary.h"
  10. #include "ua_types_generated_handling.h"
  11. #include "ua_transport_generated_handling.h"
  12. #define UA_SECURE_MESSAGE_HEADER_LENGTH 24
  13. void UA_SecureChannel_init(UA_SecureChannel *channel) {
  14. memset(channel, 0, sizeof(UA_SecureChannel));
  15. /* Linked lists are also initialized by zeroing out */
  16. /* LIST_INIT(&channel->sessions); */
  17. /* LIST_INIT(&channel->chunks); */
  18. }
  19. void UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel) {
  20. /* Delete members */
  21. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->serverAsymAlgSettings);
  22. UA_ByteString_deleteMembers(&channel->serverNonce);
  23. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->clientAsymAlgSettings);
  24. UA_ByteString_deleteMembers(&channel->clientNonce);
  25. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  26. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  27. /* Detach from the channel */
  28. if(channel->connection)
  29. UA_Connection_detachSecureChannel(channel->connection);
  30. /* Remove session pointers (not the sessions) */
  31. struct SessionEntry *se, *temp;
  32. LIST_FOREACH_SAFE(se, &channel->sessions, pointers, temp) {
  33. if(se->session)
  34. se->session->channel = NULL;
  35. LIST_REMOVE(se, pointers);
  36. UA_free(se);
  37. }
  38. /* Remove the buffered chunks */
  39. struct ChunkEntry *ch, *temp_ch;
  40. LIST_FOREACH_SAFE(ch, &channel->chunks, pointers, temp_ch) {
  41. UA_ByteString_deleteMembers(&ch->bytes);
  42. LIST_REMOVE(ch, pointers);
  43. UA_free(ch);
  44. }
  45. }
  46. //TODO implement real nonce generator - DUMMY function
  47. UA_StatusCode UA_SecureChannel_generateNonce(UA_ByteString *nonce) {
  48. if(!(nonce->data = (UA_Byte *)UA_malloc(1)))
  49. return UA_STATUSCODE_BADOUTOFMEMORY;
  50. nonce->length = 1;
  51. nonce->data[0] = 'a';
  52. return UA_STATUSCODE_GOOD;
  53. }
  54. #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
  55. #pragma GCC diagnostic push
  56. #pragma GCC diagnostic ignored "-Wextra"
  57. #pragma GCC diagnostic ignored "-Wcast-qual"
  58. #pragma GCC diagnostic ignored "-Wunused-value"
  59. #endif
  60. void UA_SecureChannel_attachSession(UA_SecureChannel *channel, UA_Session *session) {
  61. struct SessionEntry *se = (struct SessionEntry *)UA_malloc(sizeof(struct SessionEntry));
  62. if(!se)
  63. return;
  64. se->session = session;
  65. if(UA_atomic_cmpxchg((void**)&session->channel, NULL, channel) != NULL) {
  66. UA_free(se);
  67. return;
  68. }
  69. LIST_INSERT_HEAD(&channel->sessions, se, pointers);
  70. }
  71. #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
  72. #pragma GCC diagnostic pop
  73. #endif
  74. void UA_SecureChannel_detachSession(UA_SecureChannel *channel, UA_Session *session) {
  75. if(session)
  76. session->channel = NULL;
  77. struct SessionEntry *se;
  78. LIST_FOREACH(se, &channel->sessions, pointers) {
  79. if(se->session == session)
  80. break;
  81. }
  82. if(!se)
  83. return;
  84. LIST_REMOVE(se, pointers);
  85. UA_free(se);
  86. }
  87. UA_Session * UA_SecureChannel_getSession(UA_SecureChannel *channel, UA_NodeId *token) {
  88. struct SessionEntry *se;
  89. LIST_FOREACH(se, &channel->sessions, pointers) {
  90. if(UA_NodeId_equal(&se->session->authenticationToken, token))
  91. break;
  92. }
  93. if(!se)
  94. return NULL;
  95. return se->session;
  96. }
  97. void UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  98. if(channel->nextSecurityToken.tokenId == 0) //no security token issued
  99. return;
  100. //FIXME: not thread-safe
  101. memcpy(&channel->securityToken, &channel->nextSecurityToken,
  102. sizeof(UA_ChannelSecurityToken));
  103. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  104. }
  105. /***********************/
  106. /* Send Binary Message */
  107. /***********************/
  108. static UA_StatusCode
  109. UA_SecureChannel_sendChunk(UA_ChunkInfo *ci, UA_ByteString *dst, size_t offset) {
  110. UA_SecureChannel *channel = ci->channel;
  111. UA_Connection *connection = channel->connection;
  112. if(!connection)
  113. return UA_STATUSCODE_BADINTERNALERROR;
  114. /* adjust the buffer where the header was hidden */
  115. dst->data = &dst->data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  116. dst->length += UA_SECURE_MESSAGE_HEADER_LENGTH;
  117. offset += UA_SECURE_MESSAGE_HEADER_LENGTH;
  118. if(ci->messageSizeSoFar + offset > connection->remoteConf.maxMessageSize &&
  119. connection->remoteConf.maxMessageSize > 0)
  120. ci->errorCode = UA_STATUSCODE_BADRESPONSETOOLARGE;
  121. if(++ci->chunksSoFar > connection->remoteConf.maxChunkCount &&
  122. connection->remoteConf.maxChunkCount > 0)
  123. ci->errorCode = UA_STATUSCODE_BADRESPONSETOOLARGE;
  124. /* Prepare the chunk headers */
  125. UA_SecureConversationMessageHeader respHeader;
  126. respHeader.secureChannelId = channel->securityToken.channelId;
  127. respHeader.messageHeader.messageTypeAndChunkType = ci->messageType;
  128. if(ci->errorCode == UA_STATUSCODE_GOOD) {
  129. if(ci->final)
  130. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  131. else
  132. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  133. } else {
  134. /* abort message */
  135. ci->final = true; /* mark as finished */
  136. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_ABORT;
  137. UA_String errorMsg;
  138. UA_String_init(&errorMsg);
  139. offset = UA_SECURE_MESSAGE_HEADER_LENGTH;
  140. UA_UInt32_encodeBinary(&ci->errorCode, dst, &offset);
  141. UA_String_encodeBinary(&errorMsg, dst, &offset);
  142. }
  143. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  144. ci->messageSizeSoFar += offset;
  145. /* Encode the header at the beginning of the buffer */
  146. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  147. symSecHeader.tokenId = channel->securityToken.tokenId;
  148. UA_SequenceHeader seqHeader;
  149. seqHeader.requestId = ci->requestId;
  150. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  151. size_t offset_header = 0;
  152. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, dst, &offset_header);
  153. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, dst, &offset_header);
  154. UA_SequenceHeader_encodeBinary(&seqHeader, dst, &offset_header);
  155. /* Send the chunk, the buffer is freed in the network layer */
  156. dst->length = offset; /* set the buffer length to the content length */
  157. connection->send(channel->connection, dst);
  158. /* Replace with the buffer for the next chunk */
  159. if(!ci->final) {
  160. UA_StatusCode retval =
  161. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  162. if(retval != UA_STATUSCODE_GOOD)
  163. return retval;
  164. /* Forward the data pointer so that the payload is encoded after the message header.
  165. * TODO: This works but is a bit too clever. Instead, we could return an offset to the
  166. * binary encoding exchangeBuffer function. */
  167. dst->data = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  168. dst->length = connection->localConf.sendBufferSize - UA_SECURE_MESSAGE_HEADER_LENGTH;
  169. }
  170. return ci->errorCode;
  171. }
  172. UA_StatusCode
  173. UA_SecureChannel_sendBinaryMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  174. const void *content, const UA_DataType *contentType) {
  175. UA_Connection *connection = channel->connection;
  176. if(!connection)
  177. return UA_STATUSCODE_BADINTERNALERROR;
  178. /* Allocate the message buffer */
  179. UA_ByteString message;
  180. UA_StatusCode retval =
  181. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &message);
  182. if(retval != UA_STATUSCODE_GOOD)
  183. return retval;
  184. /* Hide the message beginning where the header will be encoded */
  185. message.data = &message.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  186. message.length -= UA_SECURE_MESSAGE_HEADER_LENGTH;
  187. /* Encode the message type */
  188. size_t messagePos = 0;
  189. UA_NodeId typeId = contentType->typeId; /* always numeric */
  190. typeId.identifier.numeric = contentType->binaryEncodingId;
  191. UA_NodeId_encodeBinary(&typeId, &message, &messagePos);
  192. /* Encode with the chunking callback */
  193. UA_ChunkInfo ci;
  194. ci.channel = channel;
  195. ci.requestId = requestId;
  196. ci.chunksSoFar = 0;
  197. ci.messageSizeSoFar = 0;
  198. ci.final = false;
  199. ci.messageType = UA_MESSAGETYPE_MSG;
  200. ci.errorCode = UA_STATUSCODE_GOOD;
  201. if(typeId.identifier.numeric == 446 || typeId.identifier.numeric == 449)
  202. ci.messageType = UA_MESSAGETYPE_OPN;
  203. else if(typeId.identifier.numeric == 452 || typeId.identifier.numeric == 455)
  204. ci.messageType = UA_MESSAGETYPE_CLO;
  205. retval = UA_encodeBinary(content, contentType,
  206. (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk,
  207. &ci, &message, &messagePos);
  208. /* Encoding failed, release the message */
  209. if(retval != UA_STATUSCODE_GOOD) {
  210. if(!ci.final) {
  211. /* the abort message was not send */
  212. ci.errorCode = retval;
  213. UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  214. }
  215. return retval;
  216. }
  217. /* Encoding finished, send the final chunk */
  218. ci.final = UA_TRUE;
  219. return UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  220. }
  221. /***************************/
  222. /* Process Received Chunks */
  223. /***************************/
  224. static void
  225. UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  226. struct ChunkEntry *ch;
  227. LIST_FOREACH(ch, &channel->chunks, pointers) {
  228. if(ch->requestId == requestId) {
  229. UA_ByteString_deleteMembers(&ch->bytes);
  230. LIST_REMOVE(ch, pointers);
  231. UA_free(ch);
  232. return;
  233. }
  234. }
  235. }
  236. /* assume that chunklength fits */
  237. static void
  238. appendChunk(struct ChunkEntry *ch, const UA_ByteString *msg,
  239. size_t offset, size_t chunklength) {
  240. UA_Byte* new_bytes = (UA_Byte *)UA_realloc(ch->bytes.data, ch->bytes.length + chunklength);
  241. if(!new_bytes) {
  242. UA_ByteString_deleteMembers(&ch->bytes);
  243. return;
  244. }
  245. ch->bytes.data = new_bytes;
  246. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[offset], chunklength);
  247. ch->bytes.length += chunklength;
  248. }
  249. static void
  250. UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  251. const UA_ByteString *msg, size_t offset,
  252. size_t chunklength) {
  253. /* Check if the chunk fits into the message */
  254. if(msg->length - offset < chunklength) {
  255. /* can't process all chunks for that request */
  256. UA_SecureChannel_removeChunk(channel, requestId);
  257. return;
  258. }
  259. /* Get the chunkentry */
  260. struct ChunkEntry *ch;
  261. LIST_FOREACH(ch, &channel->chunks, pointers) {
  262. if(ch->requestId == requestId)
  263. break;
  264. }
  265. /* No chunkentry on the channel, create one */
  266. if(!ch) {
  267. ch = (struct ChunkEntry *)UA_malloc(sizeof(struct ChunkEntry));
  268. if(!ch)
  269. return;
  270. ch->requestId = requestId;
  271. UA_ByteString_init(&ch->bytes);
  272. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  273. }
  274. appendChunk(ch, msg, offset, chunklength);
  275. }
  276. static UA_ByteString
  277. UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  278. const UA_ByteString *msg, size_t offset,
  279. size_t chunklength, UA_Boolean *deleteChunk) {
  280. if(msg->length - offset < chunklength) {
  281. /* can't process all chunks for that request */
  282. UA_SecureChannel_removeChunk(channel, requestId);
  283. return UA_BYTESTRING_NULL;
  284. }
  285. struct ChunkEntry *ch;
  286. LIST_FOREACH(ch, &channel->chunks, pointers) {
  287. if(ch->requestId == requestId)
  288. break;
  289. }
  290. UA_ByteString bytes;
  291. if(!ch) {
  292. *deleteChunk = false;
  293. bytes.length = chunklength;
  294. bytes.data = msg->data + offset;
  295. } else {
  296. *deleteChunk = true;
  297. appendChunk(ch, msg, offset, chunklength);
  298. bytes = ch->bytes;
  299. LIST_REMOVE(ch, pointers);
  300. UA_free(ch);
  301. }
  302. return bytes;
  303. }
  304. static UA_StatusCode
  305. UA_SecureChannel_processSequenceNumber(UA_SecureChannel *channel, UA_UInt32 SequenceNumber) {
  306. /* Does the sequence number match? */
  307. if(SequenceNumber != channel->receiveSequenceNumber + 1) {
  308. if(channel->receiveSequenceNumber + 1 > 4294966271 && SequenceNumber < 1024)
  309. channel->receiveSequenceNumber = SequenceNumber - 1; /* Roll over */
  310. else
  311. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  312. }
  313. ++channel->receiveSequenceNumber;
  314. return UA_STATUSCODE_GOOD;
  315. }
  316. UA_StatusCode
  317. UA_SecureChannel_processChunks(UA_SecureChannel *channel, const UA_ByteString *chunks,
  318. UA_ProcessMessageCallback callback, void *application) {
  319. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  320. size_t offset= 0;
  321. do {
  322. if (chunks->length > 3 && chunks->data[offset] == 'E' &&
  323. chunks->data[offset+1] == 'R' && chunks->data[offset+2] == 'R') {
  324. UA_TcpMessageHeader header;
  325. retval = UA_TcpMessageHeader_decodeBinary(chunks, &offset, &header);
  326. if(retval != UA_STATUSCODE_GOOD)
  327. break;
  328. UA_TcpErrorMessage errorMessage;
  329. retval = UA_TcpErrorMessage_decodeBinary(chunks, &offset, &errorMessage);
  330. if(retval != UA_STATUSCODE_GOOD)
  331. break;
  332. // dirty cast to pass errorMessage
  333. UA_UInt32 val = 0;
  334. callback(application, (UA_SecureChannel *)channel, (UA_MessageType)UA_MESSAGETYPE_ERR,
  335. val, (const UA_ByteString*)&errorMessage);
  336. continue;
  337. }
  338. /* Store the initial offset to compute the header length */
  339. size_t initial_offset = offset;
  340. /* Decode header */
  341. UA_SecureConversationMessageHeader header;
  342. retval = UA_SecureConversationMessageHeader_decodeBinary(chunks, &offset, &header);
  343. if(retval != UA_STATUSCODE_GOOD)
  344. break;
  345. /* Is the channel attached to connection? */
  346. if(header.secureChannelId != channel->securityToken.channelId) {
  347. //Service_CloseSecureChannel(server, channel);
  348. //connection->close(connection);
  349. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  350. }
  351. /* Use requestId = 0 with OPN as argument for the callback */
  352. UA_SequenceHeader sequenceHeader;
  353. UA_SequenceHeader_init(&sequenceHeader);
  354. if((header.messageHeader.messageTypeAndChunkType & 0x00ffffff) != UA_MESSAGETYPE_OPN) {
  355. /* Check the symmetric security header (not for OPN) */
  356. UA_UInt32 tokenId = 0;
  357. retval |= UA_UInt32_decodeBinary(chunks, &offset, &tokenId);
  358. retval |= UA_SequenceHeader_decodeBinary(chunks, &offset, &sequenceHeader);
  359. if(retval != UA_STATUSCODE_GOOD)
  360. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  361. /* Does the token match? */
  362. if(tokenId != channel->securityToken.tokenId) {
  363. if(tokenId != channel->nextSecurityToken.tokenId)
  364. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  365. UA_SecureChannel_revolveTokens(channel);
  366. }
  367. /* Does the sequence number match? */
  368. retval = UA_SecureChannel_processSequenceNumber(channel, sequenceHeader.sequenceNumber);
  369. if(retval != UA_STATUSCODE_GOOD)
  370. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  371. }
  372. /* Process chunk */
  373. size_t processed_header = offset - initial_offset;
  374. switch(header.messageHeader.messageTypeAndChunkType & 0xff000000) {
  375. case UA_CHUNKTYPE_INTERMEDIATE:
  376. UA_SecureChannel_appendChunk(channel, sequenceHeader.requestId, chunks, offset,
  377. header.messageHeader.messageSize - processed_header);
  378. break;
  379. case UA_CHUNKTYPE_FINAL: {
  380. UA_Boolean realloced = false;
  381. UA_ByteString message =
  382. UA_SecureChannel_finalizeChunk(channel, sequenceHeader.requestId, chunks, offset,
  383. header.messageHeader.messageSize - processed_header,
  384. &realloced);
  385. if(message.length > 0) {
  386. callback(application,(UA_SecureChannel *)channel,(UA_MessageType)(header.messageHeader.messageTypeAndChunkType & 0x00ffffff),
  387. sequenceHeader.requestId, &message);
  388. if(realloced)
  389. UA_ByteString_deleteMembers(&message);
  390. }
  391. break; }
  392. case UA_CHUNKTYPE_ABORT:
  393. UA_SecureChannel_removeChunk(channel, sequenceHeader.requestId);
  394. break;
  395. default:
  396. return UA_STATUSCODE_BADDECODINGERROR;
  397. }
  398. /* Jump to the end of the chunk */
  399. offset += (header.messageHeader.messageSize - processed_header);
  400. } while(chunks->length > offset);
  401. return retval;
  402. }