ua_securechannel.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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->sequenceNumber = 0;
  17. channel->connection = NULL;
  18. LIST_INIT(&channel->sessions);
  19. LIST_INIT(&channel->chunks);
  20. }
  21. void UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel) {
  22. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->serverAsymAlgSettings);
  23. UA_ByteString_deleteMembers(&channel->serverNonce);
  24. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&channel->clientAsymAlgSettings);
  25. UA_ByteString_deleteMembers(&channel->clientNonce);
  26. UA_ChannelSecurityToken_deleteMembers(&channel->securityToken);
  27. UA_ChannelSecurityToken_deleteMembers(&channel->nextSecurityToken);
  28. UA_Connection *c = channel->connection;
  29. if(c)
  30. UA_Connection_detachSecureChannel(c);
  31. /* just remove the pointers and free the linked list (not the sessions) */
  32. struct SessionEntry *se, *temp;
  33. LIST_FOREACH_SAFE(se, &channel->sessions, pointers, temp) {
  34. if(se->session)
  35. se->session->channel = NULL;
  36. LIST_REMOVE(se, pointers);
  37. UA_free(se);
  38. }
  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_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 = UA_malloc(sizeof(struct SessionEntry));
  62. if(!se)
  63. return;
  64. se->session = session;
  65. #ifdef UA_ENABLE_MULTITHREADING
  66. if(uatomic_cmpxchg(&session->channel, NULL, channel) != NULL) {
  67. UA_free(se);
  68. return;
  69. }
  70. #else
  71. if(session->channel != NULL) {
  72. UA_free(se);
  73. return;
  74. }
  75. session->channel = channel;
  76. #endif
  77. LIST_INSERT_HEAD(&channel->sessions, se, pointers);
  78. }
  79. #if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 6)
  80. #pragma GCC diagnostic pop
  81. #endif
  82. void UA_SecureChannel_detachSession(UA_SecureChannel *channel, UA_Session *session) {
  83. if(session)
  84. session->channel = NULL;
  85. struct SessionEntry *se;
  86. LIST_FOREACH(se, &channel->sessions, pointers) {
  87. if(se->session == session)
  88. break;
  89. }
  90. if(!se)
  91. return;
  92. LIST_REMOVE(se, pointers);
  93. UA_free(se);
  94. }
  95. UA_Session * UA_SecureChannel_getSession(UA_SecureChannel *channel, UA_NodeId *token) {
  96. struct SessionEntry *se;
  97. LIST_FOREACH(se, &channel->sessions, pointers) {
  98. if(UA_NodeId_equal(&se->session->authenticationToken, token))
  99. break;
  100. }
  101. if(!se)
  102. return NULL;
  103. return se->session;
  104. }
  105. void UA_SecureChannel_revolveTokens(UA_SecureChannel *channel) {
  106. if(channel->nextSecurityToken.tokenId == 0) //no security token issued
  107. return;
  108. //FIXME: not thread-safe
  109. memcpy(&channel->securityToken, &channel->nextSecurityToken, sizeof(UA_ChannelSecurityToken));
  110. UA_ChannelSecurityToken_init(&channel->nextSecurityToken);
  111. }
  112. static UA_StatusCode
  113. UA_SecureChannel_sendChunk(UA_ChunkInfo *ci, UA_ByteString *dst, size_t offset) {
  114. UA_SecureChannel *channel = ci->channel;
  115. UA_Connection *connection = channel->connection;
  116. if(!connection)
  117. return UA_STATUSCODE_BADINTERNALERROR;
  118. /* adjust the buffer where the header was hidden */
  119. dst->data = &dst->data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  120. dst->length += UA_SECURE_MESSAGE_HEADER_LENGTH;
  121. offset += UA_SECURE_MESSAGE_HEADER_LENGTH;
  122. ci->messageSizeSoFar += offset;
  123. UA_Boolean chunkedMsg = (ci->chunksSoFar > 0 || ci->final == false);
  124. UA_Boolean abortMsg = ((++ci->chunksSoFar >= connection->remoteConf.maxChunkCount ||
  125. ci->messageSizeSoFar > connection->remoteConf.maxMessageSize)) && chunkedMsg;
  126. /* Prepare the chunk headers */
  127. UA_SecureConversationMessageHeader respHeader;
  128. respHeader.secureChannelId = channel->securityToken.channelId;
  129. respHeader.messageHeader.messageTypeAndChunkType = ci->messageType;
  130. if(!abortMsg) {
  131. if(ci->final)
  132. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  133. else
  134. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  135. } else {
  136. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_ABORT;
  137. ci->abort = true;
  138. UA_StatusCode retval = UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
  139. UA_String errorMsg = UA_STRING("Encoded message too long");
  140. offset = UA_SECURE_MESSAGE_HEADER_LENGTH;
  141. UA_UInt32_encodeBinary(&retval,dst,&offset);
  142. UA_String_encodeBinary(&errorMsg,dst,&offset);
  143. }
  144. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  145. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  146. symSecHeader.tokenId = channel->securityToken.tokenId;
  147. UA_SequenceHeader seqHeader;
  148. seqHeader.requestId = ci->requestId;
  149. #ifndef UA_ENABLE_MULTITHREADING
  150. seqHeader.sequenceNumber = ++channel->sequenceNumber;
  151. #else
  152. seqHeader.sequenceNumber = uatomic_add_return(&channel->sequenceNumber, 1);
  153. #endif
  154. /* Encode the header at the beginning of the buffer */
  155. size_t offset_header = 0;
  156. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, dst, &offset_header);
  157. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, dst, &offset_header);
  158. UA_SequenceHeader_encodeBinary(&seqHeader, dst, &offset_header);
  159. /* Send the chunk, the buffer is freed in the network layer */
  160. dst->length = offset; /* set the buffer length to the content length */
  161. connection->send(channel->connection, dst);
  162. /* Replace with the buffer for the next chunk */
  163. if(!ci->final && !ci->abort) {
  164. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  165. if(retval != UA_STATUSCODE_GOOD)
  166. return retval;
  167. /* Hide the header of the buffer, so that the ensuing encoding does not overwrite anything */
  168. dst->data = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  169. dst->length = connection->localConf.sendBufferSize - UA_SECURE_MESSAGE_HEADER_LENGTH;
  170. }
  171. return UA_STATUSCODE_GOOD;
  172. }
  173. UA_StatusCode
  174. UA_SecureChannel_sendBinaryMessage(UA_SecureChannel *channel, UA_UInt32 requestId, const void *content,
  175. const UA_DataType *contentType) {
  176. UA_Connection *connection = channel->connection;
  177. if(!connection)
  178. return UA_STATUSCODE_BADINTERNALERROR;
  179. /* Allocate the message buffer */
  180. UA_ByteString message;
  181. UA_StatusCode retval = 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 += UA_ENCODINGOFFSET_BINARY;
  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.abort = false;
  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, (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk,
  206. &ci, &message, &messagePos);
  207. /* Abort message was sent, the buffer is already freed */
  208. if(ci.abort)
  209. return retval;
  210. /* Encoding failed, release the message */
  211. if(retval != UA_STATUSCODE_GOOD) {
  212. /* Unhide the beginning of the buffer (header) */
  213. message.data = &message.data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  214. connection->releaseSendBuffer(connection, &message);
  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. /* assume that chunklength fits */
  222. static void appendChunk(struct ChunkEntry *ch, const UA_ByteString *msg,
  223. size_t pos, size_t chunklength) {
  224. UA_Byte* new_bytes = UA_realloc(ch->bytes.data, ch->bytes.length + chunklength);
  225. if(!new_bytes) {
  226. UA_ByteString_deleteMembers(&ch->bytes);
  227. return;
  228. }
  229. ch->bytes.data = new_bytes;
  230. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[pos], chunklength);
  231. ch->bytes.length += chunklength;
  232. }
  233. void UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  234. const UA_ByteString *msg, size_t pos, size_t chunklength) {
  235. /* Check if the chunk fits into the message */
  236. if(msg->length - pos < chunklength) {
  237. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  238. return;
  239. }
  240. /* Get/create the chunkentry */
  241. struct ChunkEntry *ch;
  242. LIST_FOREACH(ch, &channel->chunks, pointers) {
  243. if(ch->requestId == requestId)
  244. break;
  245. }
  246. if(!ch) {
  247. ch = UA_malloc(sizeof(struct ChunkEntry));
  248. if(!ch)
  249. return;
  250. ch->requestId = requestId;
  251. UA_ByteString_init(&ch->bytes);
  252. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  253. }
  254. appendChunk(ch, msg, pos, chunklength);
  255. }
  256. UA_ByteString UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  257. const UA_ByteString *msg, size_t pos, size_t chunklength,
  258. UA_Boolean *deleteChunk) {
  259. if(msg->length - pos < chunklength) {
  260. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  261. return UA_BYTESTRING_NULL;
  262. }
  263. struct ChunkEntry *ch;
  264. LIST_FOREACH(ch, &channel->chunks, pointers) {
  265. if(ch->requestId == requestId)
  266. break;
  267. }
  268. UA_ByteString bytes;
  269. if(!ch) {
  270. *deleteChunk = false;
  271. bytes.length = chunklength;
  272. bytes.data = msg->data + pos;
  273. } else {
  274. *deleteChunk = true;
  275. appendChunk(ch, msg, pos, chunklength);
  276. bytes = ch->bytes;
  277. LIST_REMOVE(ch, pointers);
  278. UA_free(ch);
  279. }
  280. return bytes;
  281. }
  282. void UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  283. struct ChunkEntry *ch;
  284. LIST_FOREACH(ch, &channel->chunks, pointers) {
  285. if(ch->requestId == requestId) {
  286. UA_ByteString_deleteMembers(&ch->bytes);
  287. LIST_REMOVE(ch, pointers);
  288. UA_free(ch);
  289. return;
  290. }
  291. }
  292. }