ua_securechannel.c 16 KB

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