ua_securechannel.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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_Byte **bufPos, const UA_Byte **bufEnd) {
  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. UA_ByteString *dst = &ci->buffer;
  116. UA_Byte *chunkEndPos = *bufPos;
  117. size_t offset = (uintptr_t)*bufPos - (uintptr_t)dst->data;
  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. chunkEndPos = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  140. UA_UInt32_encodeBinary(&ci->errorCode, &chunkEndPos, bufEnd);
  141. UA_String_encodeBinary(&errorMsg, &chunkEndPos, bufEnd);
  142. offset = (uintptr_t)*bufEnd - (uintptr_t)dst->data;
  143. }
  144. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  145. ci->messageSizeSoFar += offset;
  146. /* Encode the header at the beginning of the buffer */
  147. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  148. symSecHeader.tokenId = channel->securityToken.tokenId;
  149. UA_SequenceHeader seqHeader;
  150. seqHeader.requestId = ci->requestId;
  151. seqHeader.sequenceNumber = UA_atomic_add(&channel->sendSequenceNumber, 1);
  152. UA_Byte *beginPos = dst->data;
  153. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, &beginPos, bufEnd);
  154. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, &beginPos, bufEnd);
  155. UA_SequenceHeader_encodeBinary(&seqHeader, &beginPos, bufEnd);
  156. /* Send the chunk, the buffer is freed in the network layer */
  157. dst->length = offset; /* set the buffer length to the content length */
  158. connection->send(channel->connection, dst);
  159. /* Replace with the buffer for the next chunk */
  160. if(!ci->final) {
  161. UA_StatusCode retval =
  162. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  163. if(retval != UA_STATUSCODE_GOOD)
  164. return retval;
  165. /* Forward the data pointer so that the payload is encoded after the message header. */
  166. *bufPos = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  167. *bufEnd = &dst->data[dst->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. /* Create the chunking info structure */
  178. UA_ChunkInfo ci;
  179. ci.channel = channel;
  180. ci.requestId = requestId;
  181. ci.chunksSoFar = 0;
  182. ci.messageSizeSoFar = 0;
  183. ci.final = false;
  184. ci.messageType = UA_MESSAGETYPE_MSG;
  185. ci.errorCode = UA_STATUSCODE_GOOD;
  186. /* Allocate the message buffer */
  187. UA_StatusCode retval =
  188. connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &ci.buffer);
  189. if(retval != UA_STATUSCODE_GOOD)
  190. return retval;
  191. /* Hide the message beginning where the header will be encoded */
  192. UA_Byte *bufPos = &ci.buffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  193. const UA_Byte *bufEnd = &ci.buffer.data[ci.buffer.length];
  194. /* Encode the message type */
  195. UA_NodeId typeId = contentType->typeId; /* always numeric */
  196. typeId.identifier.numeric = contentType->binaryEncodingId;
  197. UA_NodeId_encodeBinary(&typeId, &bufPos, &bufEnd);
  198. /* Encode with the chunking callback */
  199. if(typeId.identifier.numeric == 446 || typeId.identifier.numeric == 449)
  200. ci.messageType = UA_MESSAGETYPE_OPN;
  201. else if(typeId.identifier.numeric == 452 || typeId.identifier.numeric == 455)
  202. ci.messageType = UA_MESSAGETYPE_CLO;
  203. retval = UA_encodeBinary(content, contentType, &bufPos, &bufEnd,
  204. (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk, &ci);
  205. /* Encoding failed, release the message */
  206. if(retval != UA_STATUSCODE_GOOD) {
  207. if(!ci.final) {
  208. /* the abort message was not send */
  209. ci.errorCode = retval;
  210. UA_SecureChannel_sendChunk(&ci, &bufPos, &bufEnd);
  211. }
  212. return retval;
  213. }
  214. /* Encoding finished, send the final chunk */
  215. ci.final = UA_TRUE;
  216. return UA_SecureChannel_sendChunk(&ci, &bufPos, &bufEnd);
  217. }
  218. /***************************/
  219. /* Process Received Chunks */
  220. /***************************/
  221. static void
  222. UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  223. struct ChunkEntry *ch;
  224. LIST_FOREACH(ch, &channel->chunks, pointers) {
  225. if(ch->requestId == requestId) {
  226. UA_ByteString_deleteMembers(&ch->bytes);
  227. LIST_REMOVE(ch, pointers);
  228. UA_free(ch);
  229. return;
  230. }
  231. }
  232. }
  233. /* assume that chunklength fits */
  234. static void
  235. appendChunk(struct ChunkEntry *ch, const UA_ByteString *msg,
  236. size_t offset, size_t chunklength) {
  237. UA_Byte* new_bytes = (UA_Byte *)UA_realloc(ch->bytes.data, ch->bytes.length + chunklength);
  238. if(!new_bytes) {
  239. UA_ByteString_deleteMembers(&ch->bytes);
  240. return;
  241. }
  242. ch->bytes.data = new_bytes;
  243. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[offset], chunklength);
  244. ch->bytes.length += chunklength;
  245. }
  246. static void
  247. UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  248. const UA_ByteString *msg, size_t offset,
  249. size_t chunklength) {
  250. /* Check if the chunk fits into the message */
  251. if(msg->length - offset < chunklength) {
  252. /* can't process all chunks for that request */
  253. UA_SecureChannel_removeChunk(channel, requestId);
  254. return;
  255. }
  256. /* Get the chunkentry */
  257. struct ChunkEntry *ch;
  258. LIST_FOREACH(ch, &channel->chunks, pointers) {
  259. if(ch->requestId == requestId)
  260. break;
  261. }
  262. /* No chunkentry on the channel, create one */
  263. if(!ch) {
  264. ch = (struct ChunkEntry *)UA_malloc(sizeof(struct ChunkEntry));
  265. if(!ch)
  266. return;
  267. ch->requestId = requestId;
  268. UA_ByteString_init(&ch->bytes);
  269. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  270. }
  271. appendChunk(ch, msg, offset, chunklength);
  272. }
  273. static UA_ByteString
  274. UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  275. const UA_ByteString *msg, size_t offset,
  276. size_t chunklength, UA_Boolean *deleteChunk) {
  277. if(msg->length - offset < chunklength) {
  278. /* can't process all chunks for that request */
  279. UA_SecureChannel_removeChunk(channel, requestId);
  280. return UA_BYTESTRING_NULL;
  281. }
  282. struct ChunkEntry *ch;
  283. LIST_FOREACH(ch, &channel->chunks, pointers) {
  284. if(ch->requestId == requestId)
  285. break;
  286. }
  287. UA_ByteString bytes;
  288. if(!ch) {
  289. *deleteChunk = false;
  290. bytes.length = chunklength;
  291. bytes.data = msg->data + offset;
  292. } else {
  293. *deleteChunk = true;
  294. appendChunk(ch, msg, offset, chunklength);
  295. bytes = ch->bytes;
  296. LIST_REMOVE(ch, pointers);
  297. UA_free(ch);
  298. }
  299. return bytes;
  300. }
  301. static UA_StatusCode
  302. UA_SecureChannel_processSequenceNumber(UA_SecureChannel *channel, UA_UInt32 SequenceNumber) {
  303. /* Does the sequence number match? */
  304. if(SequenceNumber != channel->receiveSequenceNumber + 1) {
  305. if(channel->receiveSequenceNumber + 1 > 4294966271 && SequenceNumber < 1024)
  306. channel->receiveSequenceNumber = SequenceNumber - 1; /* Roll over */
  307. else
  308. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  309. }
  310. ++channel->receiveSequenceNumber;
  311. return UA_STATUSCODE_GOOD;
  312. }
  313. UA_StatusCode
  314. UA_SecureChannel_processChunks(UA_SecureChannel *channel, const UA_ByteString *chunks,
  315. UA_ProcessMessageCallback callback, void *application) {
  316. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  317. size_t offset= 0;
  318. do {
  319. if (chunks->length > 3 && chunks->data[offset] == 'E' &&
  320. chunks->data[offset+1] == 'R' && chunks->data[offset+2] == 'R') {
  321. UA_TcpMessageHeader header;
  322. retval = UA_TcpMessageHeader_decodeBinary(chunks, &offset, &header);
  323. if(retval != UA_STATUSCODE_GOOD)
  324. break;
  325. UA_TcpErrorMessage errorMessage;
  326. retval = UA_TcpErrorMessage_decodeBinary(chunks, &offset, &errorMessage);
  327. if(retval != UA_STATUSCODE_GOOD)
  328. break;
  329. // dirty cast to pass errorMessage
  330. UA_UInt32 val = 0;
  331. callback(application, (UA_SecureChannel *)channel, (UA_MessageType)UA_MESSAGETYPE_ERR,
  332. val, (const UA_ByteString*)&errorMessage);
  333. continue;
  334. }
  335. /* Store the initial offset to compute the header length */
  336. size_t initial_offset = offset;
  337. /* Decode header */
  338. UA_SecureConversationMessageHeader header;
  339. retval = UA_SecureConversationMessageHeader_decodeBinary(chunks, &offset, &header);
  340. if(retval != UA_STATUSCODE_GOOD)
  341. break;
  342. /* Is the channel attached to connection? */
  343. if(header.secureChannelId != channel->securityToken.channelId) {
  344. //Service_CloseSecureChannel(server, channel);
  345. //connection->close(connection);
  346. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  347. }
  348. /* Use requestId = 0 with OPN as argument for the callback */
  349. UA_SequenceHeader sequenceHeader;
  350. UA_SequenceHeader_init(&sequenceHeader);
  351. if((header.messageHeader.messageTypeAndChunkType & 0x00ffffff) != UA_MESSAGETYPE_OPN) {
  352. /* Check the symmetric security header (not for OPN) */
  353. UA_UInt32 tokenId = 0;
  354. retval |= UA_UInt32_decodeBinary(chunks, &offset, &tokenId);
  355. retval |= UA_SequenceHeader_decodeBinary(chunks, &offset, &sequenceHeader);
  356. if(retval != UA_STATUSCODE_GOOD)
  357. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  358. /* Does the token match? */
  359. if(tokenId != channel->securityToken.tokenId) {
  360. if(tokenId != channel->nextSecurityToken.tokenId)
  361. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  362. UA_SecureChannel_revolveTokens(channel);
  363. }
  364. /* Does the sequence number match? */
  365. retval = UA_SecureChannel_processSequenceNumber(channel, sequenceHeader.sequenceNumber);
  366. if(retval != UA_STATUSCODE_GOOD)
  367. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  368. }
  369. /* Process chunk */
  370. size_t processed_header = offset - initial_offset;
  371. switch(header.messageHeader.messageTypeAndChunkType & 0xff000000) {
  372. case UA_CHUNKTYPE_INTERMEDIATE:
  373. UA_SecureChannel_appendChunk(channel, sequenceHeader.requestId, chunks, offset,
  374. header.messageHeader.messageSize - processed_header);
  375. break;
  376. case UA_CHUNKTYPE_FINAL: {
  377. UA_Boolean realloced = false;
  378. UA_ByteString message =
  379. UA_SecureChannel_finalizeChunk(channel, sequenceHeader.requestId, chunks, offset,
  380. header.messageHeader.messageSize - processed_header,
  381. &realloced);
  382. if(message.length > 0) {
  383. callback(application,(UA_SecureChannel *)channel,(UA_MessageType)(header.messageHeader.messageTypeAndChunkType & 0x00ffffff),
  384. sequenceHeader.requestId, &message);
  385. if(realloced)
  386. UA_ByteString_deleteMembers(&message);
  387. }
  388. break; }
  389. case UA_CHUNKTYPE_ABORT:
  390. UA_SecureChannel_removeChunk(channel, sequenceHeader.requestId);
  391. break;
  392. default:
  393. return UA_STATUSCODE_BADDECODINGERROR;
  394. }
  395. /* Jump to the end of the chunk */
  396. offset += (header.messageHeader.messageSize - processed_header);
  397. } while(chunks->length > offset);
  398. return retval;
  399. }