ua_securechannel_manager.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2014-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2014-2017 (c) Florian Palm
  7. * Copyright 2015-2016 (c) Sten Grüner
  8. * Copyright 2015 (c) Oleksiy Vasylyev
  9. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  10. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  11. */
  12. #include "ua_securechannel_manager.h"
  13. #include "ua_session.h"
  14. #include "ua_server_internal.h"
  15. #include "ua_transport_generated_handling.h"
  16. #define STARTCHANNELID 1
  17. #define STARTTOKENID 1
  18. UA_StatusCode
  19. UA_SecureChannelManager_init(UA_SecureChannelManager *cm, UA_Server *server) {
  20. TAILQ_INIT(&cm->channels);
  21. // TODO: use an ID that is likely to be unique after a restart
  22. cm->lastChannelId = STARTCHANNELID;
  23. cm->lastTokenId = STARTTOKENID;
  24. cm->currentChannelCount = 0;
  25. cm->server = server;
  26. return UA_STATUSCODE_GOOD;
  27. }
  28. void
  29. UA_SecureChannelManager_deleteMembers(UA_SecureChannelManager *cm) {
  30. channel_entry *entry, *temp;
  31. TAILQ_FOREACH_SAFE(entry, &cm->channels, pointers, temp) {
  32. TAILQ_REMOVE(&cm->channels, entry, pointers);
  33. UA_SecureChannel_deleteMembersCleanup(&entry->channel);
  34. UA_free(entry);
  35. }
  36. }
  37. static void
  38. removeSecureChannelCallback(void *_, channel_entry *entry) {
  39. UA_SecureChannel_deleteMembersCleanup(&entry->channel);
  40. }
  41. static void
  42. removeSecureChannel(UA_SecureChannelManager *cm, channel_entry *entry) {
  43. /* Detach the channel and make the capacity available */
  44. TAILQ_REMOVE(&cm->channels, entry, pointers);
  45. UA_atomic_subUInt32(&cm->currentChannelCount, 1);
  46. /* Add a delayed callback to remove the channel when the currently
  47. * scheduled jobs have completed */
  48. entry->cleanupCallback.callback = (UA_ApplicationCallback)removeSecureChannelCallback;
  49. entry->cleanupCallback.application = NULL;
  50. entry->cleanupCallback.data = entry;
  51. UA_WorkQueue_enqueueDelayed(&cm->server->workQueue, &entry->cleanupCallback);
  52. }
  53. /* remove channels that were not renewed or who have no connection attached */
  54. void
  55. UA_SecureChannelManager_cleanupTimedOut(UA_SecureChannelManager *cm, UA_DateTime nowMonotonic) {
  56. channel_entry *entry, *temp;
  57. TAILQ_FOREACH_SAFE(entry, &cm->channels, pointers, temp) {
  58. UA_DateTime timeout = entry->channel.securityToken.createdAt +
  59. (UA_DateTime)(entry->channel.securityToken.revisedLifetime * UA_DATETIME_MSEC);
  60. if(timeout < nowMonotonic || !entry->channel.connection) {
  61. UA_LOG_INFO_CHANNEL(cm->server->config.logger, &entry->channel,
  62. "SecureChannel has timed out");
  63. removeSecureChannel(cm, entry);
  64. } else if(entry->channel.nextSecurityToken.tokenId > 0) {
  65. UA_SecureChannel_revolveTokens(&entry->channel);
  66. }
  67. }
  68. }
  69. /* remove the first channel that has no session attached */
  70. static UA_Boolean
  71. purgeFirstChannelWithoutSession(UA_SecureChannelManager *cm) {
  72. channel_entry *entry;
  73. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  74. if(LIST_EMPTY(&entry->channel.sessions)) {
  75. UA_LOG_INFO_CHANNEL(cm->server->config.logger, &entry->channel,
  76. "Channel was purged since maxSecureChannels was "
  77. "reached and channel had no session attached");
  78. removeSecureChannel(cm, entry);
  79. return true;
  80. }
  81. }
  82. return false;
  83. }
  84. UA_StatusCode
  85. UA_SecureChannelManager_create(UA_SecureChannelManager *const cm, UA_Connection *const connection,
  86. const UA_SecurityPolicy *const securityPolicy,
  87. const UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  88. /* connection already has a channel attached. */
  89. if(connection->channel != NULL)
  90. return UA_STATUSCODE_BADINTERNALERROR;
  91. /* Check if there exists a free SC, otherwise try to purge one SC without a
  92. * session the purge has been introduced to pass CTT, it is not clear what
  93. * strategy is expected here */
  94. if(cm->currentChannelCount >= cm->server->config.maxSecureChannels &&
  95. !purgeFirstChannelWithoutSession(cm))
  96. return UA_STATUSCODE_BADOUTOFMEMORY;
  97. UA_LOG_INFO(cm->server->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  98. "Creating a new SecureChannel");
  99. channel_entry *entry = (channel_entry *)UA_malloc(sizeof(channel_entry));
  100. if(!entry)
  101. return UA_STATUSCODE_BADOUTOFMEMORY;
  102. /* Create the channel context and parse the sender (remote) certificate used for the
  103. * secureChannel. */
  104. UA_SecureChannel_init(&entry->channel);
  105. UA_StatusCode retval =
  106. UA_SecureChannel_setSecurityPolicy(&entry->channel, securityPolicy,
  107. &asymHeader->senderCertificate);
  108. if(retval != UA_STATUSCODE_GOOD) {
  109. UA_free(entry);
  110. return retval;
  111. }
  112. /* Channel state is fresh (0) */
  113. entry->channel.securityToken.channelId = 0;
  114. entry->channel.securityToken.tokenId = cm->lastTokenId++;
  115. entry->channel.securityToken.createdAt = UA_DateTime_now();
  116. entry->channel.securityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  117. TAILQ_INSERT_TAIL(&cm->channels, entry, pointers);
  118. UA_atomic_addUInt32(&cm->currentChannelCount, 1);
  119. UA_Connection_attachSecureChannel(connection, &entry->channel);
  120. return UA_STATUSCODE_GOOD;
  121. }
  122. UA_StatusCode
  123. UA_SecureChannelManager_open(UA_SecureChannelManager *cm, UA_SecureChannel *channel,
  124. const UA_OpenSecureChannelRequest *request,
  125. UA_OpenSecureChannelResponse *response) {
  126. if(channel->state != UA_SECURECHANNELSTATE_FRESH) {
  127. UA_LOG_ERROR_CHANNEL(cm->server->config.logger, channel,
  128. "Called open on already open or closed channel");
  129. return UA_STATUSCODE_BADINTERNALERROR;
  130. }
  131. if(request->securityMode != UA_MESSAGESECURITYMODE_NONE &&
  132. UA_ByteString_equal(&channel->securityPolicy->policyUri, &UA_SECURITY_POLICY_NONE_URI)) {
  133. return UA_STATUSCODE_BADSECURITYMODEREJECTED;
  134. }
  135. channel->securityMode = request->securityMode;
  136. channel->securityToken.createdAt = UA_DateTime_nowMonotonic();
  137. channel->securityToken.channelId = cm->lastChannelId++;
  138. channel->securityToken.createdAt = UA_DateTime_now();
  139. /* Set the lifetime. Lifetime 0 -> set the maximum possible */
  140. channel->securityToken.revisedLifetime =
  141. (request->requestedLifetime > cm->server->config.maxSecurityTokenLifetime) ?
  142. cm->server->config.maxSecurityTokenLifetime : request->requestedLifetime;
  143. if(channel->securityToken.revisedLifetime == 0)
  144. channel->securityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  145. /* Set the nonces and generate the keys */
  146. UA_StatusCode retval = UA_ByteString_copy(&request->clientNonce, &channel->remoteNonce);
  147. if(retval != UA_STATUSCODE_GOOD)
  148. return retval;
  149. retval = UA_SecureChannel_generateLocalNonce(channel);
  150. if(retval != UA_STATUSCODE_GOOD)
  151. return retval;
  152. retval = UA_SecureChannel_generateNewKeys(channel);
  153. if(retval != UA_STATUSCODE_GOOD)
  154. return retval;
  155. /* Set the response */
  156. retval = UA_ByteString_copy(&channel->localNonce, &response->serverNonce);
  157. if(retval != UA_STATUSCODE_GOOD)
  158. return retval;
  159. retval = UA_ChannelSecurityToken_copy(&channel->securityToken, &response->securityToken);
  160. if(retval != UA_STATUSCODE_GOOD)
  161. return retval;
  162. response->responseHeader.timestamp = UA_DateTime_now();
  163. response->responseHeader.requestHandle = request->requestHeader.requestHandle;
  164. /* The channel is open */
  165. channel->state = UA_SECURECHANNELSTATE_OPEN;
  166. return UA_STATUSCODE_GOOD;
  167. }
  168. UA_StatusCode
  169. UA_SecureChannelManager_renew(UA_SecureChannelManager *cm, UA_SecureChannel *channel,
  170. const UA_OpenSecureChannelRequest *request,
  171. UA_OpenSecureChannelResponse *response) {
  172. if(channel->state != UA_SECURECHANNELSTATE_OPEN) {
  173. UA_LOG_ERROR_CHANNEL(cm->server->config.logger, channel,
  174. "Called renew on channel which is not open");
  175. return UA_STATUSCODE_BADINTERNALERROR;
  176. }
  177. /* If no security token is already issued */
  178. if(channel->nextSecurityToken.tokenId == 0) {
  179. channel->nextSecurityToken.channelId = channel->securityToken.channelId;
  180. channel->nextSecurityToken.tokenId = cm->lastTokenId++;
  181. channel->nextSecurityToken.createdAt = UA_DateTime_now();
  182. channel->nextSecurityToken.revisedLifetime =
  183. (request->requestedLifetime > cm->server->config.maxSecurityTokenLifetime) ?
  184. cm->server->config.maxSecurityTokenLifetime : request->requestedLifetime;
  185. if(channel->nextSecurityToken.revisedLifetime == 0) /* lifetime 0 -> return the max lifetime */
  186. channel->nextSecurityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  187. }
  188. /* Replace the nonces */
  189. UA_ByteString_deleteMembers(&channel->remoteNonce);
  190. UA_StatusCode retval = UA_ByteString_copy(&request->clientNonce, &channel->remoteNonce);
  191. if(retval != UA_STATUSCODE_GOOD)
  192. return retval;
  193. retval = UA_SecureChannel_generateLocalNonce(channel);
  194. if(retval != UA_STATUSCODE_GOOD)
  195. return retval;
  196. /* Set the response */
  197. response->responseHeader.requestHandle = request->requestHeader.requestHandle;
  198. retval = UA_ByteString_copy(&channel->localNonce, &response->serverNonce);
  199. if(retval != UA_STATUSCODE_GOOD)
  200. return retval;
  201. retval = UA_ChannelSecurityToken_copy(&channel->nextSecurityToken, &response->securityToken);
  202. if(retval != UA_STATUSCODE_GOOD)
  203. return retval;
  204. /* Reset the internal creation date to the monotonic clock */
  205. channel->nextSecurityToken.createdAt = UA_DateTime_nowMonotonic();
  206. return UA_STATUSCODE_GOOD;
  207. }
  208. UA_SecureChannel *
  209. UA_SecureChannelManager_get(UA_SecureChannelManager *cm, UA_UInt32 channelId) {
  210. channel_entry *entry;
  211. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  212. if(entry->channel.securityToken.channelId == channelId)
  213. return &entry->channel;
  214. }
  215. return NULL;
  216. }
  217. UA_StatusCode
  218. UA_SecureChannelManager_close(UA_SecureChannelManager *cm, UA_UInt32 channelId) {
  219. channel_entry *entry;
  220. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  221. if(entry->channel.securityToken.channelId == channelId)
  222. break;
  223. }
  224. if(!entry)
  225. return UA_STATUSCODE_BADINTERNALERROR;
  226. removeSecureChannel(cm, entry);
  227. return UA_STATUSCODE_GOOD;
  228. }