ua_client_connect.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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 2017 (c) Mark Giraud, Fraunhofer IOSB
  6. * Copyright 2017-2018 (c) Thomas Stalder, Blue Time Concept SA
  7. * Copyright 2017-2019 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  8. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  9. * Copyright 2018 (c) Kalycito Infotech Private Limited
  10. */
  11. #include <open62541/transport_generated.h>
  12. #include <open62541/transport_generated_encoding_binary.h>
  13. #include <open62541/transport_generated_handling.h>
  14. #include <open62541/types_generated_encoding_binary.h>
  15. #include "ua_client_internal.h"
  16. /* Size are refered in bytes */
  17. #define UA_MINMESSAGESIZE 8192
  18. #define UA_SESSION_LOCALNONCELENGTH 32
  19. #define MAX_DATA_SIZE 4096
  20. /********************/
  21. /* Set client state */
  22. /********************/
  23. void
  24. setClientState(UA_Client *client, UA_ClientState state) {
  25. if(client->state != state) {
  26. client->state = state;
  27. if(client->config.stateCallback)
  28. client->config.stateCallback(client, client->state);
  29. }
  30. }
  31. /***********************/
  32. /* Open the Connection */
  33. /***********************/
  34. #define UA_BITMASK_MESSAGETYPE 0x00ffffffu
  35. #define UA_BITMASK_CHUNKTYPE 0xff000000u
  36. static UA_StatusCode
  37. processACKResponse(void *application, UA_Connection *connection, UA_ByteString *chunk) {
  38. UA_Client *client = (UA_Client*)application;
  39. /* Decode the message */
  40. size_t offset = 0;
  41. UA_StatusCode retval;
  42. UA_TcpMessageHeader messageHeader;
  43. UA_TcpAcknowledgeMessage ackMessage;
  44. retval = UA_TcpMessageHeader_decodeBinary(chunk, &offset, &messageHeader);
  45. if(retval != UA_STATUSCODE_GOOD) {
  46. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  47. "Decoding ACK message failed");
  48. return retval;
  49. }
  50. // check if we got an error response from the server
  51. UA_MessageType messageType = (UA_MessageType)
  52. (messageHeader.messageTypeAndChunkType & UA_BITMASK_MESSAGETYPE);
  53. UA_ChunkType chunkType = (UA_ChunkType)
  54. (messageHeader.messageTypeAndChunkType & UA_BITMASK_CHUNKTYPE);
  55. if (messageType == UA_MESSAGETYPE_ERR) {
  56. // Header + ErrorMessage (error + reasonLength_field + length)
  57. UA_StatusCode error = *(UA_StatusCode*)(&chunk->data[offset]);
  58. UA_UInt32 len = *((UA_UInt32*)&chunk->data[offset + 4]);
  59. UA_Byte *data = (UA_Byte*)&chunk->data[offset + 4+4];
  60. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  61. "Received ERR response. %s - %.*s", UA_StatusCode_name(error), len, data);
  62. return error;
  63. }
  64. if (chunkType != UA_CHUNKTYPE_FINAL) {
  65. return UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  66. }
  67. /* Decode the ACK message */
  68. retval = UA_TcpAcknowledgeMessage_decodeBinary(chunk, &offset, &ackMessage);
  69. if(retval != UA_STATUSCODE_GOOD) {
  70. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  71. "Decoding ACK message failed");
  72. return retval;
  73. }
  74. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK, "Received ACK message");
  75. /* Process the ACK message */
  76. return UA_Connection_processHELACK(connection, &client->config.localConnectionConfig,
  77. (const UA_ConnectionConfig*)&ackMessage);
  78. }
  79. static UA_StatusCode
  80. HelAckHandshake(UA_Client *client, const UA_String endpointUrl) {
  81. /* Get a buffer */
  82. UA_ByteString message;
  83. UA_Connection *conn = &client->connection;
  84. UA_StatusCode retval = conn->getSendBuffer(conn, UA_MINMESSAGESIZE, &message);
  85. if(retval != UA_STATUSCODE_GOOD)
  86. return retval;
  87. /* Prepare the HEL message and encode at offset 8 */
  88. UA_TcpHelloMessage hello;
  89. /* just reference to avoid copy */
  90. hello.endpointUrl = endpointUrl;
  91. memcpy(&hello, &client->config.localConnectionConfig,
  92. sizeof(UA_ConnectionConfig)); /* same struct layout */
  93. UA_Byte *bufPos = &message.data[8]; /* skip the header */
  94. const UA_Byte *bufEnd = &message.data[message.length];
  95. retval = UA_TcpHelloMessage_encodeBinary(&hello, &bufPos, bufEnd);
  96. /* avoid deleting reference */
  97. hello.endpointUrl = UA_STRING_NULL;
  98. UA_TcpHelloMessage_deleteMembers(&hello);
  99. if(retval != UA_STATUSCODE_GOOD) {
  100. conn->releaseSendBuffer(conn, &message);
  101. return retval;
  102. }
  103. /* Encode the message header at offset 0 */
  104. UA_TcpMessageHeader messageHeader;
  105. messageHeader.messageTypeAndChunkType = UA_CHUNKTYPE_FINAL + UA_MESSAGETYPE_HEL;
  106. messageHeader.messageSize = (UA_UInt32)((uintptr_t)bufPos - (uintptr_t)message.data);
  107. bufPos = message.data;
  108. retval = UA_TcpMessageHeader_encodeBinary(&messageHeader, &bufPos, bufEnd);
  109. if(retval != UA_STATUSCODE_GOOD) {
  110. conn->releaseSendBuffer(conn, &message);
  111. return retval;
  112. }
  113. /* Send the HEL message */
  114. message.length = messageHeader.messageSize;
  115. retval = conn->send(conn, &message);
  116. if(retval != UA_STATUSCODE_GOOD) {
  117. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  118. "Sending HEL failed");
  119. return retval;
  120. }
  121. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  122. "Sent HEL message");
  123. /* Loop until we have a complete chunk */
  124. retval = UA_Connection_receiveChunksBlocking(conn, client, processACKResponse,
  125. client->config.timeout);
  126. if(retval != UA_STATUSCODE_GOOD) {
  127. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  128. "Receiving ACK message failed with %s", UA_StatusCode_name(retval));
  129. if(retval == UA_STATUSCODE_BADCONNECTIONCLOSED)
  130. client->state = UA_CLIENTSTATE_DISCONNECTED;
  131. UA_Client_disconnect(client);
  132. }
  133. return retval;
  134. }
  135. UA_SecurityPolicy *
  136. getSecurityPolicy(UA_Client *client, UA_String policyUri) {
  137. for(size_t i = 0; i < client->config.securityPoliciesSize; i++) {
  138. if(UA_String_equal(&policyUri, &client->config.securityPolicies[i].policyUri))
  139. return &client->config.securityPolicies[i];
  140. }
  141. return NULL;
  142. }
  143. static void
  144. processDecodedOPNResponse(UA_Client *client, UA_OpenSecureChannelResponse *response,
  145. UA_Boolean renew) {
  146. /* Replace the token */
  147. if(renew)
  148. client->channel.nextSecurityToken = response->securityToken;
  149. else
  150. client->channel.securityToken = response->securityToken;
  151. /* Replace the nonce */
  152. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  153. client->channel.remoteNonce = response->serverNonce;
  154. UA_ByteString_init(&response->serverNonce);
  155. if(client->channel.state == UA_SECURECHANNELSTATE_OPEN)
  156. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  157. "SecureChannel renewed");
  158. else
  159. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  160. "Opened SecureChannel with SecurityPolicy %.*s",
  161. (int)client->channel.securityPolicy->policyUri.length,
  162. client->channel.securityPolicy->policyUri.data);
  163. /* Response.securityToken.revisedLifetime is UInt32 we need to cast it to
  164. * DateTime=Int64 we take 75% of lifetime to start renewing as described in
  165. * standard */
  166. client->channel.state = UA_SECURECHANNELSTATE_OPEN;
  167. client->nextChannelRenewal = UA_DateTime_nowMonotonic() + (UA_DateTime)
  168. (client->channel.securityToken.revisedLifetime * (UA_Double)UA_DATETIME_MSEC * 0.75);
  169. }
  170. UA_StatusCode
  171. openSecureChannel(UA_Client *client, UA_Boolean renew) {
  172. /* Check if sc is still valid */
  173. if(renew && client->nextChannelRenewal > UA_DateTime_nowMonotonic())
  174. return UA_STATUSCODE_GOOD;
  175. UA_Connection *conn = &client->connection;
  176. if(conn->state != UA_CONNECTION_ESTABLISHED)
  177. return UA_STATUSCODE_BADSERVERNOTCONNECTED;
  178. /* Prepare the OpenSecureChannelRequest */
  179. UA_OpenSecureChannelRequest opnSecRq;
  180. UA_OpenSecureChannelRequest_init(&opnSecRq);
  181. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  182. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  183. if(renew) {
  184. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  185. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  186. "Requesting to renew the SecureChannel");
  187. } else {
  188. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  189. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  190. "Requesting to open a SecureChannel");
  191. }
  192. /* Set the securityMode to input securityMode from client data */
  193. opnSecRq.securityMode = client->channel.securityMode;
  194. opnSecRq.clientNonce = client->channel.localNonce;
  195. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  196. /* Send the OPN message */
  197. UA_UInt32 requestId = ++client->requestId;
  198. UA_StatusCode retval =
  199. UA_SecureChannel_sendAsymmetricOPNMessage(&client->channel, requestId, &opnSecRq,
  200. &UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST]);
  201. if(retval != UA_STATUSCODE_GOOD) {
  202. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  203. "Sending OPN message failed with error %s", UA_StatusCode_name(retval));
  204. UA_Client_disconnect(client);
  205. return retval;
  206. }
  207. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "OPN message sent");
  208. /* Increase nextChannelRenewal to avoid that we re-start renewal when
  209. * publish responses are received before the OPN response arrives. */
  210. client->nextChannelRenewal = UA_DateTime_nowMonotonic() +
  211. (2 * ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC));
  212. /* Receive / decrypt / decode the OPN response. Process async services in
  213. * the background until the OPN response arrives. */
  214. UA_OpenSecureChannelResponse response;
  215. retval = receiveServiceResponse(client, &response,
  216. &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE],
  217. UA_DateTime_nowMonotonic() +
  218. ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC),
  219. &requestId);
  220. if(retval != UA_STATUSCODE_GOOD) {
  221. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  222. "Receiving service response failed with error %s", UA_StatusCode_name(retval));
  223. UA_Client_disconnect(client);
  224. return retval;
  225. }
  226. processDecodedOPNResponse(client, &response, renew);
  227. UA_OpenSecureChannelResponse_deleteMembers(&response);
  228. return retval;
  229. }
  230. /* Function to verify the signature corresponds to ClientNonce
  231. * using the local certificate */
  232. static UA_StatusCode
  233. checkClientSignature(const UA_SecureChannel *channel,
  234. const UA_CreateSessionResponse *response) {
  235. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  236. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  237. return UA_STATUSCODE_GOOD;
  238. if(!channel->securityPolicy)
  239. return UA_STATUSCODE_BADINTERNALERROR;
  240. const UA_SecurityPolicy *sp = channel->securityPolicy;
  241. const UA_ByteString *lc = &sp->localCertificate;
  242. size_t dataToVerifySize = lc->length + channel->localNonce.length;
  243. UA_ByteString dataToVerify = UA_BYTESTRING_NULL;
  244. UA_StatusCode retval = UA_ByteString_allocBuffer(&dataToVerify, dataToVerifySize);
  245. if(retval != UA_STATUSCODE_GOOD)
  246. return retval;
  247. memcpy(dataToVerify.data, lc->data, lc->length);
  248. memcpy(dataToVerify.data + lc->length,
  249. channel->localNonce.data, channel->localNonce.length);
  250. retval = sp->certificateSigningAlgorithm.
  251. verify(sp, channel->channelContext, &dataToVerify,
  252. &response->serverSignature.signature);
  253. UA_ByteString_deleteMembers(&dataToVerify);
  254. return retval;
  255. }
  256. /* Function to create a signature using remote certificate and nonce */
  257. #ifdef UA_ENABLE_ENCRYPTION
  258. UA_StatusCode
  259. signActivateSessionRequest(UA_SecureChannel *channel,
  260. UA_ActivateSessionRequest *request) {
  261. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  262. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  263. return UA_STATUSCODE_GOOD;
  264. const UA_SecurityPolicy *sp = channel->securityPolicy;
  265. UA_SignatureData *sd = &request->clientSignature;
  266. /* Prepare the signature */
  267. size_t signatureSize = sp->certificateSigningAlgorithm.
  268. getLocalSignatureSize(sp, channel->channelContext);
  269. UA_StatusCode retval = UA_String_copy(&sp->certificateSigningAlgorithm.uri,
  270. &sd->algorithm);
  271. if(retval != UA_STATUSCODE_GOOD)
  272. return retval;
  273. retval = UA_ByteString_allocBuffer(&sd->signature, signatureSize);
  274. if(retval != UA_STATUSCODE_GOOD)
  275. return retval;
  276. /* Allocate a temporary buffer */
  277. size_t dataToSignSize = channel->remoteCertificate.length + channel->remoteNonce.length;
  278. if(dataToSignSize > MAX_DATA_SIZE)
  279. return UA_STATUSCODE_BADINTERNALERROR;
  280. UA_ByteString dataToSign;
  281. retval = UA_ByteString_allocBuffer(&dataToSign, dataToSignSize);
  282. if(retval != UA_STATUSCODE_GOOD)
  283. return retval; /* sd->signature is cleaned up with the response */
  284. /* Sign the signature */
  285. memcpy(dataToSign.data, channel->remoteCertificate.data,
  286. channel->remoteCertificate.length);
  287. memcpy(dataToSign.data + channel->remoteCertificate.length,
  288. channel->remoteNonce.data, channel->remoteNonce.length);
  289. retval = sp->certificateSigningAlgorithm.sign(sp, channel->channelContext,
  290. &dataToSign, &sd->signature);
  291. /* Clean up */
  292. UA_ByteString_deleteMembers(&dataToSign);
  293. return retval;
  294. }
  295. UA_StatusCode
  296. encryptUserIdentityToken(UA_Client *client, const UA_String *userTokenSecurityPolicy,
  297. UA_ExtensionObject *userIdentityToken) {
  298. UA_IssuedIdentityToken *iit = NULL;
  299. UA_UserNameIdentityToken *unit = NULL;
  300. UA_ByteString *tokenData;
  301. if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
  302. iit = (UA_IssuedIdentityToken*)userIdentityToken->content.decoded.data;
  303. tokenData = &iit->tokenData;
  304. } else if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
  305. unit = (UA_UserNameIdentityToken*)userIdentityToken->content.decoded.data;
  306. tokenData = &unit->password;
  307. } else {
  308. return UA_STATUSCODE_GOOD;
  309. }
  310. /* No encryption */
  311. const UA_String none = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  312. if(userTokenSecurityPolicy->length == 0 ||
  313. UA_String_equal(userTokenSecurityPolicy, &none)) {
  314. return UA_STATUSCODE_GOOD;
  315. }
  316. UA_SecurityPolicy *sp = getSecurityPolicy(client, *userTokenSecurityPolicy);
  317. if(!sp) {
  318. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  319. "Could not find the required SecurityPolicy for the UserToken");
  320. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  321. }
  322. /* Create a temp channel context */
  323. void *channelContext;
  324. UA_StatusCode retval = sp->channelModule.
  325. newContext(sp, &client->config.endpoint.serverCertificate, &channelContext);
  326. if(retval != UA_STATUSCODE_GOOD) {
  327. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  328. "Could not instantiate the SecurityPolicy for the UserToken");
  329. return UA_STATUSCODE_BADINTERNALERROR;
  330. }
  331. /* Compute the encrypted length (at least one byte padding) */
  332. size_t plainTextBlockSize = sp->asymmetricModule.cryptoModule.
  333. encryptionAlgorithm.getRemotePlainTextBlockSize(sp, channelContext);
  334. UA_UInt32 length = (UA_UInt32)(tokenData->length + client->channel.remoteNonce.length);
  335. UA_UInt32 totalLength = length + 4; /* Including the length field */
  336. size_t blocks = totalLength / plainTextBlockSize;
  337. if(totalLength % plainTextBlockSize != 0)
  338. blocks++;
  339. size_t overHead =
  340. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(sp, channelContext,
  341. blocks * plainTextBlockSize);
  342. /* Allocate memory for encryption overhead */
  343. UA_ByteString encrypted;
  344. retval = UA_ByteString_allocBuffer(&encrypted, (blocks * plainTextBlockSize) + overHead);
  345. if(retval != UA_STATUSCODE_GOOD) {
  346. sp->channelModule.deleteContext(channelContext);
  347. return UA_STATUSCODE_BADOUTOFMEMORY;
  348. }
  349. UA_Byte *pos = encrypted.data;
  350. const UA_Byte *end = &encrypted.data[encrypted.length];
  351. UA_UInt32_encodeBinary(&length, &pos, end);
  352. memcpy(pos, tokenData->data, tokenData->length);
  353. memcpy(&pos[tokenData->length], client->channel.remoteNonce.data,
  354. client->channel.remoteNonce.length);
  355. /* Add padding
  356. *
  357. * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add any
  358. * padding after the secret. If a Client adds padding then all bytes shall
  359. * be zero. A Server shall check for padding added by Clients and ensure
  360. * that all padding bytes are zeros. */
  361. size_t paddedLength = plainTextBlockSize * blocks;
  362. for(size_t i = totalLength; i < paddedLength; i++)
  363. encrypted.data[i] = 0;
  364. encrypted.length = paddedLength;
  365. retval = sp->asymmetricModule.cryptoModule.encryptionAlgorithm.encrypt(sp, channelContext,
  366. &encrypted);
  367. encrypted.length = (blocks * plainTextBlockSize) + overHead;
  368. if(iit) {
  369. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  370. &iit->encryptionAlgorithm);
  371. } else {
  372. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  373. &unit->encryptionAlgorithm);
  374. }
  375. UA_ByteString_deleteMembers(tokenData);
  376. *tokenData = encrypted;
  377. /* Delete the temp channel context */
  378. sp->channelModule.deleteContext(channelContext);
  379. return retval;
  380. }
  381. #endif
  382. static UA_StatusCode
  383. activateSession(UA_Client *client) {
  384. UA_ActivateSessionRequest request;
  385. UA_ActivateSessionRequest_init(&request);
  386. request.requestHeader.requestHandle = ++client->requestHandle;
  387. request.requestHeader.timestamp = UA_DateTime_now();
  388. request.requestHeader.timeoutHint = 600000;
  389. UA_StatusCode retval =
  390. UA_ExtensionObject_copy(&client->config.userIdentityToken, &request.userIdentityToken);
  391. if(retval != UA_STATUSCODE_GOOD)
  392. return retval;
  393. /* If not token is set, use anonymous */
  394. if(request.userIdentityToken.encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  395. UA_AnonymousIdentityToken *t = UA_AnonymousIdentityToken_new();
  396. if(!t) {
  397. UA_ActivateSessionRequest_deleteMembers(&request);
  398. return UA_STATUSCODE_BADOUTOFMEMORY;
  399. }
  400. request.userIdentityToken.content.decoded.data = t;
  401. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  402. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  403. }
  404. /* Set the policy-Id from the endpoint. Every IdentityToken starts with a
  405. * string. */
  406. retval = UA_String_copy(&client->config.userTokenPolicy.policyId,
  407. (UA_String*)request.userIdentityToken.content.decoded.data);
  408. #ifdef UA_ENABLE_ENCRYPTION
  409. /* Encrypt the UserIdentityToken */
  410. const UA_String *userTokenPolicy = &client->channel.securityPolicy->policyUri;
  411. if(client->config.userTokenPolicy.securityPolicyUri.length > 0)
  412. userTokenPolicy = &client->config.userTokenPolicy.securityPolicyUri;
  413. retval |= encryptUserIdentityToken(client, userTokenPolicy, &request.userIdentityToken);
  414. /* This function call is to prepare a client signature */
  415. retval |= signActivateSessionRequest(&client->channel, &request);
  416. #endif
  417. if(retval != UA_STATUSCODE_GOOD) {
  418. UA_ActivateSessionRequest_deleteMembers(&request);
  419. return retval;
  420. }
  421. UA_ActivateSessionResponse response;
  422. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  423. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  424. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  425. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  426. "ActivateSession failed with error code %s",
  427. UA_StatusCode_name(response.responseHeader.serviceResult));
  428. }
  429. retval = response.responseHeader.serviceResult;
  430. UA_ActivateSessionRequest_deleteMembers(&request);
  431. UA_ActivateSessionResponse_deleteMembers(&response);
  432. return retval;
  433. }
  434. /* Gets a list of endpoints. Memory is allocated for endpointDescription array */
  435. UA_StatusCode
  436. UA_Client_getEndpointsInternal(UA_Client *client, const UA_String endpointUrl,
  437. size_t *endpointDescriptionsSize,
  438. UA_EndpointDescription **endpointDescriptions) {
  439. UA_GetEndpointsRequest request;
  440. UA_GetEndpointsRequest_init(&request);
  441. request.requestHeader.timestamp = UA_DateTime_now();
  442. request.requestHeader.timeoutHint = 10000;
  443. // assume the endpointurl outlives the service call
  444. request.endpointUrl = endpointUrl;
  445. UA_GetEndpointsResponse response;
  446. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  447. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  448. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  449. UA_StatusCode retval = response.responseHeader.serviceResult;
  450. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  451. "GetEndpointRequest failed with error code %s",
  452. UA_StatusCode_name(retval));
  453. UA_GetEndpointsResponse_deleteMembers(&response);
  454. return retval;
  455. }
  456. *endpointDescriptions = response.endpoints;
  457. *endpointDescriptionsSize = response.endpointsSize;
  458. response.endpoints = NULL;
  459. response.endpointsSize = 0;
  460. UA_GetEndpointsResponse_deleteMembers(&response);
  461. return UA_STATUSCODE_GOOD;
  462. }
  463. static UA_StatusCode
  464. selectEndpoint(UA_Client *client, const UA_String endpointUrl) {
  465. UA_EndpointDescription* endpointArray = NULL;
  466. size_t endpointArraySize = 0;
  467. UA_StatusCode retval =
  468. UA_Client_getEndpointsInternal(client, endpointUrl,
  469. &endpointArraySize, &endpointArray);
  470. if(retval != UA_STATUSCODE_GOOD)
  471. return retval;
  472. UA_Boolean endpointFound = false;
  473. UA_Boolean tokenFound = false;
  474. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  475. "Transport/uatcp-uasc-uabinary");
  476. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Found %lu endpoints", (long unsigned)endpointArraySize);
  477. for(size_t i = 0; i < endpointArraySize; ++i) {
  478. UA_EndpointDescription* endpoint = &endpointArray[i];
  479. /* Match Binary TransportProfile?
  480. * Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  481. if(endpoint->transportProfileUri.length != 0 &&
  482. !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  483. continue;
  484. /* Valid SecurityMode? */
  485. if(endpoint->securityMode < 1 || endpoint->securityMode > 3) {
  486. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: invalid security mode", (long unsigned)i);
  487. continue;
  488. }
  489. /* Selected SecurityMode? */
  490. if(client->config.securityMode > 0 &&
  491. client->config.securityMode != endpoint->securityMode) {
  492. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security mode doesn't match", (long unsigned)i);
  493. continue;
  494. }
  495. /* Matching SecurityPolicy? */
  496. if(client->config.securityPolicyUri.length > 0 &&
  497. !UA_String_equal(&client->config.securityPolicyUri,
  498. &endpoint->securityPolicyUri)) {
  499. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security policy doesn't match", (long unsigned)i);
  500. continue;
  501. }
  502. /* SecurityPolicy available? */
  503. if(!getSecurityPolicy(client, endpoint->securityPolicyUri)) {
  504. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security policy not available", (long unsigned)i);
  505. continue;
  506. }
  507. endpointFound = true;
  508. /* Select a matching UserTokenPolicy inside the endpoint */
  509. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Endpoint %lu has %lu user token policies", (long unsigned)i, (long unsigned)endpoint->userIdentityTokensSize);
  510. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  511. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  512. /* Usertokens also have a security policy... */
  513. if (userToken->securityPolicyUri.length > 0 &&
  514. !getSecurityPolicy(client, userToken->securityPolicyUri)) {
  515. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu in endpoint %lu: security policy '%.*s' not available",
  516. (long unsigned)j, (long unsigned)i,
  517. (int)userToken->securityPolicyUri.length, userToken->securityPolicyUri.data);
  518. continue;
  519. }
  520. if(userToken->tokenType > 3) {
  521. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu in endpoint %lu: invalid token type", (long unsigned)j, (long unsigned)i);
  522. continue;
  523. }
  524. /* Does the token type match the client configuration? */
  525. if (userToken->tokenType == UA_USERTOKENTYPE_ANONYMOUS &&
  526. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN] &&
  527. client->config.userIdentityToken.content.decoded.type != NULL) {
  528. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu (anonymous) in endpoint %lu: configuration doesn't match", (long unsigned)j, (long unsigned)i);
  529. continue;
  530. }
  531. if (userToken->tokenType == UA_USERTOKENTYPE_USERNAME &&
  532. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
  533. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu (username) in endpoint %lu: configuration doesn't match", (long unsigned)j, (long unsigned)i);
  534. continue;
  535. }
  536. if (userToken->tokenType == UA_USERTOKENTYPE_CERTIFICATE &&
  537. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]) {
  538. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu (certificate) in endpoint %lu: configuration doesn't match", (long unsigned)j, (long unsigned)i);
  539. continue;
  540. }
  541. if (userToken->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN &&
  542. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
  543. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu (token) in endpoint %lu: configuration doesn't match", (long unsigned)j, (long unsigned)i);
  544. continue;
  545. }
  546. /* Endpoint with matching UserTokenPolicy found. Copy to the configuration. */
  547. tokenFound = true;
  548. UA_EndpointDescription_deleteMembers(&client->config.endpoint);
  549. UA_EndpointDescription temp = *endpoint;
  550. temp.userIdentityTokensSize = 0;
  551. temp.userIdentityTokens = NULL;
  552. UA_UserTokenPolicy_deleteMembers(&client->config.userTokenPolicy);
  553. retval = UA_EndpointDescription_copy(&temp, &client->config.endpoint);
  554. if(retval != UA_STATUSCODE_GOOD) {
  555. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  556. "Copying endpoint description failed with error code %s",
  557. UA_StatusCode_name(retval));
  558. break;
  559. }
  560. retval = UA_UserTokenPolicy_copy(userToken, &client->config.userTokenPolicy);
  561. if(retval != UA_STATUSCODE_GOOD) {
  562. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  563. "Copying user token policy failed with error code %s",
  564. UA_StatusCode_name(retval));
  565. break;
  566. }
  567. #if UA_LOGLEVEL <= 300
  568. const char *securityModeNames[3] = {"None", "Sign", "SignAndEncrypt"};
  569. const char *userTokenTypeNames[4] = {"Anonymous", "UserName",
  570. "Certificate", "IssuedToken"};
  571. UA_String *securityPolicyUri = &userToken->securityPolicyUri;
  572. if(securityPolicyUri->length == 0)
  573. securityPolicyUri = &endpoint->securityPolicyUri;
  574. /* Log the selected endpoint */
  575. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  576. "Selected Endpoint %.*s with SecurityMode %s and SecurityPolicy %.*s",
  577. (int)endpoint->endpointUrl.length, endpoint->endpointUrl.data,
  578. securityModeNames[endpoint->securityMode - 1],
  579. (int)endpoint->securityPolicyUri.length,
  580. endpoint->securityPolicyUri.data);
  581. /* Log the selected UserTokenPolicy */
  582. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  583. "Selected UserTokenPolicy %.*s with UserTokenType %s and SecurityPolicy %.*s",
  584. (int)userToken->policyId.length, userToken->policyId.data,
  585. userTokenTypeNames[userToken->tokenType],
  586. (int)securityPolicyUri->length, securityPolicyUri->data);
  587. #endif
  588. break;
  589. }
  590. if(tokenFound)
  591. break;
  592. }
  593. UA_Array_delete(endpointArray, endpointArraySize,
  594. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  595. if(retval != UA_STATUSCODE_GOOD)
  596. return retval;
  597. if(!endpointFound) {
  598. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  599. "No suitable endpoint found");
  600. retval = UA_STATUSCODE_BADINTERNALERROR;
  601. } else if(!tokenFound) {
  602. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  603. "No suitable UserTokenPolicy found for the possible endpoints");
  604. retval = UA_STATUSCODE_BADINTERNALERROR;
  605. }
  606. return retval;
  607. }
  608. static UA_StatusCode
  609. createSession(UA_Client *client) {
  610. UA_CreateSessionRequest request;
  611. UA_CreateSessionRequest_init(&request);
  612. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  613. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  614. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  615. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  616. UA_ByteString_deleteMembers(&client->channel.localNonce);
  617. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  618. UA_SESSION_LOCALNONCELENGTH);
  619. if(retval != UA_STATUSCODE_GOOD)
  620. return retval;
  621. }
  622. retval = client->channel.securityPolicy->symmetricModule.
  623. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  624. if(retval != UA_STATUSCODE_GOOD)
  625. return retval;
  626. }
  627. request.requestHeader.timestamp = UA_DateTime_now();
  628. request.requestHeader.timeoutHint = 10000;
  629. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  630. request.requestedSessionTimeout = client->config.requestedSessionTimeout;
  631. request.maxResponseMessageSize = UA_INT32_MAX;
  632. UA_String_copy(&client->config.endpoint.endpointUrl, &request.endpointUrl);
  633. UA_ApplicationDescription_copy(&client->config.clientDescription,
  634. &request.clientDescription);
  635. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  636. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  637. UA_ByteString_copy(&client->channel.securityPolicy->localCertificate,
  638. &request.clientCertificate);
  639. }
  640. UA_CreateSessionResponse response;
  641. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  642. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  643. if(response.responseHeader.serviceResult == UA_STATUSCODE_GOOD) {
  644. /* Verify the encrypted response */
  645. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  646. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  647. if(!UA_ByteString_equal(&response.serverCertificate,
  648. &client->channel.remoteCertificate)) {
  649. retval = UA_STATUSCODE_BADCERTIFICATEINVALID;
  650. goto cleanup;
  651. }
  652. /* Verify the client signature */
  653. retval = checkClientSignature(&client->channel, &response);
  654. if(retval != UA_STATUSCODE_GOOD)
  655. goto cleanup;
  656. }
  657. /* Copy nonce and and authenticationtoken */
  658. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  659. retval |= UA_ByteString_copy(&response.serverNonce, &client->channel.remoteNonce);
  660. UA_NodeId_deleteMembers(&client->authenticationToken);
  661. retval |= UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  662. }
  663. retval |= response.responseHeader.serviceResult;
  664. cleanup:
  665. UA_CreateSessionRequest_deleteMembers(&request);
  666. UA_CreateSessionResponse_deleteMembers(&response);
  667. return retval;
  668. }
  669. UA_StatusCode
  670. UA_Client_connectTCPSecureChannel(UA_Client *client, const UA_String endpointUrl) {
  671. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  672. return UA_STATUSCODE_GOOD;
  673. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  674. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  675. client->channel.sendSequenceNumber = 0;
  676. client->requestId = 0;
  677. /* Set the channel SecurityMode */
  678. client->channel.securityMode = client->config.endpoint.securityMode;
  679. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  680. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  681. /* Initialized the SecureChannel */
  682. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  683. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  684. "Initialize the SecurityPolicy context");
  685. if(!client->channel.securityPolicy) {
  686. /* Set the channel SecurityPolicy to #None if no endpoint is selected */
  687. UA_String sps = client->config.endpoint.securityPolicyUri;
  688. if(sps.length == 0) {
  689. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  690. "SecurityPolicy not specified -> use default #None");
  691. sps = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  692. }
  693. UA_SecurityPolicy *sp = getSecurityPolicy(client, sps);
  694. if(!sp) {
  695. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  696. "Failed to find the required security policy");
  697. retval = UA_STATUSCODE_BADINTERNALERROR;
  698. goto cleanup;
  699. }
  700. retval = UA_SecureChannel_setSecurityPolicy(&client->channel, sp,
  701. &client->config.endpoint.serverCertificate);
  702. if(retval != UA_STATUSCODE_GOOD) {
  703. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  704. "Failed to set the security policy");
  705. goto cleanup;
  706. }
  707. }
  708. /* Open a TCP connection */
  709. client->connection = client->config.connectionFunc(client->config.localConnectionConfig,
  710. endpointUrl, client->config.timeout,
  711. &client->config.logger);
  712. if(client->connection.state != UA_CONNECTION_OPENING) {
  713. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  714. "Opening the TCP socket failed");
  715. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  716. goto cleanup;
  717. }
  718. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  719. "TCP connection established");
  720. /* Perform the HEL/ACK handshake */
  721. client->connection.config = client->config.localConnectionConfig;
  722. retval = HelAckHandshake(client, endpointUrl);
  723. if(retval != UA_STATUSCODE_GOOD) {
  724. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  725. "HEL/ACK handshake failed");
  726. goto cleanup;
  727. }
  728. setClientState(client, UA_CLIENTSTATE_CONNECTED);
  729. /* Open a SecureChannel. */
  730. retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  731. if(retval != UA_STATUSCODE_GOOD) {
  732. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  733. "Generating a local nonce failed");
  734. goto cleanup;
  735. }
  736. client->channel.connection = &client->connection;
  737. retval = openSecureChannel(client, false);
  738. if(retval != UA_STATUSCODE_GOOD) {
  739. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  740. "Opening a secure channel failed");
  741. goto cleanup;
  742. }
  743. retval = UA_SecureChannel_generateNewKeys(&client->channel);
  744. if(retval != UA_STATUSCODE_GOOD) {
  745. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  746. "Generating new keys failed");
  747. return retval;
  748. }
  749. setClientState(client, UA_CLIENTSTATE_SECURECHANNEL);
  750. return retval;
  751. cleanup:
  752. UA_Client_disconnect(client);
  753. return retval;
  754. }
  755. UA_StatusCode
  756. UA_Client_connectSession(UA_Client *client) {
  757. if(client->state < UA_CLIENTSTATE_SECURECHANNEL)
  758. return UA_STATUSCODE_BADINTERNALERROR;
  759. /* Delete async service. TODO: Move this from connect to the disconnect/cleanup phase */
  760. UA_Client_AsyncService_removeAll(client, UA_STATUSCODE_BADSHUTDOWN);
  761. // TODO: actually, reactivate an existing session is working, but currently
  762. // republish is not implemented This option is disabled until we have a good
  763. // implementation of the subscription recovery.
  764. #ifdef UA_SESSION_RECOVERY
  765. /* Try to activate an existing Session for this SecureChannel */
  766. if((!UA_NodeId_equal(&client->authenticationToken, &UA_NODEID_NULL)) && (createNewSession)) {
  767. UA_StatusCode res = activateSession(client);
  768. if(res != UA_STATUSCODE_BADSESSIONIDINVALID) {
  769. if(res == UA_STATUSCODE_GOOD) {
  770. setClientState(client, UA_CLIENTSTATE_SESSION_RENEWED);
  771. } else {
  772. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  773. "Could not activate the Session with StatusCode %s",
  774. UA_StatusCode_name(retval));
  775. UA_Client_disconnect(client);
  776. }
  777. return res;
  778. }
  779. }
  780. #endif /* UA_SESSION_RECOVERY */
  781. /* Could not recover an old session. Remove authenticationToken */
  782. UA_NodeId_deleteMembers(&client->authenticationToken);
  783. /* Create a session */
  784. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Create a new session");
  785. UA_StatusCode retval = createSession(client);
  786. if(retval != UA_STATUSCODE_GOOD) {
  787. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  788. "Could not open a Session with StatusCode %s",
  789. UA_StatusCode_name(retval));
  790. UA_Client_disconnect(client);
  791. return retval;
  792. }
  793. /* A new session has been created. We need to clean up the subscriptions */
  794. #ifdef UA_ENABLE_SUBSCRIPTIONS
  795. UA_Client_Subscriptions_clean(client);
  796. client->currentlyOutStandingPublishRequests = 0;
  797. #endif
  798. /* Activate the session */
  799. retval = activateSession(client);
  800. if(retval != UA_STATUSCODE_GOOD) {
  801. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  802. "Could not activate the Session with StatusCode %s",
  803. UA_StatusCode_name(retval));
  804. UA_Client_disconnect(client);
  805. return retval;
  806. }
  807. setClientState(client, UA_CLIENTSTATE_SESSION);
  808. return retval;
  809. }
  810. #ifdef UA_ENABLE_ENCRYPTION
  811. /* The local ApplicationURI has to match the certificates of the
  812. * SecurityPolicies */
  813. static void
  814. verifyClientApplicationURI(const UA_Client *client) {
  815. #if UA_LOGLEVEL <= 400
  816. for(size_t i = 0; i < client->config.securityPoliciesSize; i++) {
  817. UA_SecurityPolicy *sp = &client->config.securityPolicies[i];
  818. if(!sp->certificateVerification)
  819. continue;
  820. UA_StatusCode retval =
  821. sp->certificateVerification->
  822. verifyApplicationURI(sp->certificateVerification->context,
  823. &sp->localCertificate,
  824. &client->config.clientDescription.applicationUri);
  825. if(retval != UA_STATUSCODE_GOOD) {
  826. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  827. "The configured ApplicationURI does not match the URI "
  828. "specified in the certificate for the SecurityPolicy %.*s",
  829. (int)sp->policyUri.length, sp->policyUri.data);
  830. }
  831. }
  832. #endif
  833. }
  834. #endif
  835. UA_StatusCode
  836. UA_Client_connectInternal(UA_Client *client, const UA_String endpointUrl) {
  837. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  838. return UA_STATUSCODE_GOOD;
  839. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  840. "Connecting to endpoint %.*s", (int)endpointUrl.length,
  841. endpointUrl.data);
  842. #ifdef UA_ENABLE_ENCRYPTION
  843. verifyClientApplicationURI(client);
  844. #endif
  845. /* Get endpoints only if the description has not been touched (memset to zero) */
  846. UA_Byte test = 0;
  847. UA_Byte *pos = (UA_Byte*)&client->config.endpoint;
  848. for(size_t i = 0; i < sizeof(UA_EndpointDescription); i++)
  849. test = test | pos[i];
  850. pos = (UA_Byte*)&client->config.userTokenPolicy;
  851. for(size_t i = 0; i < sizeof(UA_UserTokenPolicy); i++)
  852. test = test | pos[i];
  853. UA_Boolean getEndpoints = (test == 0);
  854. /* Connect up to the SecureChannel */
  855. UA_StatusCode retval = UA_Client_connectTCPSecureChannel(client, endpointUrl);
  856. if (retval != UA_STATUSCODE_GOOD) {
  857. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  858. "Couldn't connect the client to a TCP secure channel");
  859. goto cleanup;
  860. }
  861. /* Get and select endpoints if required */
  862. if(getEndpoints) {
  863. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  864. "Endpoint and UserTokenPolicy unconfigured, perform GetEndpoints");
  865. retval = selectEndpoint(client, endpointUrl);
  866. if(retval != UA_STATUSCODE_GOOD)
  867. goto cleanup;
  868. /* Reconnect with a new SecureChannel if the current one does not match
  869. * the selected endpoint */
  870. if(!UA_String_equal(&client->config.endpoint.securityPolicyUri,
  871. &client->channel.securityPolicy->policyUri)) {
  872. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  873. "Disconnect to switch to a different SecurityPolicy");
  874. UA_Client_disconnect(client);
  875. return UA_Client_connectInternal(client, endpointUrl);
  876. }
  877. }
  878. retval = UA_Client_connectSession(client);
  879. if(retval != UA_STATUSCODE_GOOD)
  880. goto cleanup;
  881. return retval;
  882. cleanup:
  883. UA_Client_disconnect(client);
  884. return retval;
  885. }
  886. UA_StatusCode
  887. UA_Client_connect(UA_Client *client, const char *endpointUrl) {
  888. return UA_Client_connectInternal(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  889. }
  890. UA_StatusCode
  891. UA_Client_connect_noSession(UA_Client *client, const char *endpointUrl) {
  892. return UA_Client_connectTCPSecureChannel(client, UA_STRING((char*)(uintptr_t)endpointUrl));
  893. }
  894. UA_StatusCode
  895. UA_Client_connect_username(UA_Client *client, const char *endpointUrl,
  896. const char *username, const char *password) {
  897. UA_UserNameIdentityToken* identityToken = UA_UserNameIdentityToken_new();
  898. if(!identityToken)
  899. return UA_STATUSCODE_BADOUTOFMEMORY;
  900. identityToken->userName = UA_STRING_ALLOC(username);
  901. identityToken->password = UA_STRING_ALLOC(password);
  902. UA_ExtensionObject_deleteMembers(&client->config.userIdentityToken);
  903. client->config.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  904. client->config.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN];
  905. client->config.userIdentityToken.content.decoded.data = identityToken;
  906. return UA_Client_connect(client, endpointUrl);
  907. }
  908. /************************/
  909. /* Close the Connection */
  910. /************************/
  911. static void
  912. sendCloseSession(UA_Client *client) {
  913. UA_CloseSessionRequest request;
  914. UA_CloseSessionRequest_init(&request);
  915. request.requestHeader.timestamp = UA_DateTime_now();
  916. request.requestHeader.timeoutHint = 10000;
  917. request.deleteSubscriptions = true;
  918. UA_CloseSessionResponse response;
  919. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST],
  920. &response, &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE]);
  921. UA_CloseSessionRequest_deleteMembers(&request);
  922. UA_CloseSessionResponse_deleteMembers(&response);
  923. }
  924. static void
  925. sendCloseSecureChannel(UA_Client *client) {
  926. UA_SecureChannel *channel = &client->channel;
  927. UA_CloseSecureChannelRequest request;
  928. UA_CloseSecureChannelRequest_init(&request);
  929. request.requestHeader.requestHandle = ++client->requestHandle;
  930. request.requestHeader.timestamp = UA_DateTime_now();
  931. request.requestHeader.timeoutHint = 10000;
  932. request.requestHeader.authenticationToken = client->authenticationToken;
  933. UA_SecureChannel_sendSymmetricMessage(channel, ++client->requestId,
  934. UA_MESSAGETYPE_CLO, &request,
  935. &UA_TYPES[UA_TYPES_CLOSESECURECHANNELREQUEST]);
  936. UA_CloseSecureChannelRequest_deleteMembers(&request);
  937. UA_SecureChannel_close(&client->channel);
  938. UA_SecureChannel_deleteMembers(&client->channel);
  939. }
  940. UA_StatusCode
  941. UA_Client_disconnect(UA_Client *client) {
  942. /* Is a session established? */
  943. if(client->state >= UA_CLIENTSTATE_SESSION) {
  944. client->state = UA_CLIENTSTATE_SECURECHANNEL;
  945. sendCloseSession(client);
  946. }
  947. UA_NodeId_deleteMembers(&client->authenticationToken);
  948. client->requestHandle = 0;
  949. /* Is a secure channel established? */
  950. if(client->state >= UA_CLIENTSTATE_SECURECHANNEL) {
  951. client->state = UA_CLIENTSTATE_CONNECTED;
  952. sendCloseSecureChannel(client);
  953. }
  954. /* Close the TCP connection */
  955. if(client->connection.state != UA_CONNECTION_CLOSED
  956. && client->connection.state != UA_CONNECTION_OPENING)
  957. /* UA_ClientConnectionTCP_init sets initial state to opening */
  958. if(client->connection.close != NULL)
  959. client->connection.close(&client->connection);
  960. #ifdef UA_ENABLE_SUBSCRIPTIONS
  961. // TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
  962. /* We need to clean up the subscriptions */
  963. UA_Client_Subscriptions_clean(client);
  964. #endif
  965. UA_SecureChannel_deleteMembers(&client->channel);
  966. setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
  967. return UA_STATUSCODE_GOOD;
  968. }