tsig.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef __TSIG_H
  15. #define __TSIG_H 1
  16. #include <boost/noncopyable.hpp>
  17. #include <exceptions/exceptions.h>
  18. #include <dns/tsigerror.h>
  19. #include <dns/tsigkey.h>
  20. #include <dns/tsigrecord.h>
  21. namespace isc {
  22. namespace dns {
  23. /// An exception that is thrown for logic errors identified in TSIG
  24. /// sign/verify operations.
  25. ///
  26. /// Note that this exception is not thrown for TSIG protocol errors such as
  27. /// verification failures. In general, this exception indicates an internal
  28. /// program bug.
  29. class TSIGContextError : public isc::Exception {
  30. public:
  31. TSIGContextError(const char* file, size_t line, const char* what) :
  32. isc::Exception(file, line, what) {}
  33. };
  34. /// TSIG session context.
  35. ///
  36. /// The \c TSIGContext class maintains a context of a signed session of
  37. /// DNS transactions by TSIG. In many cases a TSIG signed session consists
  38. /// of a single set of request (e.g. normal query) and reply (e.g. normal
  39. /// response), where the request is initially signed by the client, and the
  40. /// reply is signed by the server using the initial signature. As mentioned
  41. /// in RFC2845, a session can consist of multiple exchanges in a TCP
  42. /// connection. As also mentioned in the RFC, an AXFR response often contains
  43. /// multiple DNS messages, which can belong to the same TSIG session.
  44. /// This class supports all these cases.
  45. ///
  46. /// A \c TSIGContext object is generally constructed with a TSIG key to be
  47. /// used for the session, and keeps track of various kinds of session specific
  48. /// information, such as the original digest while waiting for a response or
  49. /// verification error information that is to be used for a subsequent
  50. /// response.
  51. ///
  52. /// This class has two main methods, \c sign() and \c verify().
  53. /// The \c sign() method signs given data (which is supposed to be a complete
  54. /// DNS message without the TSIG itself) using the TSIG key and other
  55. /// related information associated with the \c TSIGContext object.
  56. /// The \c verify() method verifies a given DNS message that contains a TSIG
  57. /// RR using the key and other internal information.
  58. ///
  59. /// In general, a DNS client that wants to send a signed query will construct
  60. /// a \c TSIGContext object with the TSIG key that the client is intending to
  61. /// use, and sign the query with the context. The client will keeps the
  62. /// context, and verify the response with it.
  63. ///
  64. /// On the other hand, a DNS server will construct a \c TSIGContext object
  65. /// with the information of the TSIG RR included in a query with a set of
  66. /// possible keys (in the form of a \c TSIGKeyRing object). The constructor
  67. /// in this mode will identify the appropriate TSIG key (or internally record
  68. /// an error if it doesn't find a key). The server will then verify the
  69. /// query with the context, and generate a signed response using the same
  70. /// same context.
  71. ///
  72. /// When multiple messages belong to the same TSIG session, either side
  73. /// (signer or verifier) will keep using the same context. It records
  74. /// the latest session state (such as the previous digest) so that repeated
  75. /// calls to \c sign() or \c verify() work correctly in terms of the TSIG
  76. /// protocol.
  77. ///
  78. /// \b Examples
  79. ///
  80. /// This is a typical client application that sends a TSIG signed query
  81. /// and verifies the response.
  82. ///
  83. /// \code
  84. /// // "renderer" is of MessageRenderer to render the message.
  85. /// Message message(Message::RENDER);
  86. /// message.addQuestion(Question(Name("www.example.com"), RRClass::IN(),
  87. /// RRType::A()));
  88. /// message.toWire(renderer, ctx);
  89. ///
  90. /// // sendto, then recvfrom. received result in (data, data_len)
  91. ///
  92. /// message.clear(Message::PARSE);
  93. /// InputBuffer buffer(data, data_len);
  94. /// message.fromWire(buffer);
  95. /// TSIGError tsig_error = ctx.verify(message.getTSIGRecord(),
  96. /// data, data_len);
  97. /// if (tsig_error == TSIGError::NOERROR()) {
  98. /// // okay. ctx can be continuously used if it's receiving subsequent
  99. /// // signed responses from a TCP stream.
  100. /// } else if (message.getRcode() == Rcode::NOTAUTH()) {
  101. /// // hard error. give up this transaction per RFC2845 4.6.
  102. /// } else {
  103. /// // keep waiting for further response with the same ctx.
  104. /// } \endcode
  105. ///
  106. /// And this is a typical server application that authenticates a signed
  107. /// query and returns a response according to the result.
  108. ///
  109. /// \code
  110. /// // Assume "message" is of type Message for query handling and
  111. /// // "renderer" is of MessageRenderer to render responses.
  112. /// Message message(Message::RENDER);
  113. ///
  114. /// TSIGKeyRing keyring; // this must be configured with keys somewhere
  115. ///
  116. /// // Receive a query and store it in (data, data_len)
  117. /// InputBuffer buffer(data, data_len);
  118. /// message.clear(Message::PARSE);
  119. /// message.fromWire(buffer);
  120. ///
  121. /// const TSIGRecord* tsig = message.getTSIGRecord();
  122. /// if (tsig != NULL) {
  123. /// TSIGContext ctx(tsig->getName(), tsig->getRdata().getAlgorithm(),
  124. /// keyring);
  125. /// ctx.verify(tsig, data, data_len);
  126. ///
  127. /// // prepare response
  128. /// message.makeResponse();
  129. /// //...
  130. /// message.toWire(renderer, ctx);
  131. ///
  132. /// // send the response data back to the client.
  133. /// // If this is a beginning of a signed session over a TCP and
  134. /// // server has more data to send to the client, this ctx
  135. /// // will be used to sign subsequent messages.
  136. /// } \endcode
  137. ///
  138. /// <b>TCP Consideration</b>
  139. ///
  140. /// RFC2845 describes the case where a single TSIG session is used for
  141. /// multiple DNS messages (Section 4.4). This class supports signing and
  142. /// verifying the messages in this scenario, but does not care if the messages
  143. /// were delivered over a TCP connection or not. If, for example, the
  144. /// same \c TSIGContext object is used to sign two independent DNS queries
  145. /// sent over UDP, they will be considered to belong to the same TSIG
  146. /// session, and, as a result, verification will be likely to fail.
  147. ///
  148. /// \b Copyability
  149. ///
  150. /// This class is currently non copyable based on the observation of the
  151. /// typical usage as described above. But there is no strong technical
  152. /// reason why this class cannot be copyable. If we see the need for it
  153. /// in future we may change the implementation on this point.
  154. ///
  155. /// <b>Note to developers:</b>
  156. /// One basic design choice is to make the \c TSIGContext class is as
  157. /// independent from the \c Message class. This is because the latter is
  158. /// much more complicated, depending on many other classes, while TSIG is
  159. /// a very specific part of the entire DNS protocol set. If the \c TSIGContext
  160. /// class depends on \c \c Message, it will be more vulnerable to changes
  161. /// to other classes, and will be more difficult to test due to the
  162. /// direct or indirect dependencies. The interface of \c sign() that takes
  163. /// opaque data (instead of, e.g., a \c Message or \c MessageRenderer object)
  164. /// is therefore a deliberate design decision.
  165. class TSIGContext : boost::noncopyable {
  166. public:
  167. /// Internal state of context
  168. ///
  169. /// The constants of this enum type define a specific state of
  170. /// \c TSIGContext to adjust the behavior. The definition is public
  171. /// and the state can be seen via the \c getState() method, but this is
  172. /// mostly private information. It's publicly visible mainly for testing
  173. /// purposes; there is no API for the application to change the state
  174. /// directly.
  175. enum State {
  176. INIT, ///< Initial state
  177. SENT_REQUEST, ///< Client sent a signed request, waiting response
  178. RECEIVED_REQUEST, ///< Server received a signed request
  179. SENT_RESPONSE, ///< Server sent a signed response
  180. VERIFIED_RESPONSE ///< Client successfully verified a response
  181. };
  182. /// \name Constructors and destructor
  183. ///
  184. //@{
  185. /// Constructor from a TSIG key.
  186. ///
  187. /// \exception std::bad_alloc Resource allocation for internal data fails
  188. ///
  189. /// \param key The TSIG key to be used for TSIG sessions with this context.
  190. explicit TSIGContext(const TSIGKey& key);
  191. /// Constructor from key parameters and key ring.
  192. TSIGContext(const Name& key_name, const Name& algorithm_name,
  193. const TSIGKeyRing& keyring);
  194. /// The destructor.
  195. ~TSIGContext();
  196. //@}
  197. /// Sign a DNS message.
  198. ///
  199. /// This method computes the TSIG MAC for the given data, which is
  200. /// generally expected to be a complete, wire-format DNS message
  201. /// that doesn't contain a TSIG RR, based on the TSIG key and
  202. /// other context information of \c TSIGContext, and returns a
  203. /// result in the form of a (pointer object pointing to)
  204. /// \c TSIGRecord object.
  205. ///
  206. /// The caller of this method will use the returned value to render a
  207. /// complete TSIG RR into the message that has been signed so that it
  208. /// will become a complete TSIG-signed message.
  209. ///
  210. /// In general, this method is called once by a client to send a
  211. /// signed request or one more times by a server to sign
  212. /// response(s) to a signed request. To avoid allowing accidental
  213. /// misuse, if this method is called after a "client" validates a
  214. /// response, an exception of class \c TSIGContextError will be
  215. /// thrown.
  216. ///
  217. /// \note Normal applications are not expected to call this method
  218. /// directly; they will usually use the \c Message::toWire() method
  219. /// with a \c TSIGContext object being a parameter and have the
  220. /// \c Message class create a complete signed message.
  221. ///
  222. /// This method treats the given data as opaque, even though it's generally
  223. /// expected to represent a wire-format DNS message (see also the class
  224. /// description), and doesn't inspect it in any way. For example, it
  225. /// doesn't check whether the data length is sane for a valid DNS message.
  226. /// This is also the reason why this method takes the \c qid parameter,
  227. /// which will be used as the original ID of the resulting
  228. /// \c TSIGRecordx object, even though this value should be stored in the
  229. /// first two octets (in wire format) of the given data.
  230. ///
  231. /// \note This method still checks and rejects empty data (\c NULL pointer
  232. /// data or the specified data length is 0) in order to avoid catastrophic
  233. /// effect such as program crash. Empty data is not necessarily invalid
  234. /// for HMAC computation, but obviously it doesn't make sense for a DNS
  235. /// message.
  236. ///
  237. /// This method provides the strong exception guarantee; unless the method
  238. /// returns (without an exception being thrown), the internal state of
  239. /// the \c TSIGContext won't be modified.
  240. ///
  241. /// \exception TSIGContextError Context already verified a response.
  242. /// \exception InvalidParameter \c data is NULL or \c data_len is 0
  243. /// \exception cryptolink::LibraryError Some unexpected error in the
  244. /// underlying crypto operation
  245. /// \exception std::bad_alloc Temporary resource allocation failure
  246. ///
  247. /// \param qid The QID to be as the value of the original ID field of
  248. /// the resulting TSIG record
  249. /// \param data Points to the wire-format data to be signed
  250. /// \param data_len The length of \c data in bytes
  251. ///
  252. /// \return A TSIG record for the given data along with the context.
  253. ConstTSIGRecordPtr sign(const uint16_t qid, const void* const data,
  254. const size_t data_len);
  255. /// Verify a DNS message.
  256. ///
  257. /// This method verifies given data along with the context and a given
  258. /// TSIG in the form of a \c TSIGRecord object. The data to be verified
  259. /// is generally expected to be a complete, wire-format DNS message,
  260. /// exactly as received by the host, and ending with a TSIG RR.
  261. /// After verification process this method updates its internal state,
  262. /// and returns the result in the form of a \c TSIGError object.
  263. /// Possible return values are (see the \c TSIGError class description
  264. /// for the mnemonics):
  265. ///
  266. /// - \c NOERROR: The data has been verified correctly.
  267. /// - \c FORMERR: \c TSIGRecord is not given (see below).
  268. /// - \c BAD_KEY: Appropriate key is not found or specified key doesn't
  269. /// match for the data.
  270. /// - \c BAD_TIME: The current time doesn't fall in the range specified
  271. /// in the TSIG.
  272. /// - \c BAD_SIG: The signature given in the TSIG doesn't match against
  273. /// the locally computed digest or is the signature is
  274. /// invalid in other way.
  275. ///
  276. /// If this method is called by a DNS client waiting for a signed
  277. /// response and the result is not \c NOERROR, the context can be used
  278. /// to try validating another signed message as described in RFC2845
  279. /// Section 4.6.
  280. ///
  281. /// If this method is called by a DNS server that tries to authenticate
  282. /// a signed request, and if the result is not \c NOERROR, the
  283. /// corresponding error condition is recorded in the context so that
  284. /// the server can return a response indicating what was wrong by calling
  285. /// \c sign() with the updated context.
  286. ///
  287. /// In general, this method is called once by a server for
  288. /// authenticating a signed request or one more times by a client to
  289. /// validate signed response(s) to a signed request. To avoid allowing
  290. /// accidental misuse, if this method is called after a "server" signs
  291. /// a response, an exception of class \c TSIGContextError will be thrown.
  292. ///
  293. /// The \c record parameter can be NULL; in that case this method simply
  294. /// returns \c FORMERR as the case described in Section 4.6 of RFC2845,
  295. /// i.e., receiving an unsigned response to a signed request. This way
  296. /// a client can transparently pass the result of
  297. /// \c Message::getTSIGRecord() without checking whether it's non NULL
  298. /// and take an appropriate action based on the result of this method.
  299. ///
  300. /// This method handles the given data mostly as opaque. It digests
  301. /// the data assuming it begins with a DNS header and ends with a TSIG
  302. /// RR whose length is given by calling \c TSIGRecord::getLength() on
  303. /// \c record, but otherwise it doesn't parse the data to confirm the
  304. /// assumption. It's caller's responsibility to ensure the data is
  305. /// valid and consistent with \c record. To avoid disruption, this
  306. /// method performs minimal validation on the given \c data and \c record:
  307. /// \c data must not be NULL; \c data_len must not be smaller than the
  308. /// sum of the DNS header length (fixed, 12 octets) and the length of
  309. /// the TSIG RR. If this check fails it throws an \c InvalidParameter
  310. /// exception.
  311. ///
  312. /// One unexpected case that is not covered by this method is that a
  313. /// client receives a signed response to an unsigned request. RFC2845 is
  314. /// silent about such cases; BIND 9 explicitly identifies the case and
  315. /// reject it. With this implementation, the client can know that the
  316. /// response contains a TSIG via the result of
  317. /// \c Message::getTSIGRecord() and that it is an unexpected TSIG due to
  318. /// the fact that it doesn't have a corresponding \c TSIGContext.
  319. /// It's up to the client implementation whether to react to such a case
  320. /// explicitly (for example, it could either ignore the TSIG and accept
  321. /// the response or drop it).
  322. ///
  323. /// This method provides the strong exception guarantee; unless the method
  324. /// returns (without an exception being thrown), the internal state of
  325. /// the \c TSIGContext won't be modified.
  326. ///
  327. /// \todo Support intermediate TCP DNS messages without TSIG (RFC2845 4.4)
  328. /// \todo Signature truncation support based on RFC4635
  329. ///
  330. /// \exception TSIGContextError Context already signed a response.
  331. /// \exception InvalidParameter \c data is NULL or \c data_len is too small.
  332. ///
  333. /// \param record The \c TSIGRecord to be verified with \c data
  334. /// \param data Points to the wire-format data (exactly as received) to
  335. /// be verified
  336. /// \param data_len The length of \c data in bytes
  337. /// \return The \c TSIGError that indicates verification result
  338. TSIGError verify(const TSIGRecord* const record, const void* const data,
  339. const size_t data_len);
  340. /// Return the current state of the context
  341. ///
  342. /// \note
  343. /// The states are visible in public mainly for testing purposes.
  344. /// Normal applications won't have to deal with them.
  345. ///
  346. /// \exception None
  347. State getState() const;
  348. /// Return the TSIG error as a result of the latest verification
  349. ///
  350. /// This method can be called even before verifying anything, but the
  351. /// returned value is meaningless in that case.
  352. ///
  353. /// \exception None
  354. TSIGError getError() const;
  355. /// \name Protocol constants and defaults
  356. ///
  357. //@{
  358. /// The recommended fudge value (in seconds) by RFC2845.
  359. ///
  360. /// Right now fudge is not tunable, and all TSIGs generated by this API
  361. /// will have this value of fudge.
  362. static const uint16_t DEFAULT_FUDGE = 300;
  363. //@}
  364. private:
  365. struct TSIGContextImpl;
  366. TSIGContextImpl* impl_;
  367. };
  368. }
  369. }
  370. #endif // __TSIG_H
  371. // Local Variables:
  372. // mode: c++
  373. // End: