ua_securechannel.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2017 (c) Florian Palm
  7. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  8. * Copyright 2017 (c) Mark Giraud, Fraunhofer IOSB
  9. */
  10. #ifndef UA_SECURECHANNEL_H_
  11. #define UA_SECURECHANNEL_H_
  12. #ifdef __cplusplus
  13. extern "C" {
  14. #endif
  15. #include "ua_types.h"
  16. #include "ua_transport_generated.h"
  17. #include "ua_connection_internal.h"
  18. #include "ua_plugin_securitypolicy.h"
  19. #include "ua_plugin_log.h"
  20. #include "../deps/queue.h"
  21. #define UA_SECURE_CONVERSATION_MESSAGE_HEADER_LENGTH 12
  22. #define UA_SECURE_MESSAGE_HEADER_LENGTH 24
  23. /* Thread-local variables to force failure modes during testing */
  24. #ifdef UA_ENABLE_UNIT_TEST_FAILURE_HOOKS
  25. extern UA_StatusCode decrypt_verifySignatureFailure;
  26. extern UA_StatusCode sendAsym_sendFailure;
  27. extern UA_StatusCode processSym_seqNumberFailure;
  28. #endif
  29. /* The Session implementation differs between client and server. Still, it is
  30. * expected that the Session structure begins with the SessionHeader. This is
  31. * the interface that will be used by the SecureChannel. The lifecycle of
  32. * Sessions is independent of the underlying SecureChannel. But every Session
  33. * can be attached to only one SecureChannel. */
  34. typedef struct UA_SessionHeader {
  35. LIST_ENTRY(UA_SessionHeader) pointers;
  36. UA_NodeId authenticationToken;
  37. UA_SecureChannel *channel; /* The pointer back to the SecureChannel in the session. */
  38. } UA_SessionHeader;
  39. /* For chunked requests */
  40. typedef struct UA_ChunkPayload {
  41. SIMPLEQ_ENTRY(UA_ChunkPayload) pointers;
  42. UA_ByteString bytes;
  43. UA_Boolean copied; /* Do the bytes point to a buffer from the network or was
  44. memory allocated for the chunk separately */
  45. } UA_ChunkPayload;
  46. /* Receieved messages. Process them only in order. The Chunk payload has all
  47. * headers and the padding stripped out. The payload begins at the
  48. * ExtensionObject prefix.*/
  49. typedef struct UA_Message {
  50. TAILQ_ENTRY(UA_Message) pointers;
  51. UA_UInt32 requestId;
  52. UA_MessageType messageType;
  53. SIMPLEQ_HEAD(pp, UA_ChunkPayload) chunkPayloads;
  54. size_t chunkPayloadsSize; /* No of chunks received so far */
  55. size_t messageSize; /* Total length of the chunks received so far */
  56. UA_Boolean final; /* All chunks for the message have been received */
  57. } UA_Message;
  58. typedef enum {
  59. UA_SECURECHANNELSTATE_FRESH,
  60. UA_SECURECHANNELSTATE_OPEN,
  61. UA_SECURECHANNELSTATE_CLOSED
  62. } UA_SecureChannelState;
  63. typedef TAILQ_HEAD(UA_MessageQueue, UA_Message) UA_MessageQueue;
  64. struct UA_SecureChannel {
  65. UA_SecureChannelState state;
  66. UA_MessageSecurityMode securityMode;
  67. UA_ChannelSecurityToken securityToken; /* the channelId is contained in the securityToken */
  68. UA_ChannelSecurityToken nextSecurityToken;
  69. /* The endpoint and context of the channel */
  70. const UA_SecurityPolicy *securityPolicy;
  71. void *channelContext; /* For interaction with the security policy */
  72. UA_Connection *connection;
  73. /* Asymmetric encryption info */
  74. UA_ByteString remoteCertificate;
  75. UA_Byte remoteCertificateThumbprint[20]; /* The thumbprint of the remote certificate */
  76. /* Symmetric encryption info */
  77. UA_ByteString remoteNonce;
  78. UA_ByteString localNonce;
  79. UA_UInt32 receiveSequenceNumber;
  80. UA_UInt32 sendSequenceNumber;
  81. LIST_HEAD(, UA_SessionHeader) sessions;
  82. UA_MessageQueue messages;
  83. };
  84. void UA_SecureChannel_init(UA_SecureChannel *channel);
  85. UA_StatusCode
  86. UA_SecureChannel_setSecurityPolicy(UA_SecureChannel *channel,
  87. const UA_SecurityPolicy *securityPolicy,
  88. const UA_ByteString *remoteCertificate);
  89. /* Remove (partially) received unprocessed messages */
  90. void UA_SecureChannel_deleteMessages(UA_SecureChannel *channel);
  91. void UA_SecureChannel_deleteMembersCleanup(UA_SecureChannel *channel);
  92. /* Generates new keys and sets them in the channel context */
  93. UA_StatusCode
  94. UA_SecureChannel_generateNewKeys(UA_SecureChannel* channel);
  95. /* Wrapper function for generating a local nonce for the supplied channel. Uses
  96. * the random generator of the channels security policy to allocate and generate
  97. * a nonce with the specified length. */
  98. UA_StatusCode
  99. UA_SecureChannel_generateLocalNonce(UA_SecureChannel *channel);
  100. UA_SessionHeader *
  101. UA_SecureChannel_getSession(UA_SecureChannel *channel,
  102. const UA_NodeId *authenticationToken);
  103. UA_StatusCode
  104. UA_SecureChannel_revolveTokens(UA_SecureChannel *channel);
  105. /**
  106. * Sending Messages
  107. * ---------------- */
  108. UA_StatusCode
  109. UA_SecureChannel_sendAsymmetricOPNMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  110. const void *content, const UA_DataType *contentType);
  111. UA_StatusCode
  112. UA_SecureChannel_sendSymmetricMessage(UA_SecureChannel *channel, UA_UInt32 requestId,
  113. UA_MessageType messageType, void *payload,
  114. const UA_DataType *payloadType);
  115. /* The MessageContext is forwarded into the encoding layer so that we can send
  116. * chunks before continuing to encode. This lets us reuse a fixed chunk-sized
  117. * messages buffer. */
  118. typedef struct {
  119. UA_SecureChannel *channel;
  120. UA_UInt32 requestId;
  121. UA_UInt32 messageType;
  122. UA_UInt16 chunksSoFar;
  123. size_t messageSizeSoFar;
  124. UA_ByteString messageBuffer;
  125. UA_Byte *buf_pos;
  126. const UA_Byte *buf_end;
  127. UA_Boolean final;
  128. } UA_MessageContext;
  129. /* Start the context of a new symmetric message. */
  130. UA_StatusCode
  131. UA_MessageContext_begin(UA_MessageContext *mc, UA_SecureChannel *channel,
  132. UA_UInt32 requestId, UA_MessageType messageType);
  133. /* Encode the content and send out full chunks. If the return code is good, then
  134. * the ChunkInfo contains encoded content that has not been sent. If the return
  135. * code is bad, then the ChunkInfo has been cleaned up internally. */
  136. UA_StatusCode
  137. UA_MessageContext_encode(UA_MessageContext *mc, const void *content,
  138. const UA_DataType *contentType);
  139. /* Sends a symmetric message already encoded in the context. The context is
  140. * cleaned up, also in case of errors. */
  141. UA_StatusCode
  142. UA_MessageContext_finish(UA_MessageContext *mc);
  143. /* To be used when a failure occures when a MessageContext is open. Note that
  144. * the _encode and _finish methods will clean up internally. _abort can be run
  145. * on a MessageContext that has already been cleaned up before. */
  146. void
  147. UA_MessageContext_abort(UA_MessageContext *mc);
  148. /**
  149. * Receive Message
  150. * --------------- */
  151. /* Decrypt a chunk and add it to the message. Create a new message if necessary. */
  152. UA_StatusCode
  153. UA_SecureChannel_decryptAddChunk(UA_SecureChannel *channel, const UA_ByteString *chunk);
  154. /* The network buffer is about to be cleared. Copy all chunks that point into
  155. * the network buffer into dedicated memory. */
  156. UA_StatusCode
  157. UA_SecureChannel_persistIncompleteMessages(UA_SecureChannel *channel);
  158. typedef void
  159. (UA_ProcessMessageCallback)(void *application, UA_SecureChannel *channel,
  160. UA_MessageType messageType, UA_UInt32 requestId,
  161. const UA_ByteString *message);
  162. /* Process received complete messages in-order. The callback function is called
  163. * with the complete message body if the message is complete. The message is
  164. * removed afterwards.
  165. *
  166. * Symmetric callback is ERR, MSG, CLO only
  167. * Asymmetric callback is OPN only
  168. *
  169. * @param channel the channel the chunks were received on.
  170. * @param application data pointer to application specific data that gets passed
  171. * on to the callback function.
  172. * @param callback the callback function that gets called with the complete
  173. * message body, once a final chunk is processed.
  174. * @return Returns if an irrecoverable error occured. Maybe close the channel. */
  175. UA_StatusCode
  176. UA_SecureChannel_processCompleteMessages(UA_SecureChannel *channel, void *application,
  177. UA_ProcessMessageCallback callback);
  178. /**
  179. * Log Helper
  180. * ----------
  181. * C99 requires at least one element for the variadic argument. If the log
  182. * statement has no variable arguments, supply an additional NULL. It will be
  183. * ignored by printf.
  184. *
  185. * We have to jump through some hoops to enable the use of format strings
  186. * without arguments since (pedantic) C99 does not allow variadic macros with
  187. * zero arguments. So we add a dummy argument that is not printed (%.0s is
  188. * string of length zero). */
  189. #define UA_LOG_TRACE_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  190. UA_LOG_TRACE(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  191. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  192. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  193. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  194. #define UA_LOG_TRACE_CHANNEL(LOGGER, CHANNEL, ...) \
  195. UA_MACRO_EXPAND(UA_LOG_TRACE_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  196. #define UA_LOG_DEBUG_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  197. UA_LOG_DEBUG(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  198. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  199. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  200. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  201. #define UA_LOG_DEBUG_CHANNEL(LOGGER, CHANNEL, ...) \
  202. UA_MACRO_EXPAND(UA_LOG_DEBUG_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  203. #define UA_LOG_INFO_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  204. UA_LOG_INFO(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  205. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  206. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  207. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  208. #define UA_LOG_INFO_CHANNEL(LOGGER, CHANNEL, ...) \
  209. UA_MACRO_EXPAND(UA_LOG_INFO_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  210. #define UA_LOG_WARNING_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  211. UA_LOG_WARNING(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  212. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  213. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  214. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  215. #define UA_LOG_WARNING_CHANNEL(LOGGER, CHANNEL, ...) \
  216. UA_MACRO_EXPAND(UA_LOG_WARNING_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  217. #define UA_LOG_ERROR_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  218. UA_LOG_ERROR(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  219. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  220. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  221. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  222. #define UA_LOG_ERROR_CHANNEL(LOGGER, CHANNEL, ...) \
  223. UA_MACRO_EXPAND(UA_LOG_ERROR_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  224. #define UA_LOG_FATAL_CHANNEL_INTERNAL(LOGGER, CHANNEL, MSG, ...) \
  225. UA_LOG_FATAL(LOGGER, UA_LOGCATEGORY_SECURECHANNEL, \
  226. "Connection %i | SecureChannel %i | " MSG "%.0s", \
  227. ((CHANNEL)->connection ? (CHANNEL)->connection->sockfd : 0), \
  228. (CHANNEL)->securityToken.channelId, __VA_ARGS__)
  229. #define UA_LOG_FATAL_CHANNEL(LOGGER, CHANNEL, ...) \
  230. UA_MACRO_EXPAND(UA_LOG_FATAL_CHANNEL_INTERNAL(LOGGER, CHANNEL, __VA_ARGS__, ""))
  231. #ifdef __cplusplus
  232. } // extern "C"
  233. #endif
  234. #endif /* UA_SECURECHANNEL_H_ */