tsig_250.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // Copyright (C) 2010 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. #include <string>
  15. #include <sstream>
  16. #include <vector>
  17. #include <boost/lexical_cast.hpp>
  18. #include <util/buffer.h>
  19. #include <util/encode/base64.h>
  20. #include <dns/messagerenderer.h>
  21. #include <dns/rdata.h>
  22. #include <dns/rdataclass.h>
  23. #include <dns/tsigerror.h>
  24. using namespace std;
  25. using namespace boost;
  26. using namespace isc::util;
  27. using namespace isc::util::encode;
  28. // BEGIN_ISC_NAMESPACE
  29. // BEGIN_RDATA_NAMESPACE
  30. /// This is a straightforward representation of TSIG RDATA fields.
  31. struct TSIG::TSIGImpl {
  32. TSIGImpl(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
  33. vector<uint8_t>& mac, uint16_t original_id, uint16_t error,
  34. vector<uint8_t>& other_data) :
  35. algorithm_(algorithm), time_signed_(time_signed), fudge_(fudge),
  36. mac_(mac), original_id_(original_id), error_(error),
  37. other_data_(other_data)
  38. {}
  39. TSIGImpl(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
  40. size_t macsize, const void* mac, uint16_t original_id,
  41. uint16_t error, size_t other_len, const void* other_data) :
  42. algorithm_(algorithm), time_signed_(time_signed), fudge_(fudge),
  43. mac_(static_cast<const uint8_t*>(mac),
  44. static_cast<const uint8_t*>(mac) + macsize),
  45. original_id_(original_id), error_(error),
  46. other_data_(static_cast<const uint8_t*>(other_data),
  47. static_cast<const uint8_t*>(other_data) + other_len)
  48. {}
  49. template <typename Output>
  50. void toWireCommon(Output& output) const;
  51. const Name algorithm_;
  52. const uint64_t time_signed_;
  53. const uint16_t fudge_;
  54. const vector<uint8_t> mac_;
  55. const uint16_t original_id_;
  56. const uint16_t error_;
  57. const vector<uint8_t> other_data_;
  58. };
  59. namespace {
  60. string
  61. getToken(istringstream& iss, const string& full_input) {
  62. string token;
  63. iss >> token;
  64. if (iss.bad() || iss.fail()) {
  65. isc_throw(InvalidRdataText, "Invalid TSIG text: parse error " <<
  66. full_input);
  67. }
  68. return (token);
  69. }
  70. // This helper function converts a string token to an *unsigned* integer.
  71. // NumType is a *signed* integral type (e.g. int32_t) that is sufficiently
  72. // wide to store resulting integers.
  73. // BitSize is the maximum number of bits that the resulting integer can take.
  74. // This function first checks whether the given token can be converted to
  75. // an integer of NumType type. It then confirms the conversion result is
  76. // within the valid range, i.e., [0, 2^NumType - 1]. The second check is
  77. // necessary because lexical_cast<T> where T is an unsigned integer type
  78. // doesn't correctly reject negative numbers when compiled with SunStudio.
  79. template <typename NumType, int BitSize>
  80. NumType
  81. tokenToNum(const string& num_token) {
  82. NumType num;
  83. try {
  84. num = lexical_cast<NumType>(num_token);
  85. } catch (const boost::bad_lexical_cast& ex) {
  86. isc_throw(InvalidRdataText, "Invalid TSIG numeric parameter: " <<
  87. num_token);
  88. }
  89. if (num < 0 || num >= (static_cast<NumType>(1) << BitSize)) {
  90. isc_throw(InvalidRdataText, "Numeric TSIG parameter out of range: " <<
  91. num);
  92. }
  93. return (num);
  94. }
  95. }
  96. /// \brief Constructor from string.
  97. ///
  98. /// \c tsig_str must be formatted as follows:
  99. /// \code <Alg> <Time> <Fudge> <MACsize> [<MAC>] <OrigID> <Error> <OtherLen> [<OtherData>]
  100. /// \endcode
  101. /// where
  102. /// - <Alg> is a valid textual representation of domain name.
  103. /// - <Time> is an unsigned 48-bit decimal integer.
  104. /// - <MACSize>, <OrigID>, and <OtherLen> are an unsigned 16-bit decimal
  105. /// integer.
  106. /// - <Error> is an unsigned 16-bit decimal integer or a valid mnemonic for
  107. /// the Error field specified in RFC2845. Currently, "BADSIG", "BADKEY",
  108. /// and "BADTIME" are supported (case sensitive). In future versions
  109. /// other representations that are compatible with the DNS RCODE will be
  110. /// supported.
  111. /// - <MAC> and <OtherData> is a BASE-64 encoded string that does not contain
  112. /// space characters.
  113. /// When <MACSize> and <OtherLen> is 0, <MAC> and <OtherData> must not
  114. /// appear in \c tsgi_str, respectively.
  115. /// - The decoded data of <MAC> is <MACSize> bytes of binary stream.
  116. /// - The decoded data of <OtherData> is <OtherLen> bytes of binary stream.
  117. ///
  118. /// An example of valid string is:
  119. /// \code "hmac-sha256. 853804800 300 3 AAAA 2845 0 0" \endcode
  120. /// In this example <OtherData> is missing because <OtherLen> is 0.
  121. ///
  122. /// Note that RFC2845 does not define the standard presentation format
  123. /// of %TSIG RR, so the above syntax is implementation specific.
  124. /// This is, however, compatible with the format acceptable to BIND 9's
  125. /// RDATA parser.
  126. ///
  127. /// <b>Exceptions</b>
  128. ///
  129. /// If <Alg> is not a valid domain name, a corresponding exception from
  130. /// the \c Name class will be thrown;
  131. /// if <MAC> or <OtherData> is not validly encoded in BASE-64, an exception
  132. /// of class \c isc::BadValue will be thrown;
  133. /// if %any of the other bullet points above is not met, an exception of
  134. /// class \c InvalidRdataText will be thrown.
  135. /// This constructor internally involves resource allocation, and if it fails
  136. /// a corresponding standard exception will be thrown.
  137. TSIG::TSIG(const std::string& tsig_str) : impl_(NULL) {
  138. istringstream iss(tsig_str);
  139. const Name algorithm(getToken(iss, tsig_str));
  140. const int64_t time_signed = tokenToNum<int64_t, 48>(getToken(iss,
  141. tsig_str));
  142. const int32_t fudge = tokenToNum<int32_t, 16>(getToken(iss, tsig_str));
  143. const int32_t macsize = tokenToNum<int32_t, 16>(getToken(iss, tsig_str));
  144. const string mac_txt = (macsize > 0) ? getToken(iss, tsig_str) : "";
  145. vector<uint8_t> mac;
  146. decodeBase64(mac_txt, mac);
  147. if (mac.size() != macsize) {
  148. isc_throw(InvalidRdataText, "TSIG MAC size and data are inconsistent");
  149. }
  150. const int32_t orig_id = tokenToNum<int32_t, 16>(getToken(iss, tsig_str));
  151. const string error_txt = getToken(iss, tsig_str);
  152. int32_t error = 0;
  153. // XXX: In the initial implementation we hardcode the mnemonics.
  154. // We'll soon generalize this.
  155. if (error_txt == "BADSIG") {
  156. error = 16;
  157. } else if (error_txt == "BADKEY") {
  158. error = 17;
  159. } else if (error_txt == "BADTIME") {
  160. error = 18;
  161. } else {
  162. error = tokenToNum<int32_t, 16>(error_txt);
  163. }
  164. const int32_t otherlen = tokenToNum<int32_t, 16>(getToken(iss, tsig_str));
  165. const string otherdata_txt = (otherlen > 0) ? getToken(iss, tsig_str) : "";
  166. vector<uint8_t> other_data;
  167. decodeBase64(otherdata_txt, other_data);
  168. if (!iss.eof()) {
  169. isc_throw(InvalidRdataText, "Unexpected input for TSIG RDATA: " <<
  170. tsig_str);
  171. }
  172. impl_ = new TSIGImpl(algorithm, time_signed, fudge, mac, orig_id,
  173. error, other_data);
  174. }
  175. /// \brief Constructor from wire-format data.
  176. ///
  177. /// When a read operation on \c buffer fails (e.g., due to a corrupted
  178. /// message) a corresponding exception from the \c InputBuffer class will
  179. /// be thrown.
  180. /// If the wire-format data does not begin with a valid domain name,
  181. /// a corresponding exception from the \c Name class will be thrown.
  182. /// In addition, this constructor internally involves resource allocation,
  183. /// and if it fails a corresponding standard exception will be thrown.
  184. ///
  185. /// According to RFC3597, the Algorithm field must be a non compressed form
  186. /// of domain name. But this implementation accepts a %TSIG RR even if that
  187. /// field is compressed.
  188. ///
  189. /// \param buffer A buffer storing the wire format data.
  190. /// \param rdata_len The length of the RDATA in bytes, normally expected
  191. /// to be the value of the RDLENGTH field of the corresponding RR.
  192. /// But this constructor does not use this parameter; if necessary, the caller
  193. /// must check consistency between the length parameter and the actual
  194. /// RDATA length.
  195. TSIG::TSIG(InputBuffer& buffer, size_t) : impl_(NULL) {
  196. Name algorithm(buffer);
  197. uint8_t time_signed_buf[6];
  198. buffer.readData(time_signed_buf, sizeof(time_signed_buf));
  199. const uint64_t time_signed =
  200. (static_cast<uint64_t>(time_signed_buf[0]) << 40 |
  201. static_cast<uint64_t>(time_signed_buf[1]) << 32 |
  202. static_cast<uint64_t>(time_signed_buf[2]) << 24 |
  203. static_cast<uint64_t>(time_signed_buf[3]) << 16 |
  204. static_cast<uint64_t>(time_signed_buf[4]) << 8 |
  205. static_cast<uint64_t>(time_signed_buf[5]));
  206. const uint16_t fudge = buffer.readUint16();
  207. const uint16_t mac_size = buffer.readUint16();
  208. vector<uint8_t> mac(mac_size);
  209. if (mac_size > 0) {
  210. buffer.readData(&mac[0], mac_size);
  211. }
  212. const uint16_t original_id = buffer.readUint16();
  213. const uint16_t error = buffer.readUint16();
  214. const uint16_t other_len = buffer.readUint16();
  215. vector<uint8_t> other_data(other_len);
  216. if (other_len > 0) {
  217. buffer.readData(&other_data[0], other_len);
  218. }
  219. impl_ = new TSIGImpl(algorithm, time_signed, fudge, mac, original_id,
  220. error, other_data);
  221. }
  222. TSIG::TSIG(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
  223. uint16_t mac_size, const void* mac, uint16_t original_id,
  224. uint16_t error, uint16_t other_len, const void* other_data) :
  225. impl_(NULL)
  226. {
  227. // Time Signed is a 48-bit value.
  228. if ((time_signed >> 48) != 0) {
  229. isc_throw(OutOfRange, "TSIG Time Signed is too large: " <<
  230. time_signed);
  231. }
  232. if ((mac_size == 0 && mac != NULL) || (mac_size > 0 && mac == NULL)) {
  233. isc_throw(InvalidParameter, "TSIG MAC size and data inconsistent");
  234. }
  235. if ((other_len == 0 && other_data != NULL) ||
  236. (other_len > 0 && other_data == NULL)) {
  237. isc_throw(InvalidParameter,
  238. "TSIG Other data length and data inconsistent");
  239. }
  240. impl_ = new TSIGImpl(algorithm, time_signed, fudge, mac_size, mac,
  241. original_id, error, other_len, other_data);
  242. }
  243. /// \brief The copy constructor.
  244. ///
  245. /// It internally allocates a resource, and if it fails a corresponding
  246. /// standard exception will be thrown.
  247. /// This constructor never throws an exception otherwise.
  248. TSIG::TSIG(const TSIG& source) : Rdata(), impl_(new TSIGImpl(*source.impl_))
  249. {}
  250. TSIG&
  251. TSIG::operator=(const TSIG& source) {
  252. if (impl_ == source.impl_) {
  253. return (*this);
  254. }
  255. TSIGImpl* newimpl = new TSIGImpl(*source.impl_);
  256. delete impl_;
  257. impl_ = newimpl;
  258. return (*this);
  259. }
  260. TSIG::~TSIG() {
  261. delete impl_;
  262. }
  263. /// \brief Convert the \c TSIG to a string.
  264. ///
  265. /// The output of this method is formatted as described in the "from string"
  266. /// constructor (\c TSIG(const std::string&))).
  267. ///
  268. /// If internal resource allocation fails, a corresponding
  269. /// standard exception will be thrown.
  270. ///
  271. /// \return A \c string object that represents the \c TSIG object.
  272. std::string
  273. TSIG::toText() const {
  274. string result;
  275. result += impl_->algorithm_.toText() + " " +
  276. lexical_cast<string>(impl_->time_signed_) + " " +
  277. lexical_cast<string>(impl_->fudge_) + " " +
  278. lexical_cast<string>(impl_->mac_.size()) + " ";
  279. if (impl_->mac_.size() > 0) {
  280. result += encodeBase64(impl_->mac_) + " ";
  281. }
  282. result += lexical_cast<string>(impl_->original_id_) + " ";
  283. result += TSIGError(impl_->error_).toText() + " ";
  284. result += lexical_cast<string>(impl_->other_data_.size());
  285. if (impl_->other_data_.size() > 0) {
  286. result += " " + encodeBase64(impl_->other_data_);
  287. }
  288. return (result);
  289. }
  290. // Common sequence of toWire() operations used for the two versions of
  291. // toWire().
  292. template <typename Output>
  293. void
  294. TSIG::TSIGImpl::toWireCommon(Output& output) const {
  295. output.writeUint16(time_signed_ >> 32);
  296. output.writeUint32(time_signed_ & 0xffffffff);
  297. output.writeUint16(fudge_);
  298. const uint16_t mac_size = mac_.size();
  299. output.writeUint16(mac_size);
  300. if (mac_size > 0) {
  301. output.writeData(&mac_[0], mac_size);
  302. }
  303. output.writeUint16(original_id_);
  304. output.writeUint16(error_);
  305. const uint16_t other_len = other_data_.size();
  306. output.writeUint16(other_len);
  307. if (other_len > 0) {
  308. output.writeData(&other_data_[0], other_len);
  309. }
  310. }
  311. /// \brief Render the \c TSIG in the wire format without name compression.
  312. ///
  313. /// If internal resource allocation fails, a corresponding
  314. /// standard exception will be thrown.
  315. /// This method never throws an exception otherwise.
  316. ///
  317. /// \param buffer An output buffer to store the wire data.
  318. void
  319. TSIG::toWire(OutputBuffer& buffer) const {
  320. impl_->algorithm_.toWire(buffer);
  321. impl_->toWireCommon<OutputBuffer>(buffer);
  322. }
  323. /// \brief Render the \c TSIG in the wire format with taking into account
  324. /// compression.
  325. ///
  326. /// As specified in RFC3597, the Algorithm field (a domain name) will not
  327. /// be compressed. However, the domain name could be a target of compression
  328. /// of other compressible names (though pretty unlikely), the offset
  329. /// information of the algorithm name may be recorded in \c renderer.
  330. ///
  331. /// If internal resource allocation fails, a corresponding
  332. /// standard exception will be thrown.
  333. /// This method never throws an exception otherwise.
  334. ///
  335. /// \param renderer DNS message rendering context that encapsulates the
  336. /// output buffer and name compression information.
  337. void
  338. TSIG::toWire(AbstractMessageRenderer& renderer) const {
  339. renderer.writeName(impl_->algorithm_, false);
  340. impl_->toWireCommon<AbstractMessageRenderer>(renderer);
  341. }
  342. // A helper function commonly used for TSIG::compare().
  343. int
  344. vectorComp(const vector<uint8_t>& v1, const vector<uint8_t>& v2) {
  345. const size_t this_size = v1.size();
  346. const size_t other_size = v2.size();
  347. if (this_size != other_size) {
  348. return (this_size < other_size ? -1 : 1);
  349. }
  350. if (this_size > 0) {
  351. return (memcmp(&v1[0], &v2[0], this_size));
  352. }
  353. return (0);
  354. }
  355. /// \brief Compare two instances of \c TSIG RDATA.
  356. ///
  357. /// This method compares \c this and the \c other \c TSIG objects
  358. /// in terms of the DNSSEC sorting order as defined in RFC4034, and returns
  359. /// the result as an integer.
  360. ///
  361. /// This method is expected to be used in a polymorphic way, and the
  362. /// parameter to compare against is therefore of the abstract \c Rdata class.
  363. /// However, comparing two \c Rdata objects of different RR types
  364. /// is meaningless, and \c other must point to a \c TSIG object;
  365. /// otherwise, the standard \c bad_cast exception will be thrown.
  366. /// This method never throws an exception otherwise.
  367. ///
  368. /// \param other the right-hand operand to compare against.
  369. /// \return < 0 if \c this would be sorted before \c other.
  370. /// \return 0 if \c this is identical to \c other in terms of sorting order.
  371. /// \return > 0 if \c this would be sorted after \c other.
  372. int
  373. TSIG::compare(const Rdata& other) const {
  374. const TSIG& other_tsig = dynamic_cast<const TSIG&>(other);
  375. const int ncmp = compareNames(impl_->algorithm_,
  376. other_tsig.impl_->algorithm_);
  377. if (ncmp != 0) {
  378. return (ncmp);
  379. }
  380. if (impl_->time_signed_ != other_tsig.impl_->time_signed_) {
  381. return (impl_->time_signed_ < other_tsig.impl_->time_signed_ ? -1 : 1);
  382. }
  383. if (impl_->fudge_ != other_tsig.impl_->fudge_) {
  384. return (impl_->fudge_ < other_tsig.impl_->fudge_ ? -1 : 1);
  385. }
  386. const int vcmp = vectorComp(impl_->mac_, other_tsig.impl_->mac_);
  387. if (vcmp != 0) {
  388. return (vcmp);
  389. }
  390. if (impl_->original_id_ != other_tsig.impl_->original_id_) {
  391. return (impl_->original_id_ < other_tsig.impl_->original_id_ ? -1 : 1);
  392. }
  393. if (impl_->error_ != other_tsig.impl_->error_) {
  394. return (impl_->error_ < other_tsig.impl_->error_ ? -1 : 1);
  395. }
  396. return (vectorComp(impl_->other_data_, other_tsig.impl_->other_data_));
  397. }
  398. const Name&
  399. TSIG::getAlgorithm() const {
  400. return (impl_->algorithm_);
  401. }
  402. uint64_t
  403. TSIG::getTimeSigned() const {
  404. return (impl_->time_signed_);
  405. }
  406. uint16_t
  407. TSIG::getFudge() const {
  408. return (impl_->fudge_);
  409. }
  410. uint16_t
  411. TSIG::getMACSize() const {
  412. return (impl_->mac_.size());
  413. }
  414. const void*
  415. TSIG::getMAC() const {
  416. if (impl_->mac_.size() > 0) {
  417. return (&impl_->mac_[0]);
  418. } else {
  419. return (NULL);
  420. }
  421. }
  422. uint16_t
  423. TSIG::getOriginalID() const {
  424. return (impl_->original_id_);
  425. }
  426. uint16_t
  427. TSIG::getError() const {
  428. return (impl_->error_);
  429. }
  430. uint16_t
  431. TSIG::getOtherLen() const {
  432. return (impl_->other_data_.size());
  433. }
  434. const void*
  435. TSIG::getOtherData() const {
  436. if (impl_->other_data_.size() > 0) {
  437. return (&impl_->other_data_[0]);
  438. } else {
  439. return (NULL);
  440. }
  441. }
  442. // END_RDATA_NAMESPACE
  443. // END_ISC_NAMESPACE