ua_services_session.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. UA_CertificateVerification *cv = channel->securityPolicy->certificateVerification;
  83. if(cv && cv->verifyApplicationURI) {
  84. response->responseHeader.serviceResult =
  85. cv->verifyApplicationURI(cv->context, &request->clientCertificate,
  86. &request->clientDescription.applicationUri);
  87. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
  88. return;
  89. }
  90. /* Allocate the response */
  91. response->serverEndpoints = (UA_EndpointDescription *)
  92. UA_Array_new(server->config.endpointsSize,
  93. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  94. if(!response->serverEndpoints) {
  95. response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY;
  96. return;
  97. }
  98. response->serverEndpointsSize = server->config.endpointsSize;
  99. /* Copy the server's endpointdescriptions into the response */
  100. for(size_t i = 0; i < server->config.endpointsSize; ++i)
  101. response->responseHeader.serviceResult |=
  102. UA_EndpointDescription_copy(&server->config.endpoints[i].endpointDescription,
  103. &response->serverEndpoints[i]);
  104. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD)
  105. return;
  106. /* Mirror back the endpointUrl */
  107. for(size_t i = 0; i < response->serverEndpointsSize; ++i) {
  108. UA_String_deleteMembers(&response->serverEndpoints[i].endpointUrl);
  109. UA_String_copy(&request->endpointUrl,
  110. &response->serverEndpoints[i].endpointUrl);
  111. }
  112. UA_Session *newSession = NULL;
  113. response->responseHeader.serviceResult =
  114. UA_SessionManager_createSession(&server->sessionManager, channel, request, &newSession);
  115. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  116. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  117. "Processing CreateSessionRequest failed");
  118. return;
  119. }
  120. UA_assert(newSession != NULL);
  121. /* Attach the session to the channel. But don't activate for now. */
  122. UA_Session_attachToSecureChannel(newSession, channel);
  123. /* Fill the session information */
  124. newSession->maxResponseMessageSize = request->maxResponseMessageSize;
  125. newSession->maxRequestMessageSize =
  126. channel->connection->localConf.maxMessageSize;
  127. response->responseHeader.serviceResult |=
  128. UA_ApplicationDescription_copy(&request->clientDescription,
  129. &newSession->clientDescription);
  130. /* Prepare the response */
  131. response->sessionId = newSession->sessionId;
  132. response->revisedSessionTimeout = (UA_Double)newSession->timeout;
  133. response->authenticationToken = newSession->header.authenticationToken;
  134. response->responseHeader.serviceResult =
  135. UA_String_copy(&request->sessionName, &newSession->sessionName);
  136. if(server->config.endpointsSize > 0)
  137. response->responseHeader.serviceResult |=
  138. UA_ByteString_copy(&channel->securityPolicy->localCertificate,
  139. &response->serverCertificate);
  140. /* Create a session nonce */
  141. response->responseHeader.serviceResult = UA_Session_generateNonce(newSession);
  142. response->responseHeader.serviceResult |=
  143. UA_ByteString_copy(&newSession->serverNonce, &response->serverNonce);
  144. /* Sign the signature */
  145. response->responseHeader.serviceResult |=
  146. signCreateSessionResponse(server, channel, request, response);
  147. /* Failure -> remove the session */
  148. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  149. UA_SessionManager_removeSession(&server->sessionManager,
  150. &newSession->header.authenticationToken);
  151. return;
  152. }
  153. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  154. "Session " UA_PRINTF_GUID_FORMAT " created",
  155. UA_PRINTF_GUID_DATA(newSession->sessionId.identifier.guid));
  156. }
  157. static UA_StatusCode
  158. checkSignature(const UA_Server *server, const UA_SecureChannel *channel,
  159. UA_Session *session, const UA_ActivateSessionRequest *request) {
  160. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  161. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  162. return UA_STATUSCODE_GOOD;
  163. if(!channel->securityPolicy)
  164. return UA_STATUSCODE_BADINTERNALERROR;
  165. const UA_SecurityPolicy *securityPolicy = channel->securityPolicy;
  166. const UA_ByteString *localCertificate = &securityPolicy->localCertificate;
  167. size_t dataToVerifySize = localCertificate->length + session->serverNonce.length;
  168. UA_ByteString dataToVerify;
  169. UA_StatusCode retval = UA_ByteString_allocBuffer(&dataToVerify, dataToVerifySize);
  170. if(retval != UA_STATUSCODE_GOOD)
  171. return retval;
  172. memcpy(dataToVerify.data, localCertificate->data, localCertificate->length);
  173. memcpy(dataToVerify.data + localCertificate->length,
  174. session->serverNonce.data, session->serverNonce.length);
  175. retval = securityPolicy->certificateSigningAlgorithm.verify(securityPolicy, channel->channelContext, &dataToVerify,
  176. &request->clientSignature.signature);
  177. UA_ByteString_deleteMembers(&dataToVerify);
  178. return retval;
  179. }
  180. /* TODO: Check all of the following:
  181. *
  182. * Part 4, §5.6.3: When the ActivateSession Service is called for the first time
  183. * then the Server shall reject the request if the SecureChannel is not same as
  184. * the one associated with the CreateSession request. Subsequent calls to
  185. * ActivateSession may be associated with different SecureChannels. If this is
  186. * the case then the Server shall verify that the Certificate the Client used to
  187. * create the new SecureChannel is the same as the Certificate used to create
  188. * the original SecureChannel. In addition, the Server shall verify that the
  189. * Client supplied a UserIdentityToken that is identical to the token currently
  190. * associated with the Session. Once the Server accepts the new SecureChannel it
  191. * shall reject requests sent via the old SecureChannel. */
  192. void
  193. Service_ActivateSession(UA_Server *server, UA_SecureChannel *channel,
  194. UA_Session *session, const UA_ActivateSessionRequest *request,
  195. UA_ActivateSessionResponse *response) {
  196. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Execute ActivateSession");
  197. if(session->validTill < UA_DateTime_nowMonotonic()) {
  198. UA_LOG_INFO_SESSION(server->config.logger, session,
  199. "ActivateSession: SecureChannel %i wants "
  200. "to activate, but the session has timed out",
  201. channel->securityToken.channelId);
  202. response->responseHeader.serviceResult =
  203. UA_STATUSCODE_BADSESSIONIDINVALID;
  204. return;
  205. }
  206. /* Check if the signature corresponds to the ServerNonce that was last sent
  207. * to the client */
  208. response->responseHeader.serviceResult = checkSignature(server, channel, session, request);
  209. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  210. UA_LOG_INFO_SESSION(server->config.logger, session,
  211. "Signature check failed with status code %s",
  212. UA_StatusCode_name(response->responseHeader.serviceResult));
  213. return;
  214. }
  215. /* Find the matching endpoint */
  216. const UA_EndpointDescription *ed = NULL;
  217. for(size_t i = 0; ed == NULL && i < server->config.endpointsSize; ++i) {
  218. const UA_Endpoint *e = &server->config.endpoints[i];
  219. /* Match the Security Mode */
  220. if(e->endpointDescription.securityMode != channel->securityMode)
  221. continue;
  222. /* Match the SecurityPolicy */
  223. if(!UA_String_equal(&e->securityPolicy.policyUri,
  224. &channel->securityPolicy->policyUri))
  225. continue;
  226. /* Match the UserTokenType */
  227. for(size_t j = 0; j < e->endpointDescription.userIdentityTokensSize; j++) {
  228. const UA_UserTokenPolicy *u = &e->endpointDescription.userIdentityTokens[j];
  229. if(u->tokenType == UA_USERTOKENTYPE_ANONYMOUS) {
  230. if(request->userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN])
  231. continue;
  232. } else if(u->tokenType == UA_USERTOKENTYPE_USERNAME) {
  233. if(request->userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN])
  234. continue;
  235. } else if(u->tokenType == UA_USERTOKENTYPE_CERTIFICATE) {
  236. if(request->userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN])
  237. continue;
  238. } else if(u->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN) {
  239. if(request->userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN])
  240. continue;
  241. } else {
  242. response->responseHeader.serviceResult = UA_STATUSCODE_BADIDENTITYTOKENINVALID;
  243. return;
  244. }
  245. /* Match found */
  246. ed = &e->endpointDescription;
  247. break;
  248. }
  249. }
  250. /* No matching endpoint found */
  251. if(!ed) {
  252. response->responseHeader.serviceResult = UA_STATUSCODE_BADIDENTITYTOKENREJECTED;
  253. return;
  254. }
  255. /* Callback into userland access control */
  256. response->responseHeader.serviceResult =
  257. server->config.accessControl.activateSession(server, &server->config.accessControl,
  258. ed, &channel->remoteCertificate,
  259. &session->sessionId,
  260. &request->userIdentityToken,
  261. &session->sessionHandle);
  262. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  263. UA_LOG_INFO_SESSION(server->config.logger, session,
  264. "ActivateSession: Could not generate a server nonce");
  265. return;
  266. }
  267. if(session->header.channel && session->header.channel != channel) {
  268. UA_LOG_INFO_SESSION(server->config.logger, session,
  269. "ActivateSession: Detach from old channel");
  270. /* Detach the old SecureChannel and attach the new */
  271. UA_Session_detachFromSecureChannel(session);
  272. UA_Session_attachToSecureChannel(session, channel);
  273. }
  274. /* Activate the session */
  275. session->activated = true;
  276. UA_Session_updateLifetime(session);
  277. /* Generate a new session nonce for the next time ActivateSession is called */
  278. response->responseHeader.serviceResult = UA_Session_generateNonce(session);
  279. response->responseHeader.serviceResult |=
  280. UA_ByteString_copy(&session->serverNonce, &response->serverNonce);
  281. if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  282. UA_Session_detachFromSecureChannel(session);
  283. session->activated = false;
  284. UA_LOG_INFO_SESSION(server->config.logger, session,
  285. "ActivateSession: Could not generate a server nonce");
  286. return;
  287. }
  288. UA_LOG_INFO_SESSION(server->config.logger, session,
  289. "ActivateSession: Session activated");
  290. }
  291. void
  292. Service_CloseSession(UA_Server *server, UA_Session *session,
  293. const UA_CloseSessionRequest *request,
  294. UA_CloseSessionResponse *response) {
  295. UA_LOG_INFO_SESSION(server->config.logger, session, "CloseSession");
  296. /* Callback into userland access control */
  297. server->config.accessControl.closeSession(server, &server->config.accessControl,
  298. &session->sessionId, session->sessionHandle);
  299. response->responseHeader.serviceResult =
  300. UA_SessionManager_removeSession(&server->sessionManager,
  301. &session->header.authenticationToken);
  302. }