ua_securechannel.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. if(++ci->chunksSoFar > connection->remoteConf.maxChunkCount ||
  126. ci->messageSizeSoFar + offset > connection->remoteConf.maxMessageSize)
  127. ci->errorCode = UA_STATUSCODE_BADTCPMESSAGETOOLARGE;
  128. /* Prepare the chunk headers */
  129. UA_SecureConversationMessageHeader respHeader;
  130. respHeader.secureChannelId = channel->securityToken.channelId;
  131. respHeader.messageHeader.messageTypeAndChunkType = ci->messageType;
  132. if(ci->errorCode == UA_STATUSCODE_GOOD) {
  133. if(ci->final)
  134. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  135. else
  136. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  137. } else {
  138. /* abort message */
  139. ci->final = true; /* mark as finished */
  140. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_ABORT;
  141. UA_String errorMsg;
  142. UA_String_init(&errorMsg);
  143. offset = UA_SECURE_MESSAGE_HEADER_LENGTH;
  144. UA_UInt32_encodeBinary(&ci->errorCode, dst, &offset);
  145. UA_String_encodeBinary(&errorMsg, dst, &offset);
  146. }
  147. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  148. ci->messageSizeSoFar += offset;
  149. /* Encode the header at the beginning of the buffer */
  150. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  151. symSecHeader.tokenId = channel->securityToken.tokenId;
  152. UA_SequenceHeader seqHeader;
  153. seqHeader.requestId = ci->requestId;
  154. #ifndef UA_ENABLE_MULTITHREADING
  155. seqHeader.sequenceNumber = ++channel->sendSequenceNumber;
  156. #else
  157. seqHeader.sequenceNumber = uatomic_add_return(&channel->sendSequenceNumber, 1);
  158. #endif
  159. size_t offset_header = 0;
  160. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, dst, &offset_header);
  161. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, dst, &offset_header);
  162. UA_SequenceHeader_encodeBinary(&seqHeader, dst, &offset_header);
  163. /* Send the chunk, the buffer is freed in the network layer */
  164. dst->length = offset; /* set the buffer length to the content length */
  165. connection->send(channel->connection, dst);
  166. /* Replace with the buffer for the next chunk */
  167. if(!ci->final) {
  168. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  169. if(retval != UA_STATUSCODE_GOOD)
  170. return retval;
  171. /* Hide the header of the buffer, so that the ensuing encoding does not overwrite anything */
  172. dst->data = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  173. dst->length = connection->localConf.sendBufferSize - UA_SECURE_MESSAGE_HEADER_LENGTH;
  174. }
  175. return ci->errorCode;
  176. }
  177. UA_StatusCode
  178. UA_SecureChannel_sendBinaryMessage(UA_SecureChannel *channel, UA_UInt32 requestId, const void *content,
  179. const UA_DataType *contentType) {
  180. UA_Connection *connection = channel->connection;
  181. if(!connection)
  182. return UA_STATUSCODE_BADINTERNALERROR;
  183. /* Allocate the message buffer */
  184. UA_ByteString message;
  185. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &message);
  186. if(retval != UA_STATUSCODE_GOOD)
  187. return retval;
  188. /* Hide the message beginning where the header will be encoded */
  189. message.data = &message.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  190. message.length -= UA_SECURE_MESSAGE_HEADER_LENGTH;
  191. /* Encode the message type */
  192. size_t messagePos = 0;
  193. UA_NodeId typeId = contentType->typeId; /* always numeric */
  194. typeId.identifier.numeric += UA_ENCODINGOFFSET_BINARY;
  195. UA_NodeId_encodeBinary(&typeId, &message, &messagePos);
  196. /* Encode with the chunking callback */
  197. UA_ChunkInfo ci;
  198. ci.channel = channel;
  199. ci.requestId = requestId;
  200. ci.chunksSoFar = 0;
  201. ci.messageSizeSoFar = 0;
  202. ci.final = false;
  203. ci.messageType = UA_MESSAGETYPE_MSG;
  204. ci.errorCode = UA_STATUSCODE_GOOD;
  205. if(typeId.identifier.numeric == 446 || typeId.identifier.numeric == 449)
  206. ci.messageType = UA_MESSAGETYPE_OPN;
  207. else if(typeId.identifier.numeric == 452 || typeId.identifier.numeric == 455)
  208. ci.messageType = UA_MESSAGETYPE_CLO;
  209. retval = UA_encodeBinary(content, contentType, (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk,
  210. &ci, &message, &messagePos);
  211. /* Encoding failed, release the message */
  212. if(retval != UA_STATUSCODE_GOOD) {
  213. if(!ci.final) {
  214. /* the abort message was not send */
  215. ci.errorCode = retval;
  216. UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  217. }
  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 offset, 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[offset], 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 offset, size_t chunklength) {
  238. /* Check if the chunk fits into the message */
  239. if(msg->length - offset < chunklength) {
  240. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  241. return;
  242. }
  243. /* Get the chunkentry */
  244. struct ChunkEntry *ch;
  245. LIST_FOREACH(ch, &channel->chunks, pointers) {
  246. if(ch->requestId == requestId)
  247. break;
  248. }
  249. /* No chunkentry on the channel, create one */
  250. if(!ch) {
  251. ch = UA_malloc(sizeof(struct ChunkEntry));
  252. if(!ch)
  253. return;
  254. ch->requestId = requestId;
  255. UA_ByteString_init(&ch->bytes);
  256. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  257. }
  258. appendChunk(ch, msg, offset, chunklength);
  259. }
  260. UA_ByteString UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  261. const UA_ByteString *msg, size_t offset, size_t chunklength,
  262. UA_Boolean *deleteChunk) {
  263. if(msg->length - offset < chunklength) {
  264. UA_SecureChannel_removeChunk(channel, requestId); /* can't process all chunks for that request */
  265. return UA_BYTESTRING_NULL;
  266. }
  267. struct ChunkEntry *ch;
  268. LIST_FOREACH(ch, &channel->chunks, pointers) {
  269. if(ch->requestId == requestId)
  270. break;
  271. }
  272. UA_ByteString bytes;
  273. if(!ch) {
  274. *deleteChunk = false;
  275. bytes.length = chunklength;
  276. bytes.data = msg->data + offset;
  277. } else {
  278. *deleteChunk = true;
  279. appendChunk(ch, msg, offset, chunklength);
  280. bytes = ch->bytes;
  281. LIST_REMOVE(ch, pointers);
  282. UA_free(ch);
  283. }
  284. return bytes;
  285. }
  286. void UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  287. struct ChunkEntry *ch;
  288. LIST_FOREACH(ch, &channel->chunks, pointers) {
  289. if(ch->requestId == requestId) {
  290. UA_ByteString_deleteMembers(&ch->bytes);
  291. LIST_REMOVE(ch, pointers);
  292. UA_free(ch);
  293. return;
  294. }
  295. }
  296. }