ua_services_session.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2014, 2017 (c) Florian Palm
  7. * Copyright 2014-2016 (c) Sten Grüner
  8. * Copyright 2015 (c) Chris Iatrou
  9. * Copyright 2015 (c) Oleksiy Vasylyev
  10. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  11. * Copyright 2017-2018 (c) Mark Giraud, Fraunhofer IOSB
  12. */
  13. #include "ua_services.h"
  14. #include "ua_server_internal.h"
  15. #include "ua_session_manager.h"
  16. #include "ua_types_generated_handling.h"
  17. static UA_StatusCode
  18. signCreateSessionResponse(UA_Server *server, UA_SecureChannel *channel,
  19. const UA_CreateSessionRequest *request,
  20. UA_CreateSessionResponse *response) {
  21. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  22. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  23. return UA_STATUSCODE_GOOD;
  24. const UA_SecurityPolicy *const securityPolicy = channel->securityPolicy;
  25. UA_SignatureData *signatureData = &response->serverSignature;
  26. /* Prepare the signature */
  27. size_t signatureSize = securityPolicy->certificateSigningAlgorithm.
  28. getLocalSignatureSize(securityPolicy, channel->channelContext);
  29. UA_StatusCode retval = UA_String_copy(&securityPolicy->certificateSigningAlgorithm.uri,
  30. &signatureData->algorithm);
  31. retval |= UA_ByteString_allocBuffer(&signatureData->signature, signatureSize);
  32. if(retval != UA_STATUSCODE_GOOD)
  33. return retval;
  34. /* Allocate a temp buffer */
  35. size_t dataToSignSize = request->clientCertificate.length + request->clientNonce.length;
  36. UA_ByteString dataToSign;
  37. retval = UA_ByteString_allocBuffer(&dataToSign, dataToSignSize);
  38. if(retval != UA_STATUSCODE_GOOD)
  39. return retval; /* signatureData->signature is cleaned up with the response */
  40. /* Sign the signature */
  41. memcpy(dataToSign.data, request->clientCertificate.data, request->clientCertificate.length);
  42. memcpy(dataToSign.data + request->clientCertificate.length,
  43. request->clientNonce.data, request->clientNonce.length);
  44. retval = securityPolicy->certificateSigningAlgorithm.
  45. sign(securityPolicy, channel->channelContext, &dataToSign, &signatureData->signature);
  46. /* Clean up */
  47. UA_ByteString_deleteMembers(&dataToSign);
  48. return retval;
  49. }
  50. void
  51. Service_CreateSession(UA_Server *server, UA_SecureChannel *channel,
  52. const UA_CreateSessionRequest *request,
  53. UA_CreateSessionResponse *response) {
  54. if(!channel) {
  55. response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  56. return;
  57. }
  58. if(!channel->connection) {
  59. response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR;
  60. return;
  61. }
  62. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel, "Trying to create session");
  63. if(channel->securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  64. channel->securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  65. if(!UA_ByteString_equal(&request->clientCertificate,
  66. &channel->remoteCertificate)) {
  67. response->responseHeader.serviceResult = UA_STATUSCODE_BADCERTIFICATEINVALID;
  68. return;
  69. }
  70. }
  71. if(channel->securityToken.channelId == 0) {
  72. response->responseHeader.serviceResult = UA_STATUSCODE_BADSECURECHANNELIDINVALID;
  73. return;
  74. }
  75. if(!UA_ByteString_equal(&channel->securityPolicy->policyUri,
  76. &UA_SECURITY_POLICY_NONE_URI) &&
  77. request->clientNonce.length < 32) {
  78. response->responseHeader.serviceResult = UA_STATUSCODE_BADNONCEINVALID;
  79. return;
  80. }
  81. /* TODO: Compare application URI with certificate uri (decode certificate) */
  82. /* Allocate the response */
  83. response->serverEndpoints = (UA_EndpointDescription *)
  84. UA_Array_new(server->config.endpointsSize,
  85. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  86. if(!response->serverEndpoints) {
  87. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  88. return;
  89. }
  90. response->serverEndpointsSize = server->config.endpointsSize;
  91. /* Copy the server's endpointdescriptions into the response */
  92. for(size_t i = 0; i < server->config.endpointsSize; ++i)
  93. response->responseHeader.serviceResult |=
  94. UA_EndpointDescription_copy(&server->config.endpoints[i].endpointDescription,
  95. &response->serverEndpoints[i]);
  96. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
  97. return;
  98. /* Mirror back the endpointUrl */
  99. for(size_t i = 0; i < response->serverEndpointsSize; ++i) {
  100. UA_String_deleteMembers(&response->serverEndpoints[i].endpointUrl);
  101. UA_String_copy(&request->endpointUrl,
  102. &response->serverEndpoints[i].endpointUrl);
  103. }
  104. UA_Session *newSession = NULL;
  105. response->responseHeader.serviceResult =
  106. UA_SessionManager_createSession(&server->sessionManager, channel, request, &newSession);
  107. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  108. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  109. "Processing CreateSessionRequest failed");
  110. return;
  111. }
  112. UA_assert(newSession != NULL);
  113. /* Attach the session to the channel. But don't activate for now. */
  114. UA_Session_attachToSecureChannel(newSession, channel);
  115. /* Fill the session information */
  116. newSession->maxResponseMessageSize = request->maxResponseMessageSize;
  117. newSession->maxRequestMessageSize =
  118. channel->connection->localConf.maxMessageSize;
  119. response->responseHeader.serviceResult |=
  120. UA_ApplicationDescription_copy(&request->clientDescription,
  121. &newSession->clientDescription);
  122. /* Prepare the response */
  123. response->sessionId = newSession->sessionId;
  124. response->revisedSessionTimeout = (UA_Double)newSession->timeout;
  125. response->authenticationToken = newSession->header.authenticationToken;
  126. response->responseHeader.serviceResult =
  127. UA_String_copy(&request->sessionName, &newSession->sessionName);
  128. if(server->config.endpointsSize > 0)
  129. response->responseHeader.serviceResult |=
  130. UA_ByteString_copy(&channel->securityPolicy->localCertificate,
  131. &response->serverCertificate);
  132. /* Create a session nonce */
  133. response->responseHeader.serviceResult = UA_Session_generateNonce(newSession);
  134. response->responseHeader.serviceResult |=
  135. UA_ByteString_copy(&newSession->serverNonce, &response->serverNonce);
  136. /* Sign the signature */
  137. response->responseHeader.serviceResult |=
  138. signCreateSessionResponse(server, channel, request, response);
  139. /* Failure -> remove the session */
  140. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  141. UA_SessionManager_removeSession(&server->sessionManager,
  142. &newSession->header.authenticationToken);
  143. return;
  144. }
  145. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  146. "Session " UA_PRINTF_GUID_FORMAT " created",
  147. UA_PRINTF_GUID_DATA(newSession->sessionId.identifier.guid));
  148. }
  149. static UA_StatusCode
  150. checkSignature(const UA_Server *server, const UA_SecureChannel *channel,
  151. UA_Session *session, const UA_ActivateSessionRequest *request) {
  152. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  153. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  154. return UA_STATUSCODE_GOOD;
  155. if(!channel->securityPolicy)
  156. return UA_STATUSCODE_BADINTERNALERROR;
  157. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  158. const UA_ByteString *localCertificate = &securityPolicy->localCertificate;
  159. size_t dataToVerifySize = localCertificate->length + session->serverNonce.length;
  160. UA_ByteString dataToVerify;
  161. UA_StatusCode retval = UA_ByteString_allocBuffer(&dataToVerify, dataToVerifySize);
  162. if(retval != UA_STATUSCODE_GOOD)
  163. return retval;
  164. memcpy(dataToVerify.data, localCertificate->data, localCertificate->length);
  165. memcpy(dataToVerify.data + localCertificate->length,
  166. session->serverNonce.data, session->serverNonce.length);
  167. retval = securityPolicy->certificateSigningAlgorithm.verify(securityPolicy, channel->channelContext, &dataToVerify,
  168. &request->clientSignature.signature);
  169. UA_ByteString_deleteMembers(&dataToVerify);
  170. return retval;
  171. }
  172. /* TODO: Check all of the following:
  173. *
  174. * Part 4, §5.6.3: When the ActivateSession Service is called for the first time
  175. * then the Server shall reject the request if the SecureChannel is not same as
  176. * the one associated with the CreateSession request. Subsequent calls to
  177. * ActivateSession may be associated with different SecureChannels. If this is
  178. * the case then the Server shall verify that the Certificate the Client used to
  179. * create the new SecureChannel is the same as the Certificate used to create
  180. * the original SecureChannel. In addition, the Server shall verify that the
  181. * Client supplied a UserIdentityToken that is identical to the token currently
  182. * associated with the Session. Once the Server accepts the new SecureChannel it
  183. * shall reject requests sent via the old SecureChannel. */
  184. void
  185. Service_ActivateSession(UA_Server *server, UA_SecureChannel *channel,
  186. UA_Session *session, const UA_ActivateSessionRequest *request,
  187. UA_ActivateSessionResponse *response) {
  188. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Execute ActivateSession");
  189. if(session->validTill < UA_DateTime_nowMonotonic()) {
  190. UA_LOG_INFO_SESSION(server->config.logger, session,
  191. "ActivateSession: SecureChannel %i wants "
  192. "to activate, but the session has timed out",
  193. channel->securityToken.channelId);
  194. response->responseHeader.serviceResult =
  195. UA_STATUSCODE_BADSESSIONIDINVALID;
  196. return;
  197. }
  198. /* Check if the signature corresponds to the ServerNonce that was last sent
  199. * to the client */
  200. response->responseHeader.serviceResult = checkSignature(server, channel, session, request);
  201. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  202. UA_LOG_INFO_SESSION(server->config.logger, session,
  203. "Signature check failed with status code %s",
  204. UA_StatusCode_name(response->responseHeader.serviceResult));
  205. return;
  206. }
  207. /* Callback into userland access control */
  208. response->responseHeader.serviceResult =
  209. server->config.accessControl.activateSession(server, &server->config.accessControl,
  210. &session->sessionId, &request->userIdentityToken,
  211. &session->sessionHandle);
  212. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  213. UA_LOG_INFO_SESSION(server->config.logger, session,
  214. "ActivateSession: Could not generate a server nonce");
  215. return;
  216. }
  217. if(session->header.channel && session->header.channel != channel) {
  218. UA_LOG_INFO_SESSION(server->config.logger, session,
  219. "ActivateSession: Detach from old channel");
  220. /* Detach the old SecureChannel and attach the new */
  221. UA_Session_detachFromSecureChannel(session);
  222. UA_Session_attachToSecureChannel(session, channel);
  223. }
  224. /* Activate the session */
  225. session->activated = true;
  226. UA_Session_updateLifetime(session);
  227. /* Generate a new session nonce for the next time ActivateSession is called */
  228. response->responseHeader.serviceResult = UA_Session_generateNonce(session);
  229. response->responseHeader.serviceResult |=
  230. UA_ByteString_copy(&session->serverNonce, &response->serverNonce);
  231. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  232. UA_Session_detachFromSecureChannel(session);
  233. session->activated = false;
  234. UA_LOG_INFO_SESSION(server->config.logger, session,
  235. "ActivateSession: Could not generate a server nonce");
  236. return;
  237. }
  238. UA_LOG_INFO_SESSION(server->config.logger, session,
  239. "ActivateSession: Session activated");
  240. }
  241. void
  242. Service_CloseSession(UA_Server *server, UA_Session *session,
  243. const UA_CloseSessionRequest *request,
  244. UA_CloseSessionResponse *response) {
  245. UA_LOG_INFO_SESSION(server->config.logger, session, "CloseSession");
  246. /* Callback into userland access control */
  247. server->config.accessControl.closeSession(server, &server->config.accessControl,
  248. &session->sessionId, session->sessionHandle);
  249. response->responseHeader.serviceResult =
  250. UA_SessionManager_removeSession(&server->sessionManager,
  251. &session->header.authenticationToken);
  252. }