ua_server_binary.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2014-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2014-2016 (c) Sten Grüner
  7. * Copyright 2014-2015, 2017 (c) Florian Palm
  8. * Copyright 2015-2016 (c) Chris Iatrou
  9. * Copyright 2015-2016 (c) Oleksiy Vasylyev
  10. * Copyright 2016 (c) Joakim L. Gilje
  11. * Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
  12. * Copyright 2016 (c) TorbenD
  13. * Copyright 2017 (c) frax2222
  14. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  15. * Copyright 2019 (c) Kalycito Infotech Private Limited
  16. */
  17. #include <open62541/transport_generated.h>
  18. #include <open62541/transport_generated_encoding_binary.h>
  19. #include <open62541/transport_generated_handling.h>
  20. #include <open62541/types_generated_encoding_binary.h>
  21. #include <open62541/types_generated_handling.h>
  22. #include "ua_securechannel_manager.h"
  23. #include "ua_server_internal.h"
  24. #include "ua_services.h"
  25. #include "ua_session_manager.h"
  26. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  27. // store the authentication token and session ID so we can help fuzzing by setting
  28. // these values in the next request automatically
  29. UA_NodeId unsafe_fuzz_authenticationToken = {
  30. 0, UA_NODEIDTYPE_NUMERIC, {0}
  31. };
  32. #endif
  33. #ifdef UA_DEBUG_DUMP_PKGS_FILE
  34. void UA_debug_dumpCompleteChunk(UA_Server *const server, UA_Connection *const connection, UA_ByteString *messageBuffer);
  35. #endif
  36. /********************/
  37. /* Helper Functions */
  38. /********************/
  39. /* This is not an ERR message, the connection is not closed afterwards */
  40. static UA_StatusCode
  41. sendServiceFault(UA_SecureChannel *channel, const UA_ByteString *msg,
  42. size_t offset, const UA_DataType *responseType,
  43. UA_UInt32 requestId, UA_StatusCode error) {
  44. UA_RequestHeader requestHeader;
  45. UA_StatusCode retval = UA_RequestHeader_decodeBinary(msg, &offset, &requestHeader);
  46. if(retval != UA_STATUSCODE_GOOD)
  47. return retval;
  48. UA_STACKARRAY(UA_Byte, response, responseType->memSize);
  49. UA_init(response, responseType);
  50. UA_ResponseHeader *responseHeader = (UA_ResponseHeader*)response;
  51. responseHeader->requestHandle = requestHeader.requestHandle;
  52. responseHeader->timestamp = UA_DateTime_now();
  53. responseHeader->serviceResult = error;
  54. // Send error message. Message type is MSG and not ERR, since we are on a securechannel!
  55. retval = UA_SecureChannel_sendSymmetricMessage(channel, requestId, UA_MESSAGETYPE_MSG,
  56. response, responseType);
  57. UA_RequestHeader_deleteMembers(&requestHeader);
  58. UA_LOG_DEBUG(channel->securityPolicy->logger, UA_LOGCATEGORY_SERVER,
  59. "Sent ServiceFault with error code %s", UA_StatusCode_name(error));
  60. return retval;
  61. }
  62. typedef enum {
  63. UA_SERVICETYPE_NORMAL,
  64. UA_SERVICETYPE_INSITU,
  65. UA_SERVICETYPE_CUSTOM
  66. } UA_ServiceType;
  67. static void
  68. getServicePointers(UA_UInt32 requestTypeId, const UA_DataType **requestType,
  69. const UA_DataType **responseType, UA_Service *service,
  70. UA_InSituService *serviceInsitu,
  71. UA_Boolean *requiresSession, UA_ServiceType *serviceType) {
  72. switch(requestTypeId) {
  73. case UA_NS0ID_GETENDPOINTSREQUEST_ENCODING_DEFAULTBINARY:
  74. *service = (UA_Service)Service_GetEndpoints;
  75. *requestType = &UA_TYPES[UA_TYPES_GETENDPOINTSREQUEST];
  76. *responseType = &UA_TYPES[UA_TYPES_GETENDPOINTSRESPONSE];
  77. *requiresSession = false;
  78. break;
  79. case UA_NS0ID_FINDSERVERSREQUEST_ENCODING_DEFAULTBINARY:
  80. *service = (UA_Service)Service_FindServers;
  81. *requestType = &UA_TYPES[UA_TYPES_FINDSERVERSREQUEST];
  82. *responseType = &UA_TYPES[UA_TYPES_FINDSERVERSRESPONSE];
  83. *requiresSession = false;
  84. break;
  85. #ifdef UA_ENABLE_DISCOVERY
  86. # ifdef UA_ENABLE_DISCOVERY_MULTICAST
  87. case UA_NS0ID_FINDSERVERSONNETWORKREQUEST_ENCODING_DEFAULTBINARY:
  88. *service = (UA_Service)Service_FindServersOnNetwork;
  89. *requestType = &UA_TYPES[UA_TYPES_FINDSERVERSONNETWORKREQUEST];
  90. *responseType = &UA_TYPES[UA_TYPES_FINDSERVERSONNETWORKRESPONSE];
  91. *requiresSession = false;
  92. break;
  93. # endif
  94. case UA_NS0ID_REGISTERSERVERREQUEST_ENCODING_DEFAULTBINARY:
  95. *service = (UA_Service)Service_RegisterServer;
  96. *requestType = &UA_TYPES[UA_TYPES_REGISTERSERVERREQUEST];
  97. *responseType = &UA_TYPES[UA_TYPES_REGISTERSERVERRESPONSE];
  98. *requiresSession = false;
  99. break;
  100. case UA_NS0ID_REGISTERSERVER2REQUEST_ENCODING_DEFAULTBINARY:
  101. *service = (UA_Service)Service_RegisterServer2;
  102. *requestType = &UA_TYPES[UA_TYPES_REGISTERSERVER2REQUEST];
  103. *responseType = &UA_TYPES[UA_TYPES_REGISTERSERVER2RESPONSE];
  104. *requiresSession = false;
  105. break;
  106. #endif
  107. case UA_NS0ID_CREATESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  108. *service = NULL; //(UA_Service)Service_CreateSession;
  109. *requestType = &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST];
  110. *responseType = &UA_TYPES[UA_TYPES_CREATESESSIONRESPONSE];
  111. *requiresSession = false;
  112. *serviceType = UA_SERVICETYPE_CUSTOM;
  113. break;
  114. case UA_NS0ID_ACTIVATESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  115. *service = NULL; //(UA_Service)Service_ActivateSession;
  116. *requestType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST];
  117. *responseType = &UA_TYPES[UA_TYPES_ACTIVATESESSIONRESPONSE];
  118. *serviceType = UA_SERVICETYPE_CUSTOM;
  119. break;
  120. case UA_NS0ID_CLOSESESSIONREQUEST_ENCODING_DEFAULTBINARY:
  121. *service = (UA_Service)Service_CloseSession;
  122. *requestType = &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST];
  123. *responseType = &UA_TYPES[UA_TYPES_CLOSESESSIONRESPONSE];
  124. break;
  125. case UA_NS0ID_READREQUEST_ENCODING_DEFAULTBINARY:
  126. *service = NULL;
  127. *serviceInsitu = (UA_InSituService)Service_Read;
  128. *requestType = &UA_TYPES[UA_TYPES_READREQUEST];
  129. *responseType = &UA_TYPES[UA_TYPES_READRESPONSE];
  130. *serviceType = UA_SERVICETYPE_INSITU;
  131. break;
  132. case UA_NS0ID_WRITEREQUEST_ENCODING_DEFAULTBINARY:
  133. *service = (UA_Service)Service_Write;
  134. *requestType = &UA_TYPES[UA_TYPES_WRITEREQUEST];
  135. *responseType = &UA_TYPES[UA_TYPES_WRITERESPONSE];
  136. break;
  137. case UA_NS0ID_BROWSEREQUEST_ENCODING_DEFAULTBINARY:
  138. *service = (UA_Service)Service_Browse;
  139. *requestType = &UA_TYPES[UA_TYPES_BROWSEREQUEST];
  140. *responseType = &UA_TYPES[UA_TYPES_BROWSERESPONSE];
  141. break;
  142. case UA_NS0ID_BROWSENEXTREQUEST_ENCODING_DEFAULTBINARY:
  143. *service = (UA_Service)Service_BrowseNext;
  144. *requestType = &UA_TYPES[UA_TYPES_BROWSENEXTREQUEST];
  145. *responseType = &UA_TYPES[UA_TYPES_BROWSENEXTRESPONSE];
  146. break;
  147. case UA_NS0ID_REGISTERNODESREQUEST_ENCODING_DEFAULTBINARY:
  148. *service = (UA_Service)Service_RegisterNodes;
  149. *requestType = &UA_TYPES[UA_TYPES_REGISTERNODESREQUEST];
  150. *responseType = &UA_TYPES[UA_TYPES_REGISTERNODESRESPONSE];
  151. break;
  152. case UA_NS0ID_UNREGISTERNODESREQUEST_ENCODING_DEFAULTBINARY:
  153. *service = (UA_Service)Service_UnregisterNodes;
  154. *requestType = &UA_TYPES[UA_TYPES_UNREGISTERNODESREQUEST];
  155. *responseType = &UA_TYPES[UA_TYPES_UNREGISTERNODESRESPONSE];
  156. break;
  157. case UA_NS0ID_TRANSLATEBROWSEPATHSTONODEIDSREQUEST_ENCODING_DEFAULTBINARY:
  158. *service = (UA_Service)Service_TranslateBrowsePathsToNodeIds;
  159. *requestType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSREQUEST];
  160. *responseType = &UA_TYPES[UA_TYPES_TRANSLATEBROWSEPATHSTONODEIDSRESPONSE];
  161. break;
  162. #ifdef UA_ENABLE_SUBSCRIPTIONS
  163. case UA_NS0ID_CREATESUBSCRIPTIONREQUEST_ENCODING_DEFAULTBINARY:
  164. *service = (UA_Service)Service_CreateSubscription;
  165. *requestType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONREQUEST];
  166. *responseType = &UA_TYPES[UA_TYPES_CREATESUBSCRIPTIONRESPONSE];
  167. break;
  168. case UA_NS0ID_PUBLISHREQUEST_ENCODING_DEFAULTBINARY:
  169. *requestType = &UA_TYPES[UA_TYPES_PUBLISHREQUEST];
  170. *responseType = &UA_TYPES[UA_TYPES_PUBLISHRESPONSE];
  171. break;
  172. case UA_NS0ID_REPUBLISHREQUEST_ENCODING_DEFAULTBINARY:
  173. *service = (UA_Service)Service_Republish;
  174. *requestType = &UA_TYPES[UA_TYPES_REPUBLISHREQUEST];
  175. *responseType = &UA_TYPES[UA_TYPES_REPUBLISHRESPONSE];
  176. break;
  177. case UA_NS0ID_MODIFYSUBSCRIPTIONREQUEST_ENCODING_DEFAULTBINARY:
  178. *service = (UA_Service)Service_ModifySubscription;
  179. *requestType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONREQUEST];
  180. *responseType = &UA_TYPES[UA_TYPES_MODIFYSUBSCRIPTIONRESPONSE];
  181. break;
  182. case UA_NS0ID_SETPUBLISHINGMODEREQUEST_ENCODING_DEFAULTBINARY:
  183. *service = (UA_Service)Service_SetPublishingMode;
  184. *requestType = &UA_TYPES[UA_TYPES_SETPUBLISHINGMODEREQUEST];
  185. *responseType = &UA_TYPES[UA_TYPES_SETPUBLISHINGMODERESPONSE];
  186. break;
  187. case UA_NS0ID_DELETESUBSCRIPTIONSREQUEST_ENCODING_DEFAULTBINARY:
  188. *service = (UA_Service)Service_DeleteSubscriptions;
  189. *requestType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSREQUEST];
  190. *responseType = &UA_TYPES[UA_TYPES_DELETESUBSCRIPTIONSRESPONSE];
  191. break;
  192. case UA_NS0ID_CREATEMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  193. *service = (UA_Service)Service_CreateMonitoredItems;
  194. *requestType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSREQUEST];
  195. *responseType = &UA_TYPES[UA_TYPES_CREATEMONITOREDITEMSRESPONSE];
  196. break;
  197. case UA_NS0ID_DELETEMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  198. *service = (UA_Service)Service_DeleteMonitoredItems;
  199. *requestType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSREQUEST];
  200. *responseType = &UA_TYPES[UA_TYPES_DELETEMONITOREDITEMSRESPONSE];
  201. break;
  202. case UA_NS0ID_MODIFYMONITOREDITEMSREQUEST_ENCODING_DEFAULTBINARY:
  203. *service = (UA_Service)Service_ModifyMonitoredItems;
  204. *requestType = &UA_TYPES[UA_TYPES_MODIFYMONITOREDITEMSREQUEST];
  205. *responseType = &UA_TYPES[UA_TYPES_MODIFYMONITOREDITEMSRESPONSE];
  206. break;
  207. case UA_NS0ID_SETMONITORINGMODEREQUEST_ENCODING_DEFAULTBINARY:
  208. *service = (UA_Service)Service_SetMonitoringMode;
  209. *requestType = &UA_TYPES[UA_TYPES_SETMONITORINGMODEREQUEST];
  210. *responseType = &UA_TYPES[UA_TYPES_SETMONITORINGMODERESPONSE];
  211. break;
  212. #endif
  213. #ifdef UA_ENABLE_HISTORIZING
  214. /* For History read */
  215. case UA_NS0ID_HISTORYREADREQUEST_ENCODING_DEFAULTBINARY:
  216. *service = (UA_Service)Service_HistoryRead;
  217. *requestType = &UA_TYPES[UA_TYPES_HISTORYREADREQUEST];
  218. *responseType = &UA_TYPES[UA_TYPES_HISTORYREADRESPONSE];
  219. break;
  220. /* For History update */
  221. case UA_NS0ID_HISTORYUPDATEREQUEST_ENCODING_DEFAULTBINARY:
  222. *service = (UA_Service)Service_HistoryUpdate;
  223. *requestType = &UA_TYPES[UA_TYPES_HISTORYUPDATEREQUEST];
  224. *responseType = &UA_TYPES[UA_TYPES_HISTORYUPDATERESPONSE];
  225. break;
  226. #endif
  227. #ifdef UA_ENABLE_METHODCALLS
  228. case UA_NS0ID_CALLREQUEST_ENCODING_DEFAULTBINARY:
  229. *service = (UA_Service)Service_Call;
  230. *requestType = &UA_TYPES[UA_TYPES_CALLREQUEST];
  231. *responseType = &UA_TYPES[UA_TYPES_CALLRESPONSE];
  232. break;
  233. #endif
  234. #ifdef UA_ENABLE_NODEMANAGEMENT
  235. case UA_NS0ID_ADDNODESREQUEST_ENCODING_DEFAULTBINARY:
  236. *service = (UA_Service)Service_AddNodes;
  237. *requestType = &UA_TYPES[UA_TYPES_ADDNODESREQUEST];
  238. *responseType = &UA_TYPES[UA_TYPES_ADDNODESRESPONSE];
  239. break;
  240. case UA_NS0ID_ADDREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  241. *service = (UA_Service)Service_AddReferences;
  242. *requestType = &UA_TYPES[UA_TYPES_ADDREFERENCESREQUEST];
  243. *responseType = &UA_TYPES[UA_TYPES_ADDREFERENCESRESPONSE];
  244. break;
  245. case UA_NS0ID_DELETENODESREQUEST_ENCODING_DEFAULTBINARY:
  246. *service = (UA_Service)Service_DeleteNodes;
  247. *requestType = &UA_TYPES[UA_TYPES_DELETENODESREQUEST];
  248. *responseType = &UA_TYPES[UA_TYPES_DELETENODESRESPONSE];
  249. break;
  250. case UA_NS0ID_DELETEREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  251. *service = (UA_Service)Service_DeleteReferences;
  252. *requestType = &UA_TYPES[UA_TYPES_DELETEREFERENCESREQUEST];
  253. *responseType = &UA_TYPES[UA_TYPES_DELETEREFERENCESRESPONSE];
  254. break;
  255. #endif
  256. default:
  257. break;
  258. }
  259. }
  260. /*************************/
  261. /* Process Message Types */
  262. /*************************/
  263. /* HEL -> Open up the connection */
  264. static UA_StatusCode
  265. processHEL(UA_Server *server, UA_Connection *connection,
  266. const UA_ByteString *msg, size_t *offset) {
  267. UA_TcpHelloMessage helloMessage;
  268. UA_StatusCode retval = UA_TcpHelloMessage_decodeBinary(msg, offset, &helloMessage);
  269. if(retval != UA_STATUSCODE_GOOD)
  270. return retval;
  271. /* Currently not checked */
  272. UA_String_deleteMembers(&helloMessage.endpointUrl);
  273. /* TODO: Use the config of the exact NetworkLayer */
  274. if(server->config.networkLayersSize == 0)
  275. return UA_STATUSCODE_BADOUTOFMEMORY;
  276. const UA_ConnectionConfig *localConfig = &server->config.networkLayers[0].localConnectionConfig;
  277. /* Parameterize the connection */
  278. UA_ConnectionConfig remoteConfig;
  279. remoteConfig.protocolVersion = helloMessage.protocolVersion;
  280. remoteConfig.sendBufferSize = helloMessage.sendBufferSize;
  281. remoteConfig.recvBufferSize = helloMessage.receiveBufferSize;
  282. remoteConfig.maxMessageSize = helloMessage.maxMessageSize;
  283. remoteConfig.maxChunkCount = helloMessage.maxChunkCount;
  284. retval = UA_Connection_processHELACK(connection, localConfig, &remoteConfig);
  285. if(retval != UA_STATUSCODE_GOOD) {
  286. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  287. "Connection %i | Error during the HEL/ACK handshake",
  288. (int)(connection->sockfd));
  289. return retval;
  290. }
  291. /* Build acknowledge response */
  292. UA_TcpAcknowledgeMessage ackMessage;
  293. memcpy(&ackMessage, localConfig, sizeof(UA_TcpAcknowledgeMessage)); /* Same struct layout.. */
  294. UA_TcpMessageHeader ackHeader;
  295. ackHeader.messageTypeAndChunkType = UA_MESSAGETYPE_ACK + UA_CHUNKTYPE_FINAL;
  296. ackHeader.messageSize = 8 + 20; /* ackHeader + ackMessage */
  297. /* Get the send buffer from the network layer */
  298. UA_ByteString ack_msg;
  299. UA_ByteString_init(&ack_msg);
  300. retval = connection->getSendBuffer(connection, connection->config.sendBufferSize, &ack_msg);
  301. if(retval != UA_STATUSCODE_GOOD)
  302. return retval;
  303. /* Encode and send the response */
  304. UA_Byte *bufPos = ack_msg.data;
  305. const UA_Byte *bufEnd = &ack_msg.data[ack_msg.length];
  306. retval = UA_TcpMessageHeader_encodeBinary(&ackHeader, &bufPos, bufEnd);
  307. if(retval != UA_STATUSCODE_GOOD) {
  308. connection->releaseSendBuffer(connection, &ack_msg);
  309. return retval;
  310. }
  311. retval = UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &bufPos, bufEnd);
  312. if(retval != UA_STATUSCODE_GOOD) {
  313. connection->releaseSendBuffer(connection, &ack_msg);
  314. return retval;
  315. }
  316. ack_msg.length = ackHeader.messageSize;
  317. return connection->send(connection, &ack_msg);
  318. }
  319. /* OPN -> Open up/renew the securechannel */
  320. static UA_StatusCode
  321. processOPN(UA_Server *server, UA_SecureChannel *channel,
  322. const UA_UInt32 requestId, const UA_ByteString *msg) {
  323. /* Decode the request */
  324. size_t offset = 0;
  325. UA_NodeId requestType;
  326. UA_OpenSecureChannelRequest openSecureChannelRequest;
  327. UA_StatusCode retval = UA_NodeId_decodeBinary(msg, &offset, &requestType);
  328. if(retval != UA_STATUSCODE_GOOD) {
  329. UA_NodeId_deleteMembers(&requestType);
  330. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  331. "Could not decode the NodeId. Closing the connection");
  332. UA_SecureChannelManager_close(&server->secureChannelManager, channel->securityToken.channelId);
  333. return retval;
  334. }
  335. retval = UA_OpenSecureChannelRequest_decodeBinary(msg, &offset, &openSecureChannelRequest);
  336. /* Error occurred */
  337. if(retval != UA_STATUSCODE_GOOD ||
  338. requestType.identifier.numeric != UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST].binaryEncodingId) {
  339. UA_NodeId_deleteMembers(&requestType);
  340. UA_OpenSecureChannelRequest_deleteMembers(&openSecureChannelRequest);
  341. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  342. "Could not decode the OPN message. Closing the connection.");
  343. UA_SecureChannelManager_close(&server->secureChannelManager, channel->securityToken.channelId);
  344. return retval;
  345. }
  346. UA_NodeId_deleteMembers(&requestType);
  347. /* Call the service */
  348. UA_OpenSecureChannelResponse openScResponse;
  349. UA_OpenSecureChannelResponse_init(&openScResponse);
  350. Service_OpenSecureChannel(server, channel, &openSecureChannelRequest, &openScResponse);
  351. UA_OpenSecureChannelRequest_deleteMembers(&openSecureChannelRequest);
  352. if(openScResponse.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  353. UA_LOG_INFO_CHANNEL(&server->config.logger, channel, "Could not open a SecureChannel. "
  354. "Closing the connection.");
  355. UA_SecureChannelManager_close(&server->secureChannelManager,
  356. channel->securityToken.channelId);
  357. return openScResponse.responseHeader.serviceResult;
  358. }
  359. /* Send the response */
  360. retval = UA_SecureChannel_sendAsymmetricOPNMessage(channel, requestId, &openScResponse,
  361. &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE]);
  362. UA_OpenSecureChannelResponse_deleteMembers(&openScResponse);
  363. if(retval != UA_STATUSCODE_GOOD) {
  364. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  365. "Could not send the OPN answer with error code %s",
  366. UA_StatusCode_name(retval));
  367. UA_SecureChannelManager_close(&server->secureChannelManager,
  368. channel->securityToken.channelId);
  369. return retval;
  370. }
  371. return retval;
  372. }
  373. static UA_StatusCode
  374. processMSG(UA_Server *server, UA_SecureChannel *channel,
  375. UA_UInt32 requestId, const UA_ByteString *msg) {
  376. /* At 0, the nodeid starts... */
  377. size_t offset = 0;
  378. /* Decode the nodeid */
  379. UA_NodeId requestTypeId;
  380. UA_StatusCode retval = UA_NodeId_decodeBinary(msg, &offset, &requestTypeId);
  381. if(retval != UA_STATUSCODE_GOOD)
  382. return retval;
  383. if(requestTypeId.namespaceIndex != 0 ||
  384. requestTypeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  385. UA_NodeId_deleteMembers(&requestTypeId); /* leads to badserviceunsupported */
  386. /* Store the start-position of the request */
  387. size_t requestPos = offset;
  388. /* Get the service pointers */
  389. UA_Service service = NULL;
  390. UA_InSituService serviceInsitu = NULL;
  391. const UA_DataType *requestType = NULL;
  392. const UA_DataType *responseType = NULL;
  393. UA_Boolean sessionRequired = true;
  394. UA_ServiceType serviceType = UA_SERVICETYPE_NORMAL;
  395. getServicePointers(requestTypeId.identifier.numeric, &requestType,
  396. &responseType, &service, &serviceInsitu, &sessionRequired, &serviceType);
  397. if(!requestType) {
  398. if(requestTypeId.identifier.numeric == 787) {
  399. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  400. "Client requested a subscription, " \
  401. "but those are not enabled in the build");
  402. } else {
  403. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  404. "Unknown request with type identifier %i",
  405. requestTypeId.identifier.numeric);
  406. }
  407. return sendServiceFault(channel, msg, requestPos, &UA_TYPES[UA_TYPES_SERVICEFAULT],
  408. requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  409. }
  410. UA_assert(responseType);
  411. /* Decode the request */
  412. UA_STACKARRAY(UA_Byte, request, requestType->memSize);
  413. UA_RequestHeader *requestHeader = (UA_RequestHeader*)request;
  414. retval = UA_decodeBinary(msg, &offset, request, requestType, server->config.customDataTypes);
  415. if(retval != UA_STATUSCODE_GOOD) {
  416. UA_LOG_DEBUG_CHANNEL(&server->config.logger, channel,
  417. "Could not decode the request");
  418. return sendServiceFault(channel, msg, requestPos, responseType, requestId, retval);
  419. }
  420. /* Prepare the respone */
  421. UA_STACKARRAY(UA_Byte, responseBuf, responseType->memSize);
  422. void *response = (void*)(uintptr_t)&responseBuf[0]; /* Get around aliasing rules */
  423. UA_init(response, responseType);
  424. UA_Session *session = NULL; /* must be initialized before goto send_response */
  425. /* CreateSession doesn't need a session */
  426. if(requestType == &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST]) {
  427. Service_CreateSession(server, channel,
  428. (const UA_CreateSessionRequest *)request,
  429. (UA_CreateSessionResponse *)response);
  430. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  431. // store the authentication token and session ID so we can help fuzzing by setting
  432. // these values in the next request automatically
  433. UA_CreateSessionResponse *res = (UA_CreateSessionResponse *)response;
  434. UA_NodeId_copy(&res->authenticationToken, &unsafe_fuzz_authenticationToken);
  435. #endif
  436. goto send_response;
  437. }
  438. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  439. // set the authenticationToken from the create session request to help fuzzing cover more lines
  440. UA_NodeId_deleteMembers(&requestHeader->authenticationToken);
  441. if(!UA_NodeId_isNull(&unsafe_fuzz_authenticationToken))
  442. UA_NodeId_copy(&unsafe_fuzz_authenticationToken, &requestHeader->authenticationToken);
  443. #endif
  444. /* Find the matching session */
  445. session = (UA_Session*)UA_SecureChannel_getSession(channel, &requestHeader->authenticationToken);
  446. if(!session && !UA_NodeId_isNull(&requestHeader->authenticationToken))
  447. session = UA_SessionManager_getSessionByToken(&server->sessionManager,
  448. &requestHeader->authenticationToken);
  449. if(requestType == &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST]) {
  450. if(!session) {
  451. UA_LOG_DEBUG_CHANNEL(&server->config.logger, channel,
  452. "Trying to activate a session that is " \
  453. "not known in the server");
  454. UA_deleteMembers(request, requestType);
  455. return sendServiceFault(channel, msg, requestPos, responseType,
  456. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  457. }
  458. Service_ActivateSession(server, channel, session,
  459. (const UA_ActivateSessionRequest*)request,
  460. (UA_ActivateSessionResponse*)response);
  461. goto send_response;
  462. }
  463. /* Set an anonymous, inactive session for services that need no session */
  464. UA_Session anonymousSession;
  465. if(!session) {
  466. if(sessionRequired) {
  467. UA_LOG_WARNING_CHANNEL(&server->config.logger, channel,
  468. "Service request %i without a valid session",
  469. requestType->binaryEncodingId);
  470. UA_deleteMembers(request, requestType);
  471. return sendServiceFault(channel, msg, requestPos, responseType,
  472. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  473. }
  474. UA_Session_init(&anonymousSession);
  475. anonymousSession.sessionId = UA_NODEID_GUID(0, UA_GUID_NULL);
  476. anonymousSession.header.channel = channel;
  477. session = &anonymousSession;
  478. }
  479. /* Trying to use a non-activated session?
  480. * Do not allow if request is of type CloseSessionRequest */
  481. if(sessionRequired && !session->activated && requestType != &UA_TYPES[UA_TYPES_CLOSESESSIONREQUEST]) {
  482. UA_LOG_WARNING_SESSION(&server->config.logger, session,
  483. "Calling service %i on a non-activated session",
  484. requestType->binaryEncodingId);
  485. UA_SessionManager_removeSession(&server->sessionManager,
  486. &session->header.authenticationToken);
  487. UA_deleteMembers(request, requestType);
  488. return sendServiceFault(channel, msg, requestPos, responseType,
  489. requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  490. }
  491. /* The session is bound to another channel */
  492. if(session != &anonymousSession && session->header.channel != channel) {
  493. UA_LOG_WARNING_CHANNEL(&server->config.logger, channel,
  494. "Client tries to use a Session that is not "
  495. "bound to this SecureChannel");
  496. UA_deleteMembers(request, requestType);
  497. return sendServiceFault(channel, msg, requestPos, responseType,
  498. requestId, UA_STATUSCODE_BADSECURECHANNELIDINVALID);
  499. }
  500. /* Update the session lifetime */
  501. UA_Session_updateLifetime(session);
  502. #ifdef UA_ENABLE_SUBSCRIPTIONS
  503. /* The publish request is not answered immediately */
  504. if(requestType == &UA_TYPES[UA_TYPES_PUBLISHREQUEST]) {
  505. Service_Publish(server, session,
  506. (const UA_PublishRequest*)request, requestId);
  507. UA_deleteMembers(request, requestType);
  508. return UA_STATUSCODE_GOOD;
  509. }
  510. #endif
  511. send_response:
  512. /* Prepare the ResponseHeader */
  513. ((UA_ResponseHeader*)response)->requestHandle = requestHeader->requestHandle;
  514. ((UA_ResponseHeader*)response)->timestamp = UA_DateTime_now();
  515. /* Check timestamp in the request header */
  516. if(!(requestHeader->timestamp)) {
  517. return sendServiceFault(channel, msg, requestPos, responseType,
  518. requestId, UA_STATUSCODE_BADINVALIDTIMESTAMP);
  519. }
  520. /* Process normal services before initializing the message context.
  521. * Some services may initialize new message contexts and to support network
  522. * layers only providing one send buffer, only one message context can be
  523. * initialized concurrently. */
  524. if(serviceType == UA_SERVICETYPE_NORMAL)
  525. service(server, session, request, response);
  526. /* Start the message */
  527. UA_NodeId typeId = UA_NODEID_NUMERIC(0, responseType->binaryEncodingId);
  528. UA_MessageContext mc;
  529. retval = UA_MessageContext_begin(&mc, channel, requestId, UA_MESSAGETYPE_MSG);
  530. if(retval != UA_STATUSCODE_GOOD)
  531. goto cleanup;
  532. /* Assert's required for clang-analyzer */
  533. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  534. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  535. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  536. if(retval != UA_STATUSCODE_GOOD)
  537. goto cleanup;
  538. switch(serviceType) {
  539. case UA_SERVICETYPE_CUSTOM:
  540. /* Was processed before...*/
  541. retval = UA_MessageContext_encode(&mc, response, responseType);
  542. break;
  543. case UA_SERVICETYPE_INSITU:
  544. retval = serviceInsitu
  545. (server, session, &mc, request, (UA_ResponseHeader*)response);
  546. break;
  547. case UA_SERVICETYPE_NORMAL:
  548. default:
  549. retval = UA_MessageContext_encode(&mc, response, responseType);
  550. break;
  551. }
  552. /* Finish sending the message */
  553. if(retval != UA_STATUSCODE_GOOD) {
  554. UA_MessageContext_abort(&mc);
  555. goto cleanup;
  556. }
  557. retval = UA_MessageContext_finish(&mc);
  558. cleanup:
  559. if(retval != UA_STATUSCODE_GOOD)
  560. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  561. "Could not send the message over the SecureChannel "
  562. "with StatusCode %s", UA_StatusCode_name(retval));
  563. /* Clean up */
  564. UA_deleteMembers(request, requestType);
  565. UA_deleteMembers(response, responseType);
  566. return retval;
  567. }
  568. /* Takes decoded messages starting at the nodeid of the content type. */
  569. static void
  570. processSecureChannelMessage(void *application, UA_SecureChannel *channel,
  571. UA_MessageType messagetype, UA_UInt32 requestId,
  572. const UA_ByteString *message) {
  573. UA_Server *server = (UA_Server*)application;
  574. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  575. switch(messagetype) {
  576. case UA_MESSAGETYPE_OPN:
  577. UA_LOG_TRACE_CHANNEL(&server->config.logger, channel,
  578. "Process an OPN on an open channel");
  579. retval = processOPN(server, channel, requestId, message);
  580. break;
  581. case UA_MESSAGETYPE_MSG:
  582. UA_LOG_TRACE_CHANNEL(&server->config.logger, channel, "Process a MSG");
  583. retval = processMSG(server, channel, requestId, message);
  584. break;
  585. case UA_MESSAGETYPE_CLO:
  586. UA_LOG_TRACE_CHANNEL(&server->config.logger, channel, "Process a CLO");
  587. Service_CloseSecureChannel(server, channel);
  588. break;
  589. default:
  590. UA_LOG_TRACE_CHANNEL(&server->config.logger, channel, "Invalid message type");
  591. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  592. break;
  593. }
  594. if(retval != UA_STATUSCODE_GOOD) {
  595. UA_LOG_INFO_CHANNEL(&server->config.logger, channel,
  596. "Processing the message failed with StatusCode %s. "
  597. "Closing the channel.", UA_StatusCode_name(retval));
  598. Service_CloseSecureChannel(server, channel);
  599. }
  600. }
  601. static UA_StatusCode
  602. createSecureChannel(void *application, UA_Connection *connection,
  603. UA_AsymmetricAlgorithmSecurityHeader *asymHeader) {
  604. UA_Server *server = (UA_Server*)application;
  605. /* Iterate over available endpoints and choose the correct one */
  606. UA_EndpointDescription *endpoint = NULL;
  607. UA_SecurityPolicy *securityPolicy = NULL;
  608. for(size_t i = 0; i < server->config.endpointsSize; ++i) {
  609. UA_EndpointDescription *endpointCandidate = &server->config.endpoints[i];
  610. if(!UA_ByteString_equal(&asymHeader->securityPolicyUri,
  611. &endpointCandidate->securityPolicyUri))
  612. continue;
  613. securityPolicy = UA_SecurityPolicy_getSecurityPolicyByUri(server,
  614. (UA_ByteString*)&endpointCandidate->securityPolicyUri);
  615. if(!securityPolicy)
  616. return UA_STATUSCODE_BADINTERNALERROR;
  617. UA_StatusCode retval = securityPolicy->asymmetricModule.
  618. compareCertificateThumbprint(securityPolicy,
  619. &asymHeader->receiverCertificateThumbprint);
  620. if(retval != UA_STATUSCODE_GOOD)
  621. continue;
  622. /* We found the correct endpoint (except for security mode) The endpoint
  623. * needs to be changed by the client / server to match the security
  624. * mode. The server does this in the securechannel manager */
  625. endpoint = endpointCandidate;
  626. break;
  627. }
  628. if(!endpoint)
  629. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  630. /* Create a new channel */
  631. return UA_SecureChannelManager_create(&server->secureChannelManager, connection,
  632. securityPolicy, asymHeader);
  633. }
  634. static UA_StatusCode
  635. processCompleteChunkWithoutChannel(UA_Server *server, UA_Connection *connection,
  636. UA_ByteString *message) {
  637. /* Process chunk without a channel; must be OPN */
  638. UA_LOG_TRACE(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  639. "Connection %i | No channel attached to the connection. "
  640. "Process the chunk directly", (int)(connection->sockfd));
  641. size_t offset = 0;
  642. UA_TcpMessageHeader tcpMessageHeader;
  643. UA_StatusCode retval =
  644. UA_TcpMessageHeader_decodeBinary(message, &offset, &tcpMessageHeader);
  645. if(retval != UA_STATUSCODE_GOOD)
  646. return retval;
  647. // Only HEL and OPN messages possible without a channel (on the server side)
  648. switch(tcpMessageHeader.messageTypeAndChunkType & 0x00ffffffu) {
  649. case UA_MESSAGETYPE_HEL:
  650. retval = processHEL(server, connection, message, &offset);
  651. break;
  652. case UA_MESSAGETYPE_OPN:
  653. {
  654. UA_LOG_TRACE(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  655. "Connection %i | Process OPN message", (int)(connection->sockfd));
  656. /* Called before HEL */
  657. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  658. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  659. break;
  660. }
  661. // Decode the asymmetric algorithm security header since it is not encrypted and
  662. // needed to decide what security policy to use.
  663. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  664. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  665. size_t messageHeaderOffset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  666. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(message,
  667. &messageHeaderOffset,
  668. &asymHeader);
  669. if(retval != UA_STATUSCODE_GOOD)
  670. break;
  671. retval = createSecureChannel(server, connection, &asymHeader);
  672. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  673. if(retval != UA_STATUSCODE_GOOD)
  674. break;
  675. retval = UA_SecureChannel_decryptAddChunk(connection->channel, message, false);
  676. if(retval != UA_STATUSCODE_GOOD)
  677. break;
  678. UA_SecureChannel_processCompleteMessages(connection->channel, server,
  679. processSecureChannelMessage);
  680. break;
  681. }
  682. default:
  683. UA_LOG_TRACE(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  684. "Connection %i | Expected OPN or HEL message on a connection "
  685. "without a SecureChannel", (int)(connection->sockfd));
  686. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  687. break;
  688. }
  689. return retval;
  690. }
  691. static UA_StatusCode
  692. processCompleteChunk(void *const application, UA_Connection *connection,
  693. UA_ByteString *chunk) {
  694. UA_Server *server = (UA_Server*)application;
  695. #ifdef UA_DEBUG_DUMP_PKGS_FILE
  696. UA_debug_dumpCompleteChunk(server, connection, chunk);
  697. #endif
  698. if(!connection->channel)
  699. return processCompleteChunkWithoutChannel(server, connection, chunk);
  700. return UA_SecureChannel_decryptAddChunk(connection->channel, chunk, false);
  701. }
  702. void
  703. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  704. UA_ByteString *message) {
  705. UA_LOG_TRACE(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  706. "Connection %i | Received a packet.", (int)(connection->sockfd));
  707. #ifdef UA_DEBUG_DUMP_PKGS
  708. UA_dump_hex_pkg(message->data, message->length);
  709. #endif
  710. UA_StatusCode retval = UA_Connection_processChunks(connection, server,
  711. processCompleteChunk, message);
  712. if(retval != UA_STATUSCODE_GOOD) {
  713. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_NETWORK,
  714. "Connection %i | Processing the message failed with "
  715. "error %s", (int)(connection->sockfd), UA_StatusCode_name(retval));
  716. /* Send an ERR message and close the connection */
  717. UA_TcpErrorMessage error;
  718. error.error = retval;
  719. error.reason = UA_STRING_NULL;
  720. UA_Connection_sendError(connection, &error);
  721. connection->close(connection);
  722. return;
  723. }
  724. UA_SecureChannel *channel = connection->channel;
  725. if(!channel)
  726. return;
  727. /* Process complete messages */
  728. UA_SecureChannel_processCompleteMessages(channel, server, processSecureChannelMessage);
  729. /* Is the channel still open? */
  730. if(channel->state == UA_SECURECHANNELSTATE_CLOSED)
  731. return;
  732. /* Store unused decoded chunks internally in the SecureChannel */
  733. UA_SecureChannel_persistIncompleteMessages(connection->channel);
  734. }
  735. #ifdef UA_ENABLE_MULTITHREADING
  736. static void
  737. deleteConnection(UA_Server *server, UA_Connection *connection) {
  738. connection->free(connection);
  739. }
  740. #endif
  741. void
  742. UA_Server_removeConnection(UA_Server *server, UA_Connection *connection) {
  743. UA_Connection_detachSecureChannel(connection);
  744. #ifndef UA_ENABLE_MULTITHREADING
  745. connection->free(connection);
  746. #else
  747. UA_DelayedCallback *dc = (UA_DelayedCallback*)UA_malloc(sizeof(UA_DelayedCallback));
  748. if(!dc)
  749. return; /* Malloc cannot fail on OS's that support multithreading. They
  750. * rather kill the process. */
  751. dc->callback = (UA_ApplicationCallback)deleteConnection;
  752. dc->application = server;
  753. dc->data = connection;
  754. UA_WorkQueue_enqueueDelayed(&server->workQueue, dc);
  755. #endif
  756. }