ua_securechannel.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. #define UA_SECURE_MESSAGE_HEADER_LENGTH 24
  8. void UA_SecureChannel_init(UA_SecureChannel *channel) {
  9. UA_MessageSecurityMode_init(&channel->securityMode);
  10. UA_ChannelSecurityToken_init(&channel->securityToken);
  11. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  12. UA_AsymmetricAlgorithmSecurityHeader_init(&channel->clientAsymAlgSettings);
  13. UA_AsymmetricAlgorithmSecurityHeader_init(&channel->serverAsymAlgSettings);
  14. UA_ByteString_init(&channel->clientNonce);
  15. UA_ByteString_init(&channel->serverNonce);
  16. channel->receiveSequenceNumber = 0;
  17. channel->sendSequenceNumber = 0;
  18. channel->connection = NULL;
  19. LIST_INIT(&channel->sessions);
  20. LIST_INIT(&channel->chunks);
  21. }
  22. void UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel) {
  23. /* Delete members */
  24. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->serverAsymAlgSettings);
  25. UA_ByteString_deleteMembers(&channel->serverNonce);
  26. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->clientAsymAlgSettings);
  27. UA_ByteString_deleteMembers(&channel->clientNonce);
  28. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  29. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  30. /* Detach from the channel */
  31. if(channel->connection)
  32. UA_Connection_detachSecureChannel(channel->connection);
  33. /* Remove session pointers (not the sessions) */
  34. struct SessionEntry *se, *temp;
  35. LIST_FOREACH_SAFE(se, &channel->sessions, pointers, temp) {
  36. if(se->session)
  37. se->session->channel = NULL;
  38. LIST_REMOVE(se, pointers);
  39. UA_free(se);
  40. }
  41. /* Remove the buffered chunks */
  42. struct ChunkEntry *ch, *temp_ch;
  43. LIST_FOREACH_SAFE(ch, &channel->chunks, pointers, temp_ch) {
  44. UA_ByteString_deleteMembers(&ch->bytes);
  45. LIST_REMOVE(ch, pointers);
  46. UA_free(ch);
  47. }
  48. }
  49. //TODO implement real nonce generator - DUMMY function
  50. UA_StatusCode UA_SecureChannel_generateNonce(UA_ByteString *nonce) {
  51. if(!(nonce->data = UA_malloc(1)))
  52. return UA_STATUSCODE_BADOUTOFMEMORY;
  53. nonce->length = 1;
  54. nonce->data[0] = 'a';
  55. return UA_STATUSCODE_GOOD;
  56. }
  57. #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
  58. #pragma GCC diagnostic push
  59. #pragma GCC diagnostic ignored "-Wextra"
  60. #pragma GCC diagnostic ignored "-Wcast-qual"
  61. #pragma GCC diagnostic ignored "-Wunused-value"
  62. #endif
  63. void UA_SecureChannel_attachSession(UA_SecureChannel *channel, UA_Session *session) {
  64. struct SessionEntry *se = UA_malloc(sizeof(struct SessionEntry));
  65. if(!se)
  66. return;
  67. se->session = session;
  68. #ifdef UA_ENABLE_MULTITHREADING
  69. if(uatomic_cmpxchg(&session->channel, NULL, channel) != NULL) {
  70. UA_free(se);
  71. return;
  72. }
  73. #else
  74. if(session->channel != NULL) {
  75. UA_free(se);
  76. return;
  77. }
  78. session->channel = channel;
  79. #endif
  80. LIST_INSERT_HEAD(&channel->sessions, se, pointers);
  81. }
  82. #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
  83. #pragma GCC diagnostic pop
  84. #endif
  85. void UA_SecureChannel_detachSession(UA_SecureChannel *channel, UA_Session *session) {
  86. if(session)
  87. session->channel = NULL;
  88. struct SessionEntry *se;
  89. LIST_FOREACH(se, &channel->sessions, pointers) {
  90. if(se->session == session)
  91. break;
  92. }
  93. if(!se)
  94. return;
  95. LIST_REMOVE(se, pointers);
  96. UA_free(se);
  97. }
  98. UA_Session * UA_SecureChannel_getSession(UA_SecureChannel *channel, UA_NodeId *token) {
  99. struct SessionEntry *se;
  100. LIST_FOREACH(se, &channel->sessions, pointers) {
  101. if(UA_NodeId_equal(&se->session->authenticationToken, token))
  102. break;
  103. }
  104. if(!se)
  105. return NULL;
  106. return se->session;
  107. }
  108. void UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  109. if(channel->nextSecurityToken.tokenId == 0) //no security token issued
  110. return;
  111. //FIXME: not thread-safe
  112. memcpy(&channel->securityToken, &channel->nextSecurityToken, sizeof(UA_ChannelSecurityToken));
  113. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  114. }
  115. static UA_StatusCode
  116. UA_SecureChannel_sendChunk(UA_ChunkInfo *ci, UA_ByteString *dst, size_t offset) {
  117. UA_SecureChannel *channel = ci->channel;
  118. UA_Connection *connection = channel->connection;
  119. if(!connection)
  120. return UA_STATUSCODE_BADINTERNALERROR;
  121. /* adjust the buffer where the header was hidden */
  122. dst->data = &dst->data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  123. dst->length += UA_SECURE_MESSAGE_HEADER_LENGTH;
  124. offset += UA_SECURE_MESSAGE_HEADER_LENGTH;
  125. ci->messageSizeSoFar += offset;
  126. UA_Boolean chunkedMsg = (ci->chunksSoFar > 0 || ci->final == false);
  127. UA_Boolean abortMsg = ((++ci->chunksSoFar >= connection->remoteConf.maxChunkCount ||
  128. ci->messageSizeSoFar > connection->remoteConf.maxMessageSize)) && chunkedMsg;
  129. /* Prepare the chunk headers */
  130. UA_SecureConversationMessageHeader respHeader;
  131. respHeader.secureChannelId = channel->securityToken.channelId;
  132. respHeader.messageHeader.messageTypeAndChunkType = ci->messageType;
  133. if(!abortMsg) {
  134. if(ci->final)
  135. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  136. else
  137. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  138. } else {
  139. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_ABORT;
  140. ci->abort = true;
  141. UA_StatusCode retval = UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
  142. UA_String errorMsg = UA_STRING("Encoded message too long");
  143. offset = UA_SECURE_MESSAGE_HEADER_LENGTH;
  144. UA_UInt32_encodeBinary(&retval,dst,&offset);
  145. UA_String_encodeBinary(&errorMsg,dst,&offset);
  146. }
  147. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  148. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  149. symSecHeader.tokenId = channel->securityToken.tokenId;
  150. UA_SequenceHeader seqHeader;
  151. seqHeader.requestId = ci->requestId;
  152. #ifndef UA_ENABLE_MULTITHREADING
  153. seqHeader.sequenceNumber = ++channel->sendSequenceNumber;
  154. #else
  155. seqHeader.sequenceNumber = uatomic_add_return(&channel->sendSequenceNumber, 1);
  156. #endif
  157. /* Encode the header at the beginning of the buffer */
  158. size_t offset_header = 0;
  159. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, dst, &offset_header);
  160. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, dst, &offset_header);
  161. UA_SequenceHeader_encodeBinary(&seqHeader, dst, &offset_header);
  162. /* Send the chunk, the buffer is freed in the network layer */
  163. dst->length = offset; /* set the buffer length to the content length */
  164. connection->send(channel->connection, dst);
  165. /* Replace with the buffer for the next chunk */
  166. if(!ci->final && !ci->abort) {
  167. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  168. if(retval != UA_STATUSCODE_GOOD)
  169. return retval;
  170. /* Hide the header of the buffer, so that the ensuing encoding does not overwrite anything */
  171. dst->data = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  172. dst->length = connection->localConf.sendBufferSize - UA_SECURE_MESSAGE_HEADER_LENGTH;
  173. }
  174. return UA_STATUSCODE_GOOD;
  175. }
  176. UA_StatusCode
  177. UA_SecureChannel_sendBinaryMessage(UA_SecureChannel *channel, UA_UInt32 requestId, const void *content,
  178. const UA_DataType *contentType) {
  179. UA_Connection *connection = channel->connection;
  180. if(!connection)
  181. return UA_STATUSCODE_BADINTERNALERROR;
  182. /* Allocate the message buffer */
  183. UA_ByteString message;
  184. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &message);
  185. if(retval != UA_STATUSCODE_GOOD)
  186. return retval;
  187. /* Hide the message beginning where the header will be encoded */
  188. message.data = &message.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  189. message.length -= UA_SECURE_MESSAGE_HEADER_LENGTH;
  190. /* Encode the message type */
  191. size_t messagePos = 0;
  192. UA_NodeId typeId = contentType->typeId; /* always numeric */
  193. typeId.identifier.numeric += UA_ENCODINGOFFSET_BINARY;
  194. UA_NodeId_encodeBinary(&typeId, &message, &messagePos);
  195. /* Encode with the chunking callback */
  196. UA_ChunkInfo ci;
  197. ci.channel = channel;
  198. ci.requestId = requestId;
  199. ci.chunksSoFar = 0;
  200. ci.messageSizeSoFar = 0;
  201. ci.final = false;
  202. ci.messageType = UA_MESSAGETYPE_MSG;
  203. ci.abort = false;
  204. if(typeId.identifier.numeric == 446 || typeId.identifier.numeric == 449)
  205. ci.messageType = UA_MESSAGETYPE_OPN;
  206. else if(typeId.identifier.numeric == 452 || typeId.identifier.numeric == 455)
  207. ci.messageType = UA_MESSAGETYPE_CLO;
  208. retval = UA_encodeBinary(content, contentType, (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk,
  209. &ci, &message, &messagePos);
  210. /* Abort message was sent, the buffer is already freed */
  211. if(ci.abort)
  212. return retval;
  213. /* Encoding failed, release the message */
  214. if(retval != UA_STATUSCODE_GOOD) {
  215. /* Unhide the beginning of the buffer (header) */
  216. message.data = &message.data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  217. connection->releaseSendBuffer(connection, &message);
  218. return retval;
  219. }
  220. /* Encoding finished, send the final chunk */
  221. ci.final = UA_TRUE;
  222. return UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  223. }
  224. /* assume that chunklength fits */
  225. static void appendChunk(struct ChunkEntry *ch, const UA_ByteString *msg,
  226. size_t pos, size_t chunklength) {
  227. UA_Byte* new_bytes = UA_realloc(ch->bytes.data, ch->bytes.length + chunklength);
  228. if(!new_bytes) {
  229. UA_ByteString_deleteMembers(&ch->bytes);
  230. return;
  231. }
  232. ch->bytes.data = new_bytes;
  233. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[pos], chunklength);
  234. ch->bytes.length += chunklength;
  235. }
  236. void UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  237. const UA_ByteString *msg, size_t pos, size_t chunklength) {
  238. /* Check if the chunk fits into the message */
  239. if(msg->length - pos < chunklength) {
  240. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  241. return;
  242. }
  243. /* Get/create the chunkentry */
  244. struct ChunkEntry *ch;
  245. LIST_FOREACH(ch, &channel->chunks, pointers) {
  246. if(ch->requestId == requestId)
  247. break;
  248. }
  249. if(!ch) {
  250. ch = UA_malloc(sizeof(struct ChunkEntry));
  251. if(!ch)
  252. return;
  253. ch->requestId = requestId;
  254. UA_ByteString_init(&ch->bytes);
  255. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  256. }
  257. appendChunk(ch, msg, pos, chunklength);
  258. }
  259. UA_ByteString UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  260. const UA_ByteString *msg, size_t pos, size_t chunklength,
  261. UA_Boolean *deleteChunk) {
  262. if(msg->length - pos < chunklength) {
  263. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  264. return UA_BYTESTRING_NULL;
  265. }
  266. struct ChunkEntry *ch;
  267. LIST_FOREACH(ch, &channel->chunks, pointers) {
  268. if(ch->requestId == requestId)
  269. break;
  270. }
  271. UA_ByteString bytes;
  272. if(!ch) {
  273. *deleteChunk = false;
  274. bytes.length = chunklength;
  275. bytes.data = msg->data + pos;
  276. } else {
  277. *deleteChunk = true;
  278. appendChunk(ch, msg, pos, chunklength);
  279. bytes = ch->bytes;
  280. LIST_REMOVE(ch, pointers);
  281. UA_free(ch);
  282. }
  283. return bytes;
  284. }
  285. void UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  286. struct ChunkEntry *ch;
  287. LIST_FOREACH(ch, &channel->chunks, pointers) {
  288. if(ch->requestId == requestId) {
  289. UA_ByteString_deleteMembers(&ch->bytes);
  290. LIST_REMOVE(ch, pointers);
  291. UA_free(ch);
  292. return;
  293. }
  294. }
  295. }