ua_client_connect.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. /* Generate clientNonce. */
  179. UA_StatusCode retval = UA_SecureChannel_generateLocalNonce(&client->channel);
  180. if(retval != UA_STATUSCODE_GOOD) {
  181. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  182. "Generating a local nonce failed");
  183. return retval;
  184. }
  185. /* Prepare the OpenSecureChannelRequest */
  186. UA_OpenSecureChannelRequest opnSecRq;
  187. UA_OpenSecureChannelRequest_init(&opnSecRq);
  188. opnSecRq.requestHeader.timestamp = UA_DateTime_now();
  189. opnSecRq.requestHeader.authenticationToken = client->authenticationToken;
  190. if(renew) {
  191. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_RENEW;
  192. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  193. "Requesting to renew the SecureChannel");
  194. } else {
  195. opnSecRq.requestType = UA_SECURITYTOKENREQUESTTYPE_ISSUE;
  196. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  197. "Requesting to open a SecureChannel");
  198. }
  199. /* Set the securityMode to input securityMode from client data */
  200. opnSecRq.securityMode = client->channel.securityMode;
  201. opnSecRq.clientNonce = client->channel.localNonce;
  202. opnSecRq.requestedLifetime = client->config.secureChannelLifeTime;
  203. /* Send the OPN message */
  204. UA_UInt32 requestId = ++client->requestId;
  205. retval = UA_SecureChannel_sendAsymmetricOPNMessage(&client->channel, requestId, &opnSecRq,
  206. &UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST]);
  207. if(retval != UA_STATUSCODE_GOOD) {
  208. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  209. "Sending OPN message failed with error %s", UA_StatusCode_name(retval));
  210. UA_Client_disconnect(client);
  211. return retval;
  212. }
  213. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "OPN message sent");
  214. /* Increase nextChannelRenewal to avoid that we re-start renewal when
  215. * publish responses are received before the OPN response arrives. */
  216. client->nextChannelRenewal = UA_DateTime_nowMonotonic() +
  217. (2 * ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC));
  218. /* Receive / decrypt / decode the OPN response. Process async services in
  219. * the background until the OPN response arrives. */
  220. UA_OpenSecureChannelResponse response;
  221. retval = receiveServiceResponse(client, &response,
  222. &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE],
  223. UA_DateTime_nowMonotonic() +
  224. ((UA_DateTime)client->config.timeout * UA_DATETIME_MSEC),
  225. &requestId);
  226. if(retval != UA_STATUSCODE_GOOD) {
  227. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL,
  228. "Receiving service response failed with error %s", UA_StatusCode_name(retval));
  229. UA_Client_disconnect(client);
  230. return retval;
  231. }
  232. processDecodedOPNResponse(client, &response, renew);
  233. UA_OpenSecureChannelResponse_deleteMembers(&response);
  234. return retval;
  235. }
  236. /* Function to verify the signature corresponds to ClientNonce
  237. * using the local certificate */
  238. static UA_StatusCode
  239. checkClientSignature(const UA_SecureChannel *channel,
  240. const UA_CreateSessionResponse *response) {
  241. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  242. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  243. return UA_STATUSCODE_GOOD;
  244. if(!channel->securityPolicy)
  245. return UA_STATUSCODE_BADINTERNALERROR;
  246. const UA_SecurityPolicy *sp = channel->securityPolicy;
  247. const UA_ByteString *lc = &sp->localCertificate;
  248. size_t dataToVerifySize = lc->length + channel->localNonce.length;
  249. UA_ByteString dataToVerify = UA_BYTESTRING_NULL;
  250. UA_StatusCode retval = UA_ByteString_allocBuffer(&dataToVerify, dataToVerifySize);
  251. if(retval != UA_STATUSCODE_GOOD)
  252. return retval;
  253. memcpy(dataToVerify.data, lc->data, lc->length);
  254. memcpy(dataToVerify.data + lc->length,
  255. channel->localNonce.data, channel->localNonce.length);
  256. retval = sp->certificateSigningAlgorithm.
  257. verify(sp, channel->channelContext, &dataToVerify,
  258. &response->serverSignature.signature);
  259. UA_ByteString_deleteMembers(&dataToVerify);
  260. return retval;
  261. }
  262. /* Function to create a signature using remote certificate and nonce */
  263. #ifdef UA_ENABLE_ENCRYPTION
  264. UA_StatusCode
  265. signActivateSessionRequest(UA_SecureChannel *channel,
  266. UA_ActivateSessionRequest *request) {
  267. if(channel->securityMode != UA_MESSAGESECURITYMODE_SIGN &&
  268. channel->securityMode != UA_MESSAGESECURITYMODE_SIGNANDENCRYPT)
  269. return UA_STATUSCODE_GOOD;
  270. const UA_SecurityPolicy *sp = channel->securityPolicy;
  271. UA_SignatureData *sd = &request->clientSignature;
  272. /* Prepare the signature */
  273. size_t signatureSize = sp->certificateSigningAlgorithm.
  274. getLocalSignatureSize(sp, channel->channelContext);
  275. UA_StatusCode retval = UA_String_copy(&sp->certificateSigningAlgorithm.uri,
  276. &sd->algorithm);
  277. if(retval != UA_STATUSCODE_GOOD)
  278. return retval;
  279. retval = UA_ByteString_allocBuffer(&sd->signature, signatureSize);
  280. if(retval != UA_STATUSCODE_GOOD)
  281. return retval;
  282. /* Allocate a temporary buffer */
  283. size_t dataToSignSize = channel->remoteCertificate.length + channel->remoteNonce.length;
  284. if(dataToSignSize > MAX_DATA_SIZE)
  285. return UA_STATUSCODE_BADINTERNALERROR;
  286. UA_ByteString dataToSign;
  287. retval = UA_ByteString_allocBuffer(&dataToSign, dataToSignSize);
  288. if(retval != UA_STATUSCODE_GOOD)
  289. return retval; /* sd->signature is cleaned up with the response */
  290. /* Sign the signature */
  291. memcpy(dataToSign.data, channel->remoteCertificate.data,
  292. channel->remoteCertificate.length);
  293. memcpy(dataToSign.data + channel->remoteCertificate.length,
  294. channel->remoteNonce.data, channel->remoteNonce.length);
  295. retval = sp->certificateSigningAlgorithm.sign(sp, channel->channelContext,
  296. &dataToSign, &sd->signature);
  297. /* Clean up */
  298. UA_ByteString_deleteMembers(&dataToSign);
  299. return retval;
  300. }
  301. UA_StatusCode
  302. encryptUserIdentityToken(UA_Client *client, const UA_String *userTokenSecurityPolicy,
  303. UA_ExtensionObject *userIdentityToken) {
  304. UA_IssuedIdentityToken *iit = NULL;
  305. UA_UserNameIdentityToken *unit = NULL;
  306. UA_ByteString *tokenData;
  307. if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
  308. iit = (UA_IssuedIdentityToken*)userIdentityToken->content.decoded.data;
  309. tokenData = &iit->tokenData;
  310. } else if(userIdentityToken->content.decoded.type == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
  311. unit = (UA_UserNameIdentityToken*)userIdentityToken->content.decoded.data;
  312. tokenData = &unit->password;
  313. } else {
  314. return UA_STATUSCODE_GOOD;
  315. }
  316. /* No encryption */
  317. const UA_String none = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  318. if(userTokenSecurityPolicy->length == 0 ||
  319. UA_String_equal(userTokenSecurityPolicy, &none)) {
  320. return UA_STATUSCODE_GOOD;
  321. }
  322. UA_SecurityPolicy *sp = getSecurityPolicy(client, *userTokenSecurityPolicy);
  323. if(!sp) {
  324. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  325. "Could not find the required SecurityPolicy for the UserToken");
  326. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  327. }
  328. /* Create a temp channel context */
  329. void *channelContext;
  330. UA_StatusCode retval = sp->channelModule.
  331. newContext(sp, &client->config.endpoint.serverCertificate, &channelContext);
  332. if(retval != UA_STATUSCODE_GOOD) {
  333. UA_LOG_WARNING(&client->config.logger, UA_LOGCATEGORY_NETWORK,
  334. "Could not instantiate the SecurityPolicy for the UserToken");
  335. return UA_STATUSCODE_BADINTERNALERROR;
  336. }
  337. /* Compute the encrypted length (at least one byte padding) */
  338. size_t plainTextBlockSize = sp->asymmetricModule.cryptoModule.
  339. encryptionAlgorithm.getRemotePlainTextBlockSize(sp, channelContext);
  340. UA_UInt32 length = (UA_UInt32)(tokenData->length + client->channel.remoteNonce.length);
  341. UA_UInt32 totalLength = length + 4; /* Including the length field */
  342. size_t blocks = totalLength / plainTextBlockSize;
  343. if(totalLength % plainTextBlockSize != 0)
  344. blocks++;
  345. size_t overHead =
  346. UA_SecurityPolicy_getRemoteAsymEncryptionBufferLengthOverhead(sp, channelContext,
  347. blocks * plainTextBlockSize);
  348. /* Allocate memory for encryption overhead */
  349. UA_ByteString encrypted;
  350. retval = UA_ByteString_allocBuffer(&encrypted, (blocks * plainTextBlockSize) + overHead);
  351. if(retval != UA_STATUSCODE_GOOD) {
  352. sp->channelModule.deleteContext(channelContext);
  353. return UA_STATUSCODE_BADOUTOFMEMORY;
  354. }
  355. UA_Byte *pos = encrypted.data;
  356. const UA_Byte *end = &encrypted.data[encrypted.length];
  357. UA_UInt32_encodeBinary(&length, &pos, end);
  358. memcpy(pos, tokenData->data, tokenData->length);
  359. memcpy(&pos[tokenData->length], client->channel.remoteNonce.data,
  360. client->channel.remoteNonce.length);
  361. /* Add padding
  362. *
  363. * 7.36.2.2 Legacy Encrypted Token Secret Format: A Client should not add any
  364. * padding after the secret. If a Client adds padding then all bytes shall
  365. * be zero. A Server shall check for padding added by Clients and ensure
  366. * that all padding bytes are zeros. */
  367. size_t paddedLength = plainTextBlockSize * blocks;
  368. for(size_t i = totalLength; i < paddedLength; i++)
  369. encrypted.data[i] = 0;
  370. encrypted.length = paddedLength;
  371. retval = sp->asymmetricModule.cryptoModule.encryptionAlgorithm.encrypt(sp, channelContext,
  372. &encrypted);
  373. encrypted.length = (blocks * plainTextBlockSize) + overHead;
  374. if(iit) {
  375. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  376. &iit->encryptionAlgorithm);
  377. } else {
  378. retval |= UA_String_copy(&sp->asymmetricModule.cryptoModule.encryptionAlgorithm.uri,
  379. &unit->encryptionAlgorithm);
  380. }
  381. UA_ByteString_deleteMembers(tokenData);
  382. *tokenData = encrypted;
  383. /* Delete the temp channel context */
  384. sp->channelModule.deleteContext(channelContext);
  385. return retval;
  386. }
  387. #endif
  388. static UA_StatusCode
  389. activateSession(UA_Client *client) {
  390. UA_ActivateSessionRequest request;
  391. UA_ActivateSessionRequest_init(&request);
  392. request.requestHeader.requestHandle = ++client->requestHandle;
  393. request.requestHeader.timestamp = UA_DateTime_now();
  394. request.requestHeader.timeoutHint = 600000;
  395. UA_StatusCode retval =
  396. UA_ExtensionObject_copy(&client->config.userIdentityToken, &request.userIdentityToken);
  397. if(retval != UA_STATUSCODE_GOOD)
  398. return retval;
  399. /* If not token is set, use anonymous */
  400. if(request.userIdentityToken.encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  401. UA_AnonymousIdentityToken *t = UA_AnonymousIdentityToken_new();
  402. if(!t) {
  403. UA_ActivateSessionRequest_deleteMembers(&request);
  404. return UA_STATUSCODE_BADOUTOFMEMORY;
  405. }
  406. request.userIdentityToken.content.decoded.data = t;
  407. request.userIdentityToken.content.decoded.type = &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN];
  408. request.userIdentityToken.encoding = UA_EXTENSIONOBJECT_DECODED;
  409. }
  410. /* Set the policy-Id from the endpoint. Every IdentityToken starts with a
  411. * string. */
  412. retval = UA_String_copy(&client->config.userTokenPolicy.policyId,
  413. (UA_String*)request.userIdentityToken.content.decoded.data);
  414. #ifdef UA_ENABLE_ENCRYPTION
  415. /* Encrypt the UserIdentityToken */
  416. const UA_String *userTokenPolicy = &client->channel.securityPolicy->policyUri;
  417. if(client->config.userTokenPolicy.securityPolicyUri.length > 0)
  418. userTokenPolicy = &client->config.userTokenPolicy.securityPolicyUri;
  419. retval |= encryptUserIdentityToken(client, userTokenPolicy, &request.userIdentityToken);
  420. /* This function call is to prepare a client signature */
  421. retval |= signActivateSessionRequest(&client->channel, &request);
  422. #endif
  423. if(retval != UA_STATUSCODE_GOOD) {
  424. UA_ActivateSessionRequest_deleteMembers(&request);
  425. return retval;
  426. }
  427. UA_ActivateSessionResponse response;
  428. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST],
  429. &response, &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE]);
  430. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  431. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  432. "ActivateSession failed with error code %s",
  433. UA_StatusCode_name(response.responseHeader.serviceResult));
  434. }
  435. retval = response.responseHeader.serviceResult;
  436. UA_ActivateSessionRequest_deleteMembers(&request);
  437. UA_ActivateSessionResponse_deleteMembers(&response);
  438. return retval;
  439. }
  440. /* Gets a list of endpoints. Memory is allocated for endpointDescription array */
  441. UA_StatusCode
  442. UA_Client_getEndpointsInternal(UA_Client *client, const UA_String endpointUrl,
  443. size_t *endpointDescriptionsSize,
  444. UA_EndpointDescription **endpointDescriptions) {
  445. UA_GetEndpointsRequest request;
  446. UA_GetEndpointsRequest_init(&request);
  447. request.requestHeader.timestamp = UA_DateTime_now();
  448. request.requestHeader.timeoutHint = 10000;
  449. // assume the endpointurl outlives the service call
  450. request.endpointUrl = endpointUrl;
  451. UA_GetEndpointsResponse response;
  452. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST],
  453. &response, &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE]);
  454. if(response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  455. UA_StatusCode retval = response.responseHeader.serviceResult;
  456. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  457. "GetEndpointRequest failed with error code %s",
  458. UA_StatusCode_name(retval));
  459. UA_GetEndpointsResponse_deleteMembers(&response);
  460. return retval;
  461. }
  462. *endpointDescriptions = response.endpoints;
  463. *endpointDescriptionsSize = response.endpointsSize;
  464. response.endpoints = NULL;
  465. response.endpointsSize = 0;
  466. UA_GetEndpointsResponse_deleteMembers(&response);
  467. return UA_STATUSCODE_GOOD;
  468. }
  469. static UA_StatusCode
  470. selectEndpoint(UA_Client *client, const UA_String endpointUrl) {
  471. UA_EndpointDescription* endpointArray = NULL;
  472. size_t endpointArraySize = 0;
  473. UA_StatusCode retval =
  474. UA_Client_getEndpointsInternal(client, endpointUrl,
  475. &endpointArraySize, &endpointArray);
  476. if(retval != UA_STATUSCODE_GOOD)
  477. return retval;
  478. UA_Boolean endpointFound = false;
  479. UA_Boolean tokenFound = false;
  480. UA_String binaryTransport = UA_STRING("http://opcfoundation.org/UA-Profile/"
  481. "Transport/uatcp-uasc-uabinary");
  482. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Found %lu endpoints", (long unsigned)endpointArraySize);
  483. for(size_t i = 0; i < endpointArraySize; ++i) {
  484. UA_EndpointDescription* endpoint = &endpointArray[i];
  485. /* Match Binary TransportProfile?
  486. * Note: Siemens returns empty ProfileUrl, we will accept it as binary */
  487. if(endpoint->transportProfileUri.length != 0 &&
  488. !UA_String_equal(&endpoint->transportProfileUri, &binaryTransport))
  489. continue;
  490. /* Valid SecurityMode? */
  491. if(endpoint->securityMode < 1 || endpoint->securityMode > 3) {
  492. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: invalid security mode", (long unsigned)i);
  493. continue;
  494. }
  495. /* Selected SecurityMode? */
  496. if(client->config.securityMode > 0 &&
  497. client->config.securityMode != endpoint->securityMode) {
  498. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security mode doesn't match", (long unsigned)i);
  499. continue;
  500. }
  501. /* Matching SecurityPolicy? */
  502. if(client->config.securityPolicyUri.length > 0 &&
  503. !UA_String_equal(&client->config.securityPolicyUri,
  504. &endpoint->securityPolicyUri)) {
  505. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security policy doesn't match", (long unsigned)i);
  506. continue;
  507. }
  508. /* SecurityPolicy available? */
  509. if(!getSecurityPolicy(client, endpoint->securityPolicyUri)) {
  510. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting endpoint %lu: security policy not available", (long unsigned)i);
  511. continue;
  512. }
  513. endpointFound = true;
  514. /* Select a matching UserTokenPolicy inside the endpoint */
  515. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Endpoint %lu has %lu user token policies", (long unsigned)i, (long unsigned)endpoint->userIdentityTokensSize);
  516. for(size_t j = 0; j < endpoint->userIdentityTokensSize; ++j) {
  517. UA_UserTokenPolicy* userToken = &endpoint->userIdentityTokens[j];
  518. /* Usertokens also have a security policy... */
  519. if (userToken->securityPolicyUri.length > 0 &&
  520. !getSecurityPolicy(client, userToken->securityPolicyUri)) {
  521. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu in endpoint %lu: security policy '%.*s' not available",
  522. (long unsigned)j, (long unsigned)i,
  523. (int)userToken->securityPolicyUri.length, userToken->securityPolicyUri.data);
  524. continue;
  525. }
  526. if(userToken->tokenType > 3) {
  527. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT, "Rejecting UserTokenPolicy %lu in endpoint %lu: invalid token type", (long unsigned)j, (long unsigned)i);
  528. continue;
  529. }
  530. /* Does the token type match the client configuration? */
  531. if (userToken->tokenType == UA_USERTOKENTYPE_ANONYMOUS &&
  532. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN] &&
  533. client->config.userIdentityToken.content.decoded.type != NULL) {
  534. 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);
  535. continue;
  536. }
  537. if (userToken->tokenType == UA_USERTOKENTYPE_USERNAME &&
  538. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
  539. 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);
  540. continue;
  541. }
  542. if (userToken->tokenType == UA_USERTOKENTYPE_CERTIFICATE &&
  543. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]) {
  544. 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);
  545. continue;
  546. }
  547. if (userToken->tokenType == UA_USERTOKENTYPE_ISSUEDTOKEN &&
  548. client->config.userIdentityToken.content.decoded.type != &UA_TYPES[UA_TYPES_ISSUEDIDENTITYTOKEN]) {
  549. 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);
  550. continue;
  551. }
  552. /* Endpoint with matching UserTokenPolicy found. Copy to the configuration. */
  553. tokenFound = true;
  554. UA_EndpointDescription_deleteMembers(&client->config.endpoint);
  555. UA_EndpointDescription temp = *endpoint;
  556. temp.userIdentityTokensSize = 0;
  557. temp.userIdentityTokens = NULL;
  558. UA_UserTokenPolicy_deleteMembers(&client->config.userTokenPolicy);
  559. retval = UA_EndpointDescription_copy(&temp, &client->config.endpoint);
  560. if(retval != UA_STATUSCODE_GOOD) {
  561. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  562. "Copying endpoint description failed with error code %s",
  563. UA_StatusCode_name(retval));
  564. break;
  565. }
  566. retval = UA_UserTokenPolicy_copy(userToken, &client->config.userTokenPolicy);
  567. if(retval != UA_STATUSCODE_GOOD) {
  568. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  569. "Copying user token policy failed with error code %s",
  570. UA_StatusCode_name(retval));
  571. break;
  572. }
  573. #if UA_LOGLEVEL <= 300
  574. const char *securityModeNames[3] = {"None", "Sign", "SignAndEncrypt"};
  575. const char *userTokenTypeNames[4] = {"Anonymous", "UserName",
  576. "Certificate", "IssuedToken"};
  577. UA_String *securityPolicyUri = &userToken->securityPolicyUri;
  578. if(securityPolicyUri->length == 0)
  579. securityPolicyUri = &endpoint->securityPolicyUri;
  580. /* Log the selected endpoint */
  581. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  582. "Selected Endpoint %.*s with SecurityMode %s and SecurityPolicy %.*s",
  583. (int)endpoint->endpointUrl.length, endpoint->endpointUrl.data,
  584. securityModeNames[endpoint->securityMode - 1],
  585. (int)endpoint->securityPolicyUri.length,
  586. endpoint->securityPolicyUri.data);
  587. /* Log the selected UserTokenPolicy */
  588. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  589. "Selected UserTokenPolicy %.*s with UserTokenType %s and SecurityPolicy %.*s",
  590. (int)userToken->policyId.length, userToken->policyId.data,
  591. userTokenTypeNames[userToken->tokenType],
  592. (int)securityPolicyUri->length, securityPolicyUri->data);
  593. #endif
  594. break;
  595. }
  596. if(tokenFound)
  597. break;
  598. }
  599. UA_Array_delete(endpointArray, endpointArraySize,
  600. &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]);
  601. if(retval != UA_STATUSCODE_GOOD)
  602. return retval;
  603. if(!endpointFound) {
  604. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  605. "No suitable endpoint found");
  606. retval = UA_STATUSCODE_BADINTERNALERROR;
  607. } else if(!tokenFound) {
  608. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  609. "No suitable UserTokenPolicy found for the possible endpoints");
  610. retval = UA_STATUSCODE_BADINTERNALERROR;
  611. }
  612. return retval;
  613. }
  614. static UA_StatusCode
  615. createSession(UA_Client *client) {
  616. UA_CreateSessionRequest request;
  617. UA_CreateSessionRequest_init(&request);
  618. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  619. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  620. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  621. if(client->channel.localNonce.length != UA_SESSION_LOCALNONCELENGTH) {
  622. UA_ByteString_deleteMembers(&client->channel.localNonce);
  623. retval = UA_ByteString_allocBuffer(&client->channel.localNonce,
  624. UA_SESSION_LOCALNONCELENGTH);
  625. if(retval != UA_STATUSCODE_GOOD)
  626. return retval;
  627. }
  628. retval = client->channel.securityPolicy->symmetricModule.
  629. generateNonce(client->channel.securityPolicy, &client->channel.localNonce);
  630. if(retval != UA_STATUSCODE_GOOD)
  631. return retval;
  632. }
  633. request.requestHeader.timestamp = UA_DateTime_now();
  634. request.requestHeader.timeoutHint = 10000;
  635. UA_ByteString_copy(&client->channel.localNonce, &request.clientNonce);
  636. request.requestedSessionTimeout = client->config.requestedSessionTimeout;
  637. request.maxResponseMessageSize = UA_INT32_MAX;
  638. UA_String_copy(&client->config.endpoint.endpointUrl, &request.endpointUrl);
  639. UA_ApplicationDescription_copy(&client->config.clientDescription,
  640. &request.clientDescription);
  641. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  642. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  643. UA_ByteString_copy(&client->channel.securityPolicy->localCertificate,
  644. &request.clientCertificate);
  645. }
  646. UA_CreateSessionResponse response;
  647. __UA_Client_Service(client, &request, &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST],
  648. &response, &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE]);
  649. if(response.responseHeader.serviceResult == UA_STATUSCODE_GOOD) {
  650. /* Verify the encrypted response */
  651. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGN ||
  652. client->channel.securityMode == UA_MESSAGESECURITYMODE_SIGNANDENCRYPT) {
  653. if(!UA_ByteString_equal(&response.serverCertificate,
  654. &client->channel.remoteCertificate)) {
  655. retval = UA_STATUSCODE_BADCERTIFICATEINVALID;
  656. goto cleanup;
  657. }
  658. /* Verify the client signature */
  659. retval = checkClientSignature(&client->channel, &response);
  660. if(retval != UA_STATUSCODE_GOOD)
  661. goto cleanup;
  662. }
  663. /* Copy nonce and and authenticationtoken */
  664. UA_ByteString_deleteMembers(&client->channel.remoteNonce);
  665. retval |= UA_ByteString_copy(&response.serverNonce, &client->channel.remoteNonce);
  666. UA_NodeId_deleteMembers(&client->authenticationToken);
  667. retval |= UA_NodeId_copy(&response.authenticationToken, &client->authenticationToken);
  668. }
  669. retval |= response.responseHeader.serviceResult;
  670. cleanup:
  671. UA_CreateSessionRequest_deleteMembers(&request);
  672. UA_CreateSessionResponse_deleteMembers(&response);
  673. return retval;
  674. }
  675. UA_StatusCode
  676. UA_Client_connectTCPSecureChannel(UA_Client *client, const UA_String endpointUrl) {
  677. if(client->state >= UA_CLIENTSTATE_CONNECTED)
  678. return UA_STATUSCODE_GOOD;
  679. UA_ChannelSecurityToken_init(&client->channel.securityToken);
  680. client->channel.state = UA_SECURECHANNELSTATE_FRESH;
  681. client->channel.sendSequenceNumber = 0;
  682. client->requestId = 0;
  683. /* Set the channel SecurityMode */
  684. client->channel.securityMode = client->config.endpoint.securityMode;
  685. if(client->channel.securityMode == UA_MESSAGESECURITYMODE_INVALID)
  686. client->channel.securityMode = UA_MESSAGESECURITYMODE_NONE;
  687. /* Initialized the SecureChannel */
  688. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  689. UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  690. "Initialize the SecurityPolicy context");
  691. if(!client->channel.securityPolicy) {
  692. /* Set the channel SecurityPolicy to #None if no endpoint is selected */
  693. UA_String sps = client->config.endpoint.securityPolicyUri;
  694. if(sps.length == 0) {
  695. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  696. "SecurityPolicy not specified -> use default #None");
  697. sps = UA_STRING("http://opcfoundation.org/UA/SecurityPolicy#None");
  698. }
  699. UA_SecurityPolicy *sp = getSecurityPolicy(client, sps);
  700. if(!sp) {
  701. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  702. "Failed to find the required security policy");
  703. retval = UA_STATUSCODE_BADINTERNALERROR;
  704. goto cleanup;
  705. }
  706. retval = UA_SecureChannel_setSecurityPolicy(&client->channel, sp,
  707. &client->config.endpoint.serverCertificate);
  708. if(retval != UA_STATUSCODE_GOOD) {
  709. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  710. "Failed to set the security policy");
  711. goto cleanup;
  712. }
  713. }
  714. /* Open a TCP connection */
  715. client->connection = client->config.connectionFunc(client->config.localConnectionConfig,
  716. endpointUrl, client->config.timeout,
  717. &client->config.logger);
  718. if(client->connection.state != UA_CONNECTION_OPENING) {
  719. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  720. "Opening the TCP socket failed");
  721. retval = UA_STATUSCODE_BADCONNECTIONCLOSED;
  722. goto cleanup;
  723. }
  724. UA_LOG_INFO(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  725. "TCP connection established");
  726. /* Perform the HEL/ACK handshake */
  727. client->connection.config = client->config.localConnectionConfig;
  728. retval = HelAckHandshake(client, endpointUrl);
  729. if(retval != UA_STATUSCODE_GOOD) {
  730. UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
  731. "HEL/ACK handshake failed");
  732. goto cleanup;
  733. }
  734. setClientState(client, UA_CLIENTSTATE_CONNECTED);
  735. /* Open a SecureChannel. */
  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. }