ua_services_session.c 17 KB

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