ua_securechannel_manager.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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(UA_Server *server, void *entry) {
  39. channel_entry *centry = (channel_entry *)entry;
  40. UA_SecureChannel_deleteMembersCleanup(&centry->channel);
  41. UA_free(entry);
  42. }
  43. static UA_StatusCode
  44. removeSecureChannel(UA_SecureChannelManager *cm, channel_entry *entry) {
  45. /* Add a delayed callback to remove the channel when the currently
  46. * scheduled jobs have completed */
  47. UA_StatusCode retval = UA_Server_delayedCallback(cm->server, removeSecureChannelCallback, entry);
  48. if(retval != UA_STATUSCODE_GOOD) {
  49. UA_LOG_WARNING(cm->server->config.logger, UA_LOGCATEGORY_SESSION,
  50. "Could not remove the secure channel with error code %s",
  51. UA_StatusCode_name(retval));
  52. return retval; /* Try again next time */
  53. }
  54. /* Detach the channel and make the capacity available */
  55. TAILQ_REMOVE(&cm->channels, entry, pointers);
  56. UA_atomic_subUInt32(&cm->currentChannelCount, 1);
  57. return UA_STATUSCODE_GOOD;
  58. }
  59. /* remove channels that were not renewed or who have no connection attached */
  60. void
  61. UA_SecureChannelManager_cleanupTimedOut(UA_SecureChannelManager *cm, UA_DateTime nowMonotonic) {
  62. channel_entry *entry, *temp;
  63. TAILQ_FOREACH_SAFE(entry, &cm->channels, pointers, temp) {
  64. UA_DateTime timeout = entry->channel.securityToken.createdAt +
  65. (UA_DateTime)(entry->channel.securityToken.revisedLifetime * UA_DATETIME_MSEC);
  66. if(timeout < nowMonotonic || !entry->channel.connection) {
  67. UA_LOG_INFO_CHANNEL(cm->server->config.logger, &entry->channel,
  68. "SecureChannel has timed out");
  69. removeSecureChannel(cm, entry);
  70. } else if(entry->channel.nextSecurityToken.tokenId > 0) {
  71. UA_SecureChannel_revolveTokens(&entry->channel);
  72. }
  73. }
  74. }
  75. /* remove the first channel that has no session attached */
  76. static UA_Boolean
  77. purgeFirstChannelWithoutSession(UA_SecureChannelManager *cm) {
  78. channel_entry *entry;
  79. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  80. if(LIST_EMPTY(&entry->channel.sessions)) {
  81. UA_LOG_INFO_CHANNEL(cm->server->config.logger, &entry->channel,
  82. "Channel was purged since maxSecureChannels was "
  83. "reached and channel had no session attached");
  84. removeSecureChannel(cm, entry);
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. UA_StatusCode
  91. UA_SecureChannelManager_create(UA_SecureChannelManager *const cm, UA_Connection *const connection,
  92. const UA_SecurityPolicy *const securityPolicy,
  93. const UA_AsymmetricAlgorithmSecurityHeader *const asymHeader) {
  94. /* connection already has a channel attached. */
  95. if(connection->channel != NULL)
  96. return UA_STATUSCODE_BADINTERNALERROR;
  97. /* Check if there exists a free SC, otherwise try to purge one SC without a
  98. * session the purge has been introduced to pass CTT, it is not clear what
  99. * strategy is expected here */
  100. if(cm->currentChannelCount >= cm->server->config.maxSecureChannels &&
  101. !purgeFirstChannelWithoutSession(cm))
  102. return UA_STATUSCODE_BADOUTOFMEMORY;
  103. UA_LOG_INFO(cm->server->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  104. "Creating a new SecureChannel");
  105. channel_entry *entry = (channel_entry *)UA_malloc(sizeof(channel_entry));
  106. if(!entry)
  107. return UA_STATUSCODE_BADOUTOFMEMORY;
  108. /* Create the channel context and parse the sender (remote) certificate used for the
  109. * secureChannel. */
  110. UA_StatusCode retval = UA_SecureChannel_init(&entry->channel, securityPolicy,
  111. &asymHeader->senderCertificate);
  112. if(retval != UA_STATUSCODE_GOOD) {
  113. UA_free(entry);
  114. return retval;
  115. }
  116. /* Channel state is fresh (0) */
  117. entry->channel.securityToken.channelId = 0;
  118. entry->channel.securityToken.tokenId = cm->lastTokenId++;
  119. entry->channel.securityToken.createdAt = UA_DateTime_now();
  120. entry->channel.securityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  121. TAILQ_INSERT_TAIL(&cm->channels, entry, pointers);
  122. UA_atomic_addUInt32(&cm->currentChannelCount, 1);
  123. UA_Connection_attachSecureChannel(connection, &entry->channel);
  124. return UA_STATUSCODE_GOOD;
  125. }
  126. UA_StatusCode
  127. UA_SecureChannelManager_open(UA_SecureChannelManager *cm, UA_SecureChannel *channel,
  128. const UA_OpenSecureChannelRequest *request,
  129. UA_OpenSecureChannelResponse *response) {
  130. if(channel->state != UA_SECURECHANNELSTATE_FRESH) {
  131. UA_LOG_ERROR_CHANNEL(cm->server->config.logger, channel,
  132. "Called open on already open or closed channel");
  133. return UA_STATUSCODE_BADINTERNALERROR;
  134. }
  135. if(request->securityMode != UA_MESSAGESECURITYMODE_NONE &&
  136. UA_ByteString_equal(&channel->securityPolicy->policyUri, &UA_SECURITY_POLICY_NONE_URI)) {
  137. return UA_STATUSCODE_BADSECURITYMODEREJECTED;
  138. }
  139. channel->securityMode = request->securityMode;
  140. channel->securityToken.createdAt = UA_DateTime_nowMonotonic();
  141. channel->securityToken.channelId = cm->lastChannelId++;
  142. channel->securityToken.createdAt = UA_DateTime_now();
  143. /* Set the lifetime. Lifetime 0 -> set the maximum possible */
  144. channel->securityToken.revisedLifetime =
  145. (request->requestedLifetime > cm->server->config.maxSecurityTokenLifetime) ?
  146. cm->server->config.maxSecurityTokenLifetime : request->requestedLifetime;
  147. if(channel->securityToken.revisedLifetime == 0)
  148. channel->securityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  149. /* Set the nonces and generate the keys */
  150. UA_StatusCode retval = UA_ByteString_copy(&request->clientNonce, &channel->remoteNonce);
  151. retval |= UA_SecureChannel_generateLocalNonce(channel);
  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. retval |= UA_ChannelSecurityToken_copy(&channel->securityToken, &response->securityToken);
  158. response->responseHeader.timestamp = UA_DateTime_now();
  159. response->responseHeader.requestHandle = request->requestHeader.requestHandle;
  160. if(retval != UA_STATUSCODE_GOOD)
  161. return retval;
  162. /* The channel is open */
  163. channel->state = UA_SECURECHANNELSTATE_OPEN;
  164. return UA_STATUSCODE_GOOD;
  165. }
  166. UA_StatusCode
  167. UA_SecureChannelManager_renew(UA_SecureChannelManager *cm, UA_SecureChannel *channel,
  168. const UA_OpenSecureChannelRequest *request,
  169. UA_OpenSecureChannelResponse *response) {
  170. if(channel->state != UA_SECURECHANNELSTATE_OPEN) {
  171. UA_LOG_ERROR_CHANNEL(cm->server->config.logger, channel,
  172. "Called renew on channel which is not open");
  173. return UA_STATUSCODE_BADINTERNALERROR;
  174. }
  175. /* If no security token is already issued */
  176. if(channel->nextSecurityToken.tokenId == 0) {
  177. channel->nextSecurityToken.channelId = channel->securityToken.channelId;
  178. channel->nextSecurityToken.tokenId = cm->lastTokenId++;
  179. channel->nextSecurityToken.createdAt = UA_DateTime_now();
  180. channel->nextSecurityToken.revisedLifetime =
  181. (request->requestedLifetime > cm->server->config.maxSecurityTokenLifetime) ?
  182. cm->server->config.maxSecurityTokenLifetime : request->requestedLifetime;
  183. if(channel->nextSecurityToken.revisedLifetime == 0) /* lifetime 0 -> return the max lifetime */
  184. channel->nextSecurityToken.revisedLifetime = cm->server->config.maxSecurityTokenLifetime;
  185. }
  186. /* Replace the nonces */
  187. UA_ByteString_deleteMembers(&channel->remoteNonce);
  188. UA_StatusCode retval = UA_ByteString_copy(&request->clientNonce, &channel->remoteNonce);
  189. retval |= UA_SecureChannel_generateLocalNonce(channel);
  190. if(retval != UA_STATUSCODE_GOOD)
  191. return retval;
  192. /* Set the response */
  193. response->responseHeader.requestHandle = request->requestHeader.requestHandle;
  194. retval = UA_ByteString_copy(&channel->localNonce, &response->serverNonce);
  195. retval |= UA_ChannelSecurityToken_copy(&channel->nextSecurityToken, &response->securityToken);
  196. if(retval != UA_STATUSCODE_GOOD)
  197. return retval;
  198. /* Reset the internal creation date to the monotonic clock */
  199. channel->nextSecurityToken.createdAt = UA_DateTime_nowMonotonic();
  200. return UA_STATUSCODE_GOOD;
  201. }
  202. UA_SecureChannel *
  203. UA_SecureChannelManager_get(UA_SecureChannelManager *cm, UA_UInt32 channelId) {
  204. channel_entry *entry;
  205. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  206. if(entry->channel.securityToken.channelId == channelId)
  207. return &entry->channel;
  208. }
  209. return NULL;
  210. }
  211. UA_StatusCode
  212. UA_SecureChannelManager_close(UA_SecureChannelManager *cm, UA_UInt32 channelId) {
  213. channel_entry *entry;
  214. TAILQ_FOREACH(entry, &cm->channels, pointers) {
  215. if(entry->channel.securityToken.channelId == channelId)
  216. break;
  217. }
  218. if(!entry)
  219. return UA_STATUSCODE_BADINTERNALERROR;
  220. return removeSecureChannel(cm, entry);
  221. }