ua_services_session.c 18 KB

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