ua_securechannel.c 13 KB

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