ua_securechannel.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. /***********************/
  118. /* Send Binary Message */
  119. /***********************/
  120. static UA_StatusCode
  121. UA_SecureChannel_sendChunk(UA_ChunkInfo *ci, UA_ByteString *dst, size_t offset) {
  122. UA_SecureChannel *channel = ci->channel;
  123. UA_Connection *connection = channel->connection;
  124. if(!connection)
  125. return UA_STATUSCODE_BADINTERNALERROR;
  126. /* adjust the buffer where the header was hidden */
  127. dst->data = &dst->data[-UA_SECURE_MESSAGE_HEADER_LENGTH];
  128. dst->length += UA_SECURE_MESSAGE_HEADER_LENGTH;
  129. offset += UA_SECURE_MESSAGE_HEADER_LENGTH;
  130. if(ci->messageSizeSoFar + offset > connection->remoteConf.maxMessageSize && connection->remoteConf.maxMessageSize > 0)
  131. ci->errorCode = UA_STATUSCODE_BADRESPONSETOOLARGE;
  132. if(++ci->chunksSoFar > connection->remoteConf.maxChunkCount && connection->remoteConf.maxChunkCount > 0)
  133. ci->errorCode = UA_STATUSCODE_BADRESPONSETOOLARGE;
  134. /* Prepare the chunk headers */
  135. UA_SecureConversationMessageHeader respHeader;
  136. respHeader.secureChannelId = channel->securityToken.channelId;
  137. respHeader.messageHeader.messageTypeAndChunkType = ci->messageType;
  138. if(ci->errorCode == UA_STATUSCODE_GOOD) {
  139. if(ci->final)
  140. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_FINAL;
  141. else
  142. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_INTERMEDIATE;
  143. } else {
  144. /* abort message */
  145. ci->final = true; /* mark as finished */
  146. respHeader.messageHeader.messageTypeAndChunkType += UA_CHUNKTYPE_ABORT;
  147. UA_String errorMsg;
  148. UA_String_init(&errorMsg);
  149. offset = UA_SECURE_MESSAGE_HEADER_LENGTH;
  150. UA_UInt32_encodeBinary(&ci->errorCode, dst, &offset);
  151. UA_String_encodeBinary(&errorMsg, dst, &offset);
  152. }
  153. respHeader.messageHeader.messageSize = (UA_UInt32)offset;
  154. ci->messageSizeSoFar += offset;
  155. /* Encode the header at the beginning of the buffer */
  156. UA_SymmetricAlgorithmSecurityHeader symSecHeader;
  157. symSecHeader.tokenId = channel->securityToken.tokenId;
  158. UA_SequenceHeader seqHeader;
  159. seqHeader.requestId = ci->requestId;
  160. #ifndef UA_ENABLE_MULTITHREADING
  161. seqHeader.sequenceNumber = ++channel->sendSequenceNumber;
  162. #else
  163. seqHeader.sequenceNumber = uatomic_add_return(&channel->sendSequenceNumber, 1);
  164. #endif
  165. size_t offset_header = 0;
  166. UA_SecureConversationMessageHeader_encodeBinary(&respHeader, dst, &offset_header);
  167. UA_SymmetricAlgorithmSecurityHeader_encodeBinary(&symSecHeader, dst, &offset_header);
  168. UA_SequenceHeader_encodeBinary(&seqHeader, dst, &offset_header);
  169. /* Send the chunk, the buffer is freed in the network layer */
  170. dst->length = offset; /* set the buffer length to the content length */
  171. connection->send(channel->connection, dst);
  172. /* Replace with the buffer for the next chunk */
  173. if(!ci->final) {
  174. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, dst);
  175. if(retval != UA_STATUSCODE_GOOD)
  176. return retval;
  177. /* Hide the header of the buffer, so that the ensuing encoding does not overwrite anything */
  178. dst->data = &dst->data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  179. dst->length = connection->localConf.sendBufferSize - UA_SECURE_MESSAGE_HEADER_LENGTH;
  180. }
  181. return ci->errorCode;
  182. }
  183. UA_StatusCode
  184. UA_SecureChannel_sendBinaryMessage(UA_SecureChannel *channel, UA_UInt32 requestId, const void *content,
  185. const UA_DataType *contentType) {
  186. UA_Connection *connection = channel->connection;
  187. if(!connection)
  188. return UA_STATUSCODE_BADINTERNALERROR;
  189. /* Allocate the message buffer */
  190. UA_ByteString message;
  191. UA_StatusCode retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize, &message);
  192. if(retval != UA_STATUSCODE_GOOD)
  193. return retval;
  194. /* Hide the message beginning where the header will be encoded */
  195. message.data = &message.data[UA_SECURE_MESSAGE_HEADER_LENGTH];
  196. message.length -= UA_SECURE_MESSAGE_HEADER_LENGTH;
  197. /* Encode the message type */
  198. size_t messagePos = 0;
  199. UA_NodeId typeId = contentType->typeId; /* always numeric */
  200. typeId.identifier.numeric = contentType->binaryEncodingId;
  201. UA_NodeId_encodeBinary(&typeId, &message, &messagePos);
  202. /* Encode with the chunking callback */
  203. UA_ChunkInfo ci;
  204. ci.channel = channel;
  205. ci.requestId = requestId;
  206. ci.chunksSoFar = 0;
  207. ci.messageSizeSoFar = 0;
  208. ci.final = false;
  209. ci.messageType = UA_MESSAGETYPE_MSG;
  210. ci.errorCode = UA_STATUSCODE_GOOD;
  211. if(typeId.identifier.numeric == 446 || typeId.identifier.numeric == 449)
  212. ci.messageType = UA_MESSAGETYPE_OPN;
  213. else if(typeId.identifier.numeric == 452 || typeId.identifier.numeric == 455)
  214. ci.messageType = UA_MESSAGETYPE_CLO;
  215. retval = UA_encodeBinary(content, contentType, (UA_exchangeEncodeBuffer)UA_SecureChannel_sendChunk,
  216. &ci, &message, &messagePos);
  217. /* Encoding failed, release the message */
  218. if(retval != UA_STATUSCODE_GOOD) {
  219. if(!ci.final) {
  220. /* the abort message was not send */
  221. ci.errorCode = retval;
  222. UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  223. }
  224. return retval;
  225. }
  226. /* Encoding finished, send the final chunk */
  227. ci.final = UA_TRUE;
  228. return UA_SecureChannel_sendChunk(&ci, &message, messagePos);
  229. }
  230. /***************************/
  231. /* Process Received Chunks */
  232. /***************************/
  233. static void
  234. UA_SecureChannel_removeChunk(UA_SecureChannel *channel, UA_UInt32 requestId) {
  235. struct ChunkEntry *ch;
  236. LIST_FOREACH(ch, &channel->chunks, pointers) {
  237. if(ch->requestId == requestId) {
  238. UA_ByteString_deleteMembers(&ch->bytes);
  239. LIST_REMOVE(ch, pointers);
  240. UA_free(ch);
  241. return;
  242. }
  243. }
  244. }
  245. /* assume that chunklength fits */
  246. static void
  247. appendChunk(struct ChunkEntry *ch, const UA_ByteString *msg,
  248. size_t offset, size_t chunklength) {
  249. UA_Byte* new_bytes = UA_realloc(ch->bytes.data, ch->bytes.length + chunklength);
  250. if(!new_bytes) {
  251. UA_ByteString_deleteMembers(&ch->bytes);
  252. return;
  253. }
  254. ch->bytes.data = new_bytes;
  255. memcpy(&ch->bytes.data[ch->bytes.length], &msg->data[offset], chunklength);
  256. ch->bytes.length += chunklength;
  257. }
  258. static void
  259. UA_SecureChannel_appendChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  260. const UA_ByteString *msg, size_t offset,
  261. size_t chunklength) {
  262. /* Check if the chunk fits into the message */
  263. if(msg->length - offset < chunklength) {
  264. /* can't process all chunks for that request */
  265. UA_SecureChannel_removeChunk(channel, requestId);
  266. return;
  267. }
  268. /* Get the chunkentry */
  269. struct ChunkEntry *ch;
  270. LIST_FOREACH(ch, &channel->chunks, pointers) {
  271. if(ch->requestId == requestId)
  272. break;
  273. }
  274. /* No chunkentry on the channel, create one */
  275. if(!ch) {
  276. ch = UA_malloc(sizeof(struct ChunkEntry));
  277. if(!ch)
  278. return;
  279. ch->requestId = requestId;
  280. UA_ByteString_init(&ch->bytes);
  281. LIST_INSERT_HEAD(&channel->chunks, ch, pointers);
  282. }
  283. appendChunk(ch, msg, offset, chunklength);
  284. }
  285. static UA_ByteString
  286. UA_SecureChannel_finalizeChunk(UA_SecureChannel *channel, UA_UInt32 requestId,
  287. const UA_ByteString *msg, size_t offset,
  288. size_t chunklength, UA_Boolean *deleteChunk) {
  289. if(msg->length - offset < chunklength) {
  290. /* can't process all chunks for that request */
  291. UA_SecureChannel_removeChunk(channel, requestId);
  292. return UA_BYTESTRING_NULL;
  293. }
  294. struct ChunkEntry *ch;
  295. LIST_FOREACH(ch, &channel->chunks, pointers) {
  296. if(ch->requestId == requestId)
  297. break;
  298. }
  299. UA_ByteString bytes;
  300. if(!ch) {
  301. *deleteChunk = false;
  302. bytes.length = chunklength;
  303. bytes.data = msg->data + offset;
  304. } else {
  305. *deleteChunk = true;
  306. appendChunk(ch, msg, offset, chunklength);
  307. bytes = ch->bytes;
  308. LIST_REMOVE(ch, pointers);
  309. UA_free(ch);
  310. }
  311. return bytes;
  312. }
  313. static UA_StatusCode
  314. UA_SecureChannel_processSequenceNumber(UA_SecureChannel *channel, UA_UInt32 SequenceNumber) {
  315. /* Does the sequence number match? */
  316. if(SequenceNumber != channel->receiveSequenceNumber + 1) {
  317. if(channel->receiveSequenceNumber + 1 > 4294966271 && SequenceNumber < 1024)
  318. channel->receiveSequenceNumber = SequenceNumber - 1; /* Roll over */
  319. else
  320. return UA_STATUSCODE_BADSECURITYCHECKSFAILED;
  321. }
  322. channel->receiveSequenceNumber++;
  323. return UA_STATUSCODE_GOOD;
  324. }
  325. UA_StatusCode
  326. UA_SecureChannel_processChunks(UA_SecureChannel *channel, const UA_ByteString *chunks,
  327. UA_ProcessMessageCallback callback, void *application) {
  328. size_t offset= 0;
  329. do {
  330. size_t initial_offset = offset;
  331. /* Decode header */
  332. UA_SecureConversationMessageHeader header;
  333. UA_StatusCode retval = UA_SecureConversationMessageHeader_decodeBinary(chunks, &offset, &header);
  334. if(retval != UA_STATUSCODE_GOOD)
  335. return retval;
  336. /* Is the channel attached to connection? */
  337. if(header.secureChannelId != channel->securityToken.channelId) {
  338. //Service_CloseSecureChannel(server, channel);
  339. //connection->close(connection);
  340. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  341. }
  342. /* Use requestId = 0 with OPN as argument for the callback */
  343. UA_SequenceHeader sequenceHeader;
  344. UA_SequenceHeader_init(&sequenceHeader);
  345. if((header.messageHeader.messageTypeAndChunkType & 0x00ffffff) != UA_MESSAGETYPE_OPN) {
  346. /* Check the symmetric security header (not for OPN) */
  347. UA_UInt32 tokenId = 0;
  348. retval |= UA_UInt32_decodeBinary(chunks, &offset, &tokenId);
  349. retval |= UA_SequenceHeader_decodeBinary(chunks, &offset, &sequenceHeader);
  350. if(retval != UA_STATUSCODE_GOOD)
  351. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  352. /* Does the token match? */
  353. if(tokenId != channel->securityToken.tokenId) {
  354. if(tokenId != channel->nextSecurityToken.tokenId)
  355. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  356. UA_SecureChannel_revolveTokens(channel);
  357. }
  358. /* Does the sequence number match? */
  359. retval = UA_SecureChannel_processSequenceNumber(channel, sequenceHeader.sequenceNumber);
  360. if(retval != UA_STATUSCODE_GOOD)
  361. return UA_STATUSCODE_BADCOMMUNICATIONERROR;
  362. }
  363. /* Process chunk */
  364. size_t processed_header = offset - initial_offset;
  365. switch(header.messageHeader.messageTypeAndChunkType & 0xff000000) {
  366. case UA_CHUNKTYPE_INTERMEDIATE:
  367. UA_SecureChannel_appendChunk(channel, sequenceHeader.requestId, chunks, offset,
  368. header.messageHeader.messageSize - processed_header);
  369. break;
  370. case UA_CHUNKTYPE_FINAL: {
  371. UA_Boolean deleteMessage = false;
  372. UA_ByteString message =
  373. UA_SecureChannel_finalizeChunk(channel, sequenceHeader.requestId, chunks, offset,
  374. header.messageHeader.messageSize - processed_header,
  375. &deleteMessage);
  376. if(message.length > 0) {
  377. callback(application, channel, header.messageHeader.messageTypeAndChunkType & 0x00ffffff,
  378. sequenceHeader.requestId, &message);
  379. if(deleteMessage)
  380. UA_ByteString_deleteMembers(&message);
  381. }
  382. break; }
  383. case UA_CHUNKTYPE_ABORT:
  384. UA_SecureChannel_removeChunk(channel, sequenceHeader.requestId);
  385. break;
  386. default:
  387. return UA_STATUSCODE_BADDECODINGERROR;
  388. }
  389. /* Jump to the end of the chunk */
  390. offset += (header.messageHeader.messageSize - processed_header);
  391. } while(chunks->length > offset);
  392. return UA_STATUSCODE_GOOD;
  393. }