ua_services_session.c 17 KB

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