ua_securechannel.c 16 KB

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