ua_server_binary.c 35 KB

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