ua_securechannel.c 12 KB

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