ua_server_binary.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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_util.h"
  17. #include "ua_server_internal.h"
  18. #include "ua_services.h"
  19. #include "ua_securechannel_manager.h"
  20. #include "ua_session_manager.h"
  21. #include "ua_types_generated_encoding_binary.h"
  22. #include "ua_transport_generated.h"
  23. #include "ua_transport_generated_handling.h"
  24. #include "ua_transport_generated_encoding_binary.h"
  25. #include "ua_types_generated_handling.h"
  26. #include "ua_securitypolicy_none.h"
  27. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  28. // store the authentication token and session ID so we can help fuzzing by setting
  29. // these values in the next request automatically
  30. UA_NodeId unsafe_fuzz_authenticationToken = {
  31. 0, UA_NODEIDTYPE_NUMERIC, {0}
  32. };
  33. #endif
  34. #ifdef UA_DEBUG_DUMP_PKGS_FILE
  35. void UA_debug_dumpCompleteChunk(UA_Server *const server, UA_Connection *const connection, UA_ByteString *messageBuffer);
  36. #endif
  37. /********************/
  38. /* Helper Functions */
  39. /********************/
  40. /* This is not an ERR message, the connection is not closed afterwards */
  41. static UA_StatusCode
  42. sendServiceFault(UA_SecureChannel *channel, const UA_ByteString *msg,
  43. size_t offset, const UA_DataType *responseType,
  44. UA_UInt32 requestId, UA_StatusCode error) {
  45. UA_RequestHeader requestHeader;
  46. UA_StatusCode retval = UA_RequestHeader_decodeBinary(msg, &offset, &requestHeader);
  47. if(retval != UA_STATUSCODE_GOOD)
  48. return retval;
  49. UA_STACKARRAY(UA_Byte, response, responseType->memSize);
  50. UA_init(response, responseType);
  51. UA_ResponseHeader *responseHeader = (UA_ResponseHeader*)response;
  52. responseHeader->requestHandle = requestHeader.requestHandle;
  53. responseHeader->timestamp = UA_DateTime_now();
  54. responseHeader->serviceResult = error;
  55. // Send error message. Message type is MSG and not ERR, since we are on a securechannel!
  56. retval = UA_SecureChannel_sendSymmetricMessage(channel, requestId, UA_MESSAGETYPE_MSG,
  57. response, responseType);
  58. UA_RequestHeader_deleteMembers(&requestHeader);
  59. UA_LOG_DEBUG(channel->securityPolicy->logger, UA_LOGCATEGORY_SERVER,
  60. "Sent ServiceFault with error code %s", UA_StatusCode_name(error));
  61. return retval;
  62. }
  63. typedef enum {
  64. UA_SERVICETYPE_NORMAL,
  65. UA_SERVICETYPE_INSITU,
  66. UA_SERVICETYPE_CUSTOM
  67. } UA_ServiceType;
  68. static void
  69. getServicePointers(UA_UInt32 requestTypeId, const UA_DataType **requestType,
  70. const UA_DataType **responseType, UA_Service *service,
  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 = (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 = (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 = (UA_Service)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_METHODCALLS
  213. case UA_NS0ID_CALLREQUEST_ENCODING_DEFAULTBINARY:
  214. *service = (UA_Service)Service_Call;
  215. *requestType = &UA_TYPES[UA_TYPES_CALLREQUEST];
  216. *responseType = &UA_TYPES[UA_TYPES_CALLRESPONSE];
  217. break;
  218. #endif
  219. #ifdef UA_ENABLE_NODEMANAGEMENT
  220. case UA_NS0ID_ADDNODESREQUEST_ENCODING_DEFAULTBINARY:
  221. *service = (UA_Service)Service_AddNodes;
  222. *requestType = &UA_TYPES[UA_TYPES_ADDNODESREQUEST];
  223. *responseType = &UA_TYPES[UA_TYPES_ADDNODESRESPONSE];
  224. break;
  225. case UA_NS0ID_ADDREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  226. *service = (UA_Service)Service_AddReferences;
  227. *requestType = &UA_TYPES[UA_TYPES_ADDREFERENCESREQUEST];
  228. *responseType = &UA_TYPES[UA_TYPES_ADDREFERENCESRESPONSE];
  229. break;
  230. case UA_NS0ID_DELETENODESREQUEST_ENCODING_DEFAULTBINARY:
  231. *service = (UA_Service)Service_DeleteNodes;
  232. *requestType = &UA_TYPES[UA_TYPES_DELETENODESREQUEST];
  233. *responseType = &UA_TYPES[UA_TYPES_DELETENODESRESPONSE];
  234. break;
  235. case UA_NS0ID_DELETEREFERENCESREQUEST_ENCODING_DEFAULTBINARY:
  236. *service = (UA_Service)Service_DeleteReferences;
  237. *requestType = &UA_TYPES[UA_TYPES_DELETEREFERENCESREQUEST];
  238. *responseType = &UA_TYPES[UA_TYPES_DELETEREFERENCESRESPONSE];
  239. break;
  240. #endif
  241. default:
  242. break;
  243. }
  244. }
  245. /*************************/
  246. /* Process Message Types */
  247. /*************************/
  248. /* HEL -> Open up the connection */
  249. static UA_StatusCode
  250. processHEL(UA_Server *server, UA_Connection *connection,
  251. const UA_ByteString *msg, size_t *offset) {
  252. UA_TcpHelloMessage helloMessage;
  253. UA_StatusCode retval = UA_TcpHelloMessage_decodeBinary(msg, offset, &helloMessage);
  254. if(retval != UA_STATUSCODE_GOOD)
  255. return retval;
  256. /* Parameterize the connection */
  257. connection->remoteConf.maxChunkCount = helloMessage.maxChunkCount; /* zero -> unlimited */
  258. connection->remoteConf.maxMessageSize = helloMessage.maxMessageSize; /* zero -> unlimited */
  259. connection->remoteConf.protocolVersion = helloMessage.protocolVersion;
  260. connection->remoteConf.recvBufferSize = helloMessage.receiveBufferSize;
  261. if(connection->localConf.sendBufferSize > helloMessage.receiveBufferSize)
  262. connection->localConf.sendBufferSize = helloMessage.receiveBufferSize;
  263. connection->remoteConf.sendBufferSize = helloMessage.sendBufferSize;
  264. if(connection->localConf.recvBufferSize > helloMessage.sendBufferSize)
  265. connection->localConf.recvBufferSize = helloMessage.sendBufferSize;
  266. UA_String_deleteMembers(&helloMessage.endpointUrl);
  267. if(connection->remoteConf.recvBufferSize == 0) {
  268. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  269. "Connection %i | Remote end indicated a receive buffer size of 0. "
  270. "Not able to send any messages.",
  271. connection->sockfd);
  272. return UA_STATUSCODE_BADINTERNALERROR;
  273. }
  274. connection->state = UA_CONNECTION_ESTABLISHED;
  275. /* Build acknowledge response */
  276. UA_TcpAcknowledgeMessage ackMessage;
  277. ackMessage.protocolVersion = connection->localConf.protocolVersion;
  278. ackMessage.receiveBufferSize = connection->localConf.recvBufferSize;
  279. ackMessage.sendBufferSize = connection->localConf.sendBufferSize;
  280. ackMessage.maxMessageSize = connection->localConf.maxMessageSize;
  281. ackMessage.maxChunkCount = connection->localConf.maxChunkCount;
  282. UA_TcpMessageHeader ackHeader;
  283. ackHeader.messageTypeAndChunkType = UA_MESSAGETYPE_ACK + UA_CHUNKTYPE_FINAL;
  284. ackHeader.messageSize = 8 + 20; /* ackHeader + ackMessage */
  285. /* Get the send buffer from the network layer */
  286. UA_ByteString ack_msg;
  287. UA_ByteString_init(&ack_msg);
  288. retval = connection->getSendBuffer(connection, connection->localConf.sendBufferSize,
  289. &ack_msg);
  290. if(retval != UA_STATUSCODE_GOOD)
  291. return retval;
  292. /* Encode and send the response */
  293. UA_Byte *bufPos = ack_msg.data;
  294. const UA_Byte *bufEnd = &ack_msg.data[ack_msg.length];
  295. retval = UA_TcpMessageHeader_encodeBinary(&ackHeader, &bufPos, bufEnd);
  296. if(retval != UA_STATUSCODE_GOOD) {
  297. connection->releaseSendBuffer(connection, &ack_msg);
  298. return retval;
  299. }
  300. retval = UA_TcpAcknowledgeMessage_encodeBinary(&ackMessage, &bufPos, bufEnd);
  301. if(retval != UA_STATUSCODE_GOOD) {
  302. connection->releaseSendBuffer(connection, &ack_msg);
  303. return retval;
  304. }
  305. ack_msg.length = ackHeader.messageSize;
  306. return connection->send(connection, &ack_msg);
  307. }
  308. /* OPN -> Open up/renew the securechannel */
  309. static UA_StatusCode
  310. processOPN(UA_Server *server, UA_SecureChannel *channel,
  311. const UA_UInt32 requestId, const UA_ByteString *msg) {
  312. /* Decode the request */
  313. size_t offset = 0;
  314. UA_NodeId requestType;
  315. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  316. UA_OpenSecureChannelRequest openSecureChannelRequest;
  317. retval |= UA_NodeId_decodeBinary(msg, &offset, &requestType);
  318. retval |= UA_OpenSecureChannelRequest_decodeBinary(msg, &offset, &openSecureChannelRequest);
  319. /* Error occurred */
  320. if(retval != UA_STATUSCODE_GOOD ||
  321. requestType.identifier.numeric != UA_TYPES[UA_TYPES_OPENSECURECHANNELREQUEST].binaryEncodingId) {
  322. UA_NodeId_deleteMembers(&requestType);
  323. UA_OpenSecureChannelRequest_deleteMembers(&openSecureChannelRequest);
  324. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  325. "Could not decode the OPN message. Closing the connection.");
  326. UA_SecureChannelManager_close(&server->secureChannelManager, channel->securityToken.channelId);
  327. return retval;
  328. }
  329. UA_NodeId_deleteMembers(&requestType);
  330. /* Call the service */
  331. UA_OpenSecureChannelResponse openScResponse;
  332. UA_OpenSecureChannelResponse_init(&openScResponse);
  333. Service_OpenSecureChannel(server, channel, &openSecureChannelRequest, &openScResponse);
  334. UA_OpenSecureChannelRequest_deleteMembers(&openSecureChannelRequest);
  335. if(openScResponse.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
  336. UA_LOG_INFO_CHANNEL(server->config.logger, channel, "Could not open a SecureChannel. "
  337. "Closing the connection.");
  338. UA_SecureChannelManager_close(&server->secureChannelManager,
  339. channel->securityToken.channelId);
  340. return openScResponse.responseHeader.serviceResult;
  341. }
  342. /* Send the response */
  343. retval = UA_SecureChannel_sendAsymmetricOPNMessage(channel, requestId, &openScResponse,
  344. &UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE]);
  345. UA_OpenSecureChannelResponse_deleteMembers(&openScResponse);
  346. if(retval != UA_STATUSCODE_GOOD) {
  347. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  348. "Could not send the OPN answer with error code %s",
  349. UA_StatusCode_name(retval));
  350. UA_SecureChannelManager_close(&server->secureChannelManager,
  351. channel->securityToken.channelId);
  352. }
  353. return retval;
  354. }
  355. static UA_StatusCode
  356. processMSG(UA_Server *server, UA_SecureChannel *channel,
  357. UA_UInt32 requestId, const UA_ByteString *msg) {
  358. /* At 0, the nodeid starts... */
  359. size_t offset = 0;
  360. /* Decode the nodeid */
  361. UA_NodeId requestTypeId;
  362. UA_StatusCode retval = UA_NodeId_decodeBinary(msg, &offset, &requestTypeId);
  363. if(retval != UA_STATUSCODE_GOOD)
  364. return retval;
  365. if(requestTypeId.namespaceIndex != 0 ||
  366. requestTypeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  367. UA_NodeId_deleteMembers(&requestTypeId); /* leads to badserviceunsupported */
  368. /* Store the start-position of the request */
  369. size_t requestPos = offset;
  370. /* Get the service pointers */
  371. UA_Service service = NULL;
  372. const UA_DataType *requestType = NULL;
  373. const UA_DataType *responseType = NULL;
  374. UA_Boolean sessionRequired = true;
  375. UA_ServiceType serviceType = UA_SERVICETYPE_NORMAL;
  376. getServicePointers(requestTypeId.identifier.numeric, &requestType,
  377. &responseType, &service, &sessionRequired, &serviceType);
  378. if(!requestType) {
  379. if(requestTypeId.identifier.numeric == 787) {
  380. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  381. "Client requested a subscription, " \
  382. "but those are not enabled in the build");
  383. } else {
  384. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  385. "Unknown request with type identifier %i",
  386. requestTypeId.identifier.numeric);
  387. }
  388. return sendServiceFault(channel, msg, requestPos, &UA_TYPES[UA_TYPES_SERVICEFAULT],
  389. requestId, UA_STATUSCODE_BADSERVICEUNSUPPORTED);
  390. }
  391. UA_assert(responseType);
  392. /* Decode the request */
  393. UA_STACKARRAY(UA_Byte, request, requestType->memSize);
  394. UA_RequestHeader *requestHeader = (UA_RequestHeader*)request;
  395. retval = UA_decodeBinary(msg, &offset, request, requestType,
  396. server->config.customDataTypesSize,
  397. server->config.customDataTypes);
  398. if(retval != UA_STATUSCODE_GOOD) {
  399. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  400. "Could not decode the request");
  401. return sendServiceFault(channel, msg, requestPos, responseType, requestId, retval);
  402. }
  403. /* Prepare the respone */
  404. UA_STACKARRAY(UA_Byte, responseBuf, responseType->memSize);
  405. void *response = (void*)(uintptr_t)&responseBuf[0]; /* Get around aliasing rules */
  406. UA_init(response, responseType);
  407. UA_Session *session = NULL; /* must be initialized before goto send_response */
  408. /* CreateSession doesn't need a session */
  409. if(requestType == &UA_TYPES[UA_TYPES_CREATESESSIONREQUEST]) {
  410. Service_CreateSession(server, channel,
  411. (const UA_CreateSessionRequest *)request,
  412. (UA_CreateSessionResponse *)response);
  413. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  414. // store the authentication token and session ID so we can help fuzzing by setting
  415. // these values in the next request automatically
  416. UA_CreateSessionResponse *res = (UA_CreateSessionResponse *)response;
  417. UA_NodeId_copy(&res->authenticationToken, &unsafe_fuzz_authenticationToken);
  418. #endif
  419. goto send_response;
  420. }
  421. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  422. // set the authenticationToken from the create session request to help fuzzing cover more lines
  423. UA_NodeId_deleteMembers(&requestHeader->authenticationToken);
  424. if(!UA_NodeId_isNull(&unsafe_fuzz_authenticationToken))
  425. UA_NodeId_copy(&unsafe_fuzz_authenticationToken, &requestHeader->authenticationToken);
  426. #endif
  427. /* Find the matching session */
  428. session = (UA_Session*)UA_SecureChannel_getSession(channel, &requestHeader->authenticationToken);
  429. if(!session && !UA_NodeId_isNull(&requestHeader->authenticationToken))
  430. session = UA_SessionManager_getSessionByToken(&server->sessionManager,
  431. &requestHeader->authenticationToken);
  432. if(requestType == &UA_TYPES[UA_TYPES_ACTIVATESESSIONREQUEST]) {
  433. if(!session) {
  434. UA_LOG_DEBUG_CHANNEL(server->config.logger, channel,
  435. "Trying to activate a session that is " \
  436. "not known in the server");
  437. UA_deleteMembers(request, requestType);
  438. return sendServiceFault(channel, msg, requestPos, responseType,
  439. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  440. }
  441. Service_ActivateSession(server, channel, session,
  442. (const UA_ActivateSessionRequest*)request,
  443. (UA_ActivateSessionResponse*)response);
  444. goto send_response;
  445. }
  446. /* Set an anonymous, inactive session for services that need no session */
  447. UA_Session anonymousSession;
  448. if(!session) {
  449. if(sessionRequired) {
  450. UA_LOG_WARNING_CHANNEL(server->config.logger, channel,
  451. "Service request %i without a valid session",
  452. requestType->binaryEncodingId);
  453. UA_deleteMembers(request, requestType);
  454. return sendServiceFault(channel, msg, requestPos, responseType,
  455. requestId, UA_STATUSCODE_BADSESSIONIDINVALID);
  456. }
  457. UA_Session_init(&anonymousSession);
  458. anonymousSession.sessionId = UA_NODEID_GUID(0, UA_GUID_NULL);
  459. anonymousSession.header.channel = channel;
  460. session = &anonymousSession;
  461. }
  462. /* Trying to use a non-activated session? */
  463. if(sessionRequired && !session->activated) {
  464. UA_LOG_WARNING_SESSION(server->config.logger, session,
  465. "Calling service %i on a non-activated session",
  466. requestType->binaryEncodingId);
  467. UA_SessionManager_removeSession(&server->sessionManager,
  468. &session->header.authenticationToken);
  469. UA_deleteMembers(request, requestType);
  470. return sendServiceFault(channel, msg, requestPos, responseType,
  471. requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  472. }
  473. /* The session is bound to another channel */
  474. if(session != &anonymousSession && session->header.channel != channel) {
  475. UA_LOG_WARNING_CHANNEL(server->config.logger, channel,
  476. "Client tries to use a Session that is not "
  477. "bound to this SecureChannel");
  478. UA_deleteMembers(request, requestType);
  479. return sendServiceFault(channel, msg, requestPos, responseType,
  480. requestId, UA_STATUSCODE_BADSESSIONNOTACTIVATED);
  481. }
  482. /* Update the session lifetime */
  483. UA_Session_updateLifetime(session);
  484. #ifdef UA_ENABLE_SUBSCRIPTIONS
  485. /* The publish request is not answered immediately */
  486. if(requestType == &UA_TYPES[UA_TYPES_PUBLISHREQUEST]) {
  487. Service_Publish(server, session,
  488. (const UA_PublishRequest*)request, requestId);
  489. UA_deleteMembers(request, requestType);
  490. return UA_STATUSCODE_GOOD;
  491. }
  492. #endif
  493. send_response:
  494. /* Prepare the ResponseHeader */
  495. ((UA_ResponseHeader*)response)->requestHandle = requestHeader->requestHandle;
  496. ((UA_ResponseHeader*)response)->timestamp = UA_DateTime_now();
  497. /* Start the message */
  498. UA_NodeId typeId = UA_NODEID_NUMERIC(0, responseType->binaryEncodingId);
  499. UA_MessageContext mc;
  500. retval = UA_MessageContext_begin(&mc, channel, requestId, UA_MESSAGETYPE_MSG);
  501. if(retval != UA_STATUSCODE_GOOD)
  502. goto cleanup;
  503. /* Assert's required for clang-analyzer */
  504. UA_assert(mc.buf_pos == &mc.messageBuffer.data[UA_SECURE_MESSAGE_HEADER_LENGTH]);
  505. UA_assert(mc.buf_end <= &mc.messageBuffer.data[mc.messageBuffer.length]);
  506. retval = UA_MessageContext_encode(&mc, &typeId, &UA_TYPES[UA_TYPES_NODEID]);
  507. if(retval != UA_STATUSCODE_GOOD)
  508. goto cleanup;
  509. switch(serviceType) {
  510. case UA_SERVICETYPE_CUSTOM:
  511. /* Was processed before...*/
  512. retval = UA_MessageContext_encode(&mc, response, responseType);
  513. break;
  514. case UA_SERVICETYPE_INSITU:
  515. retval = ((UA_InSituService)service)
  516. (server, session, &mc, request, (UA_ResponseHeader*)response);
  517. break;
  518. case UA_SERVICETYPE_NORMAL:
  519. default:
  520. service(server, session, request, response);
  521. retval = UA_MessageContext_encode(&mc, response, responseType);
  522. break;
  523. }
  524. /* Finish sending the message */
  525. if(retval != UA_STATUSCODE_GOOD) {
  526. UA_MessageContext_abort(&mc);
  527. goto cleanup;
  528. }
  529. retval = UA_MessageContext_finish(&mc);
  530. cleanup:
  531. if(retval != UA_STATUSCODE_GOOD)
  532. UA_LOG_INFO_CHANNEL(server->config.logger, channel,
  533. "Could not send the message over the SecureChannel "
  534. "with StatusCode %s", UA_StatusCode_name(retval));
  535. /* Clean up */
  536. UA_deleteMembers(request, requestType);
  537. UA_deleteMembers(response, responseType);
  538. return retval;
  539. }
  540. /* Takes decoded messages starting at the nodeid of the content type. */
  541. static UA_StatusCode
  542. processSecureChannelMessage(void *application, UA_SecureChannel *channel,
  543. UA_MessageType messagetype, UA_UInt32 requestId,
  544. const UA_ByteString *message) {
  545. UA_Server *server = (UA_Server*)application;
  546. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  547. switch(messagetype) {
  548. case UA_MESSAGETYPE_OPN:
  549. UA_LOG_TRACE_CHANNEL(server->config.logger, channel,
  550. "Process an OPN on an open channel");
  551. retval = processOPN(server, channel, requestId, message);
  552. break;
  553. case UA_MESSAGETYPE_MSG:
  554. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Process a MSG");
  555. retval = processMSG(server, channel, requestId, message);
  556. break;
  557. case UA_MESSAGETYPE_CLO:
  558. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Process a CLO");
  559. Service_CloseSecureChannel(server, channel);
  560. break;
  561. default:
  562. UA_LOG_TRACE_CHANNEL(server->config.logger, channel, "Invalid message type");
  563. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  564. break;
  565. }
  566. return retval;
  567. }
  568. static UA_StatusCode
  569. createSecureChannel(void *application, UA_Connection *connection,
  570. UA_AsymmetricAlgorithmSecurityHeader *asymHeader) {
  571. UA_Server *server = (UA_Server*)application;
  572. /* Iterate over available endpoints and choose the correct one */
  573. UA_Endpoint *endpoint = NULL;
  574. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  575. for(size_t i = 0; i < server->config.endpointsSize; ++i) {
  576. UA_Endpoint *endpointCandidate = &server->config.endpoints[i];
  577. if(!UA_ByteString_equal(&asymHeader->securityPolicyUri,
  578. &endpointCandidate->securityPolicy.policyUri))
  579. continue;
  580. retval = endpointCandidate->securityPolicy.asymmetricModule.
  581. compareCertificateThumbprint(&endpointCandidate->securityPolicy,
  582. &asymHeader->receiverCertificateThumbprint);
  583. if(retval != UA_STATUSCODE_GOOD)
  584. continue;
  585. /* We found the correct endpoint (except for security mode) The endpoint
  586. * needs to be changed by the client / server to match the security
  587. * mode. The server does this in the securechannel manager */
  588. endpoint = endpointCandidate;
  589. break;
  590. }
  591. if(!endpoint)
  592. return UA_STATUSCODE_BADSECURITYPOLICYREJECTED;
  593. /* Create a new channel */
  594. return UA_SecureChannelManager_create(&server->secureChannelManager, connection,
  595. &endpoint->securityPolicy, asymHeader);
  596. }
  597. static UA_StatusCode
  598. processCompleteChunkWithoutChannel(UA_Server *server, UA_Connection *connection,
  599. UA_ByteString *message) {
  600. /* Process chunk without a channel; must be OPN */
  601. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  602. "Connection %i | No channel attached to the connection. "
  603. "Process the chunk directly", connection->sockfd);
  604. size_t offset = 0;
  605. UA_TcpMessageHeader tcpMessageHeader;
  606. UA_StatusCode retval =
  607. UA_TcpMessageHeader_decodeBinary(message, &offset, &tcpMessageHeader);
  608. if(retval != UA_STATUSCODE_GOOD)
  609. return retval;
  610. // Only HEL and OPN messages possible without a channel (on the server side)
  611. switch(tcpMessageHeader.messageTypeAndChunkType & 0x00ffffff) {
  612. case UA_MESSAGETYPE_HEL:
  613. retval = processHEL(server, connection, message, &offset);
  614. break;
  615. case UA_MESSAGETYPE_OPN:
  616. {
  617. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  618. "Connection %i | Process OPN message", connection->sockfd);
  619. /* Called before HEL */
  620. if(connection->state != UA_CONNECTION_ESTABLISHED) {
  621. retval = UA_STATUSCODE_BADCOMMUNICATIONERROR;
  622. break;
  623. }
  624. // Decode the asymmetric algorithm security header since it is not encrypted and
  625. // needed to decide what security policy to use.
  626. UA_AsymmetricAlgorithmSecurityHeader asymHeader;
  627. UA_AsymmetricAlgorithmSecurityHeader_init(&asymHeader);
  628. size_t messageHeaderOffset = UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH;
  629. retval = UA_AsymmetricAlgorithmSecurityHeader_decodeBinary(message,
  630. &messageHeaderOffset,
  631. &asymHeader);
  632. if(retval != UA_STATUSCODE_GOOD)
  633. break;
  634. retval = createSecureChannel(server, connection, &asymHeader);
  635. UA_AsymmetricAlgorithmSecurityHeader_deleteMembers(&asymHeader);
  636. if(retval != UA_STATUSCODE_GOOD)
  637. break;
  638. retval = UA_SecureChannel_processChunk(connection->channel, message,
  639. processSecureChannelMessage,
  640. server);
  641. if(retval != UA_STATUSCODE_GOOD)
  642. break;
  643. break;
  644. }
  645. default:
  646. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  647. "Connection %i | Expected OPN or HEL message on a connection "
  648. "without a SecureChannel", connection->sockfd);
  649. retval = UA_STATUSCODE_BADTCPMESSAGETYPEINVALID;
  650. break;
  651. }
  652. return retval;
  653. }
  654. static UA_StatusCode
  655. processCompleteChunk(void *const application,
  656. UA_Connection *const connection,
  657. UA_ByteString *const chunk) {
  658. UA_Server *const server = (UA_Server*)application;
  659. #ifdef UA_DEBUG_DUMP_PKGS_FILE
  660. UA_debug_dumpCompleteChunk(server, connection, chunk);
  661. #endif
  662. if(!connection->channel)
  663. return processCompleteChunkWithoutChannel(server, connection, chunk);
  664. return UA_SecureChannel_processChunk(connection->channel, chunk,
  665. processSecureChannelMessage,
  666. server);
  667. }
  668. static void
  669. processBinaryMessage(UA_Server *server, UA_Connection *connection,
  670. UA_ByteString *message) {
  671. UA_LOG_TRACE(server->config.logger, UA_LOGCATEGORY_NETWORK,
  672. "Connection %i | Received a packet.", connection->sockfd);
  673. #ifdef UA_DEBUG_DUMP_PKGS
  674. UA_dump_hex_pkg(message->data, message->length);
  675. #endif
  676. UA_StatusCode retval = UA_Connection_processChunks(connection, server,
  677. processCompleteChunk, message);
  678. if(retval != UA_STATUSCODE_GOOD) {
  679. UA_LOG_INFO(server->config.logger, UA_LOGCATEGORY_NETWORK,
  680. "Connection %i | Processing the message failed with "
  681. "error %s", connection->sockfd, UA_StatusCode_name(retval));
  682. /* Send an ERR message and close the connection */
  683. UA_TcpErrorMessage error;
  684. error.error = retval;
  685. error.reason = UA_STRING_NULL;
  686. UA_Connection_sendError(connection, &error);
  687. connection->close(connection);
  688. }
  689. }
  690. #ifndef UA_ENABLE_MULTITHREADING
  691. void
  692. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  693. UA_ByteString *message) {
  694. processBinaryMessage(server, connection, message);
  695. }
  696. #else
  697. typedef struct {
  698. UA_Connection *connection;
  699. UA_ByteString message;
  700. } ConnectionMessage;
  701. static void
  702. workerProcessBinaryMessage(UA_Server *server, ConnectionMessage *cm) {
  703. processBinaryMessage(server, cm->connection, &cm->message);
  704. UA_free(cm);
  705. }
  706. void
  707. UA_Server_processBinaryMessage(UA_Server *server, UA_Connection *connection,
  708. UA_ByteString *message) {
  709. /* Allocate the memory for the callback data */
  710. ConnectionMessage *cm = (ConnectionMessage*)UA_malloc(sizeof(ConnectionMessage));
  711. /* If malloc failed, execute immediately */
  712. if(!cm) {
  713. processBinaryMessage(server, connection, message);
  714. return;
  715. }
  716. /* Dispatch to the workers */
  717. cm->connection = connection;
  718. cm->message = *message;
  719. UA_Server_workerCallback(server, (UA_ServerCallback)workerProcessBinaryMessage, cm);
  720. }
  721. static void
  722. deleteConnectionTrampoline(UA_Server *server, void *data) {
  723. UA_Connection *connection = (UA_Connection*)data;
  724. connection->free(connection);
  725. }
  726. #endif
  727. void
  728. UA_Server_removeConnection(UA_Server *server, UA_Connection *connection) {
  729. UA_Connection_detachSecureChannel(connection);
  730. #ifndef UA_ENABLE_MULTITHREADING
  731. connection->free(connection);
  732. #else
  733. UA_Server_delayedCallback(server, deleteConnectionTrampoline, connection);
  734. #endif
  735. }