tsig_250.cc 19 KB
Newer Older
1
// Copyright (C) 2010-2013  Internet Systems Consortium, Inc. ("ISC")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <string>
#include <sstream>
#include <vector>

#include <boost/lexical_cast.hpp>

21
#include <util/buffer.h>
22
#include <util/strutil.h>
chenzhengzhang's avatar
chenzhengzhang committed
23
#include <util/encode/base64.h>
24

25
#include <dns/messagerenderer.h>
26
#include <dns/name.h>
27
28
#include <dns/rdata.h>
#include <dns/rdataclass.h>
29
#include <dns/rcode.h>
30
#include <dns/tsigerror.h>
31
#include <dns/rdata/generic/detail/lexer_util.h>
32
33

using namespace std;
34
using boost::lexical_cast;
35
using namespace isc::util;
chenzhengzhang's avatar
chenzhengzhang committed
36
using namespace isc::util::encode;
37
using namespace isc::util::str;
38
39
using namespace isc::dns;
using isc::dns::rdata::generic::detail::createNameFromLexer;
40
41
42
43

// BEGIN_ISC_NAMESPACE
// BEGIN_RDATA_NAMESPACE

44
45
// straightforward representation of TSIG RDATA fields
struct TSIGImpl {
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    TSIGImpl(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
             vector<uint8_t>& mac, uint16_t original_id, uint16_t error,
             vector<uint8_t>& other_data) :
        algorithm_(algorithm), time_signed_(time_signed), fudge_(fudge),
        mac_(mac), original_id_(original_id), error_(error),
        other_data_(other_data)
    {}
    TSIGImpl(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
             size_t macsize, const void* mac, uint16_t original_id,
             uint16_t error, size_t other_len, const void* other_data) :
        algorithm_(algorithm), time_signed_(time_signed), fudge_(fudge),
        mac_(static_cast<const uint8_t*>(mac),
             static_cast<const uint8_t*>(mac) + macsize),
        original_id_(original_id), error_(error),
        other_data_(static_cast<const uint8_t*>(other_data),
                    static_cast<const uint8_t*>(other_data) + other_len)
    {}
63
64
    template <typename Output>
    void toWireCommon(Output& output) const;
65
66
67
68
69
70
71
72
73
74

    const Name algorithm_;
    const uint64_t time_signed_;
    const uint16_t fudge_;
    const vector<uint8_t> mac_;
    const uint16_t original_id_;
    const uint16_t error_;
    const vector<uint8_t> other_data_;
};

75
76
77
78
79
80
81
// helper function for string and lexer constructors
TSIGImpl*
TSIG::constructFromLexer(MasterLexer& lexer) {
    // RFC2845 defines Algorithm Name to be "in domain name syntax",
    // but it's not actually a domain name, so we allow it to be not
    // fully qualified.
    const Name root(".");
82
    const Name& algorithm = createNameFromLexer(lexer, &root);
83

84
85
    const string time_str =
        lexer.getNextToken(MasterToken::STRING).getString();
86
87
88
89
90
91
    uint64_t time_signed;
    try {
        time_signed = boost::lexical_cast<uint64_t>(time_str);
    } catch (const boost::bad_lexical_cast&) {
        isc_throw(InvalidRdataText, "Invalid TSIG Time");
    }
Paul Selkirk's avatar
Paul Selkirk committed
92
    if ((time_signed >> 48) != 0) {
93
94
95
        isc_throw(InvalidRdataText, "TSIG Time out of range");
    }

96
    const uint32_t fudge = lexer.getNextToken(MasterToken::NUMBER).getNumber();
97
98
99
    if (fudge > 0xffff) {
        isc_throw(InvalidRdataText, "TSIG Fudge out of range");
    }
100
101
    const uint32_t macsize =
        lexer.getNextToken(MasterToken::NUMBER).getNumber();
102
103
104
105
106
107
108
109
110
111
112
113
    if (macsize > 0xffff) {
        isc_throw(InvalidRdataText, "TSIG MAC Size out of range");
    }

    const string mac_txt = (macsize > 0) ?
            lexer.getNextToken(MasterToken::STRING).getString() : "";
    vector<uint8_t> mac;
    decodeBase64(mac_txt, mac);
    if (mac.size() != macsize) {
        isc_throw(InvalidRdataText, "TSIG MAC Size and data are inconsistent");
    }

114
115
    const uint32_t orig_id =
        lexer.getNextToken(MasterToken::NUMBER).getNumber();
116
117
118
119
    if (orig_id > 0xffff) {
        isc_throw(InvalidRdataText, "TSIG Original ID out of range");
    }

120
121
    const string error_txt =
        lexer.getNextToken(MasterToken::STRING).getString();
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    uint16_t error = 0;
    // XXX: In the initial implementation we hardcode the mnemonics.
    // We'll soon generalize this.
    if (error_txt == "NOERROR") {
        error = Rcode::NOERROR_CODE;
    } else if (error_txt == "BADSIG") {
        error = TSIGError::BAD_SIG_CODE;
    } else if (error_txt == "BADKEY") {
        error = TSIGError::BAD_KEY_CODE;
    } else if (error_txt == "BADTIME") {
        error = TSIGError::BAD_TIME_CODE;
    } else {
        try {
            error = boost::lexical_cast<uint16_t>(error_txt);
        } catch (const boost::bad_lexical_cast&) {
            isc_throw(InvalidRdataText, "Invalid TSIG Error");
        }
    }

141
142
    const int32_t otherlen =
        lexer.getNextToken(MasterToken::NUMBER).getNumber();
143
144
145
    if (otherlen > 0xffff) {
        isc_throw(InvalidRdataText, "TSIG Other Len out of range");
    }
146
    const string otherdata_txt = (otherlen > 0) ?
147
148
149
150
151
152
153
154
155
156
157
158
159
            lexer.getNextToken(MasterToken::STRING).getString() : "";
    vector<uint8_t> other_data;
    decodeBase64(otherdata_txt, other_data);
    if (other_data.size() != otherlen) {
        isc_throw(InvalidRdataText,
                  "TSIG Other Data length does not match Other Len");
    }
    // also verify Error == BADTIME?

    return new TSIGImpl(algorithm, time_signed, fudge, mac, orig_id,
                        error, other_data);
}

160
161
162
163
164
165
/// \brief Constructor from string.
///
/// \c tsig_str must be formatted as follows:
/// \code <Alg> <Time> <Fudge> <MACsize> [<MAC>] <OrigID> <Error> <OtherLen> [<OtherData>]
/// \endcode
/// where
166
167
/// - &lt;Alg&gt; is a valid textual representation of domain name.
/// - &lt;Time&gt; is an unsigned 48-bit decimal integer.
168
169
/// - &lt;MACSize&gt;, &lt;OrigID&gt;, and &lt;OtherLen&gt; are an unsigned
///   16-bit decimal
170
///   integer.
171
172
/// - &lt;Error&gt; is an unsigned 16-bit decimal integer or a valid mnemonic
///   for the Error field specified in RFC2845.  Currently, "BADSIG", "BADKEY",
173
174
175
///   and "BADTIME" are supported (case sensitive).  In future versions
///   other representations that are compatible with the DNS RCODE will be
///   supported.
176
177
178
179
180
181
182
183
/// - &lt;MAC&gt; and &lt;OtherData&gt; is a BASE-64 encoded string that does
///   not contain space characters.
///   When &lt;MACSize&gt; and &lt;OtherLen&gt; is 0, &lt;MAC&gt; and
///   &lt;OtherData&gt; must not appear in \c tsig_str, respectively.
/// - The decoded data of &lt;MAC&gt; is &lt;MACSize&gt; bytes of binary
///   stream.
/// - The decoded data of &lt;OtherData&gt; is &lt;OtherLen&gt; bytes of
///   binary stream.
184
185
186
///
/// An example of valid string is:
/// \code "hmac-sha256. 853804800 300 3 AAAA 2845 0 0" \endcode
187
/// In this example &lt;OtherData&gt; is missing because &lt;OtherLen&gt; is 0.
188
189
190
191
192
193
194
195
///
/// Note that RFC2845 does not define the standard presentation format
/// of %TSIG RR, so the above syntax is implementation specific.
/// This is, however, compatible with the format acceptable to BIND 9's
/// RDATA parser.
///
/// <b>Exceptions</b>
///
196
/// If &lt;Alg&gt; is not a valid domain name, a corresponding exception from
197
/// the \c Name class will be thrown;
198
199
/// if &lt;MAC&gt; or &lt;OtherData&gt; is not validly encoded in BASE-64, an
/// exception of class \c isc::BadValue will be thrown;
200
201
202
203
/// if %any of the other bullet points above is not met, an exception of
/// class \c InvalidRdataText will be thrown.
/// This constructor internally involves resource allocation, and if it fails
/// a corresponding standard exception will be thrown.
204
TSIG::TSIG(const std::string& tsig_str) : impl_(NULL) {
205
206
    // We use auto_ptr here because if there is an exception in this
    // constructor, the destructor is not called and there could be a
Paul Selkirk's avatar
Paul Selkirk committed
207
    // leak of the TSIGImpl that constructFromLexer() returns.
208
    std::auto_ptr<TSIGImpl> impl_ptr(NULL);
209

210
    try {
211
212
213
        std::istringstream ss(tsig_str);
        MasterLexer lexer;
        lexer.pushSource(ss);
214

215
        impl_ptr.reset(constructFromLexer(lexer));
216

217
218
219
        if (lexer.getNextToken().getType() != MasterToken::END_OF_FILE) {
            isc_throw(InvalidRdataText,
                      "Extra input text for TSIG: " << tsig_str);
220
        }
221
222
223
224
225
    } catch (const MasterLexer::LexerError& ex) {
        isc_throw(InvalidRdataText,
                  "Failed to construct TSIG from '" << tsig_str << "': "
                  << ex.what());
    }
226

227
228
    impl_ = impl_ptr.release();
}
229

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/// \brief Constructor with a context of MasterLexer.
///
/// The \c lexer should point to the beginning of valid textual
/// representation of an TSIG RDATA.
///
/// See \c TSIG::TSIG(const std::string&) for description of the
/// expected RDATA fields.
///
/// \throw MasterLexer::LexerError General parsing error such as
/// missing field.
/// \throw InvalidRdataText if any fields are out of their valid range,
/// or are incorrect.
///
/// \param lexer A \c MasterLexer object parsing a master file for the
/// RDATA to be created
TSIG::TSIG(MasterLexer& lexer, const Name*,
               MasterLoader::Options, MasterLoaderCallbacks&) :
247
    impl_(constructFromLexer(lexer))
248
{
249
250
}

251
/// \brief Constructor from wire-format data.
252
253
254
255
///
/// When a read operation on \c buffer fails (e.g., due to a corrupted
/// message) a corresponding exception from the \c InputBuffer class will
/// be thrown.
256
/// If the wire-format data does not begin with a valid domain name,
257
258
259
260
261
262
263
264
/// a corresponding exception from the \c Name class will be thrown.
/// In addition, this constructor internally involves resource allocation,
/// and if it fails a corresponding standard exception will be thrown.
///
/// According to RFC3597, the Algorithm field must be a non compressed form
/// of domain name.  But this implementation accepts a %TSIG RR even if that
/// field is compressed.
///
265
266
/// \param buffer A buffer storing the wire format data.
/// \param rdata_len The length of the RDATA in bytes, normally expected
267
268
269
270
/// to be the value of the RDLENGTH field of the corresponding RR.
/// But this constructor does not use this parameter; if necessary, the caller
/// must check consistency between the length parameter and the actual
/// RDATA length.
271
TSIG::TSIG(InputBuffer& buffer, size_t) : impl_(NULL) {
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    Name algorithm(buffer);

    uint8_t time_signed_buf[6];
    buffer.readData(time_signed_buf, sizeof(time_signed_buf));
    const uint64_t time_signed =
        (static_cast<uint64_t>(time_signed_buf[0]) << 40 |
         static_cast<uint64_t>(time_signed_buf[1]) << 32 |
         static_cast<uint64_t>(time_signed_buf[2]) << 24 |
         static_cast<uint64_t>(time_signed_buf[3]) << 16 |
         static_cast<uint64_t>(time_signed_buf[4]) << 8 |
         static_cast<uint64_t>(time_signed_buf[5]));

    const uint16_t fudge = buffer.readUint16();

    const uint16_t mac_size = buffer.readUint16();
    vector<uint8_t> mac(mac_size);
    if (mac_size > 0) {
        buffer.readData(&mac[0], mac_size);
    }

    const uint16_t original_id = buffer.readUint16();
    const uint16_t error = buffer.readUint16();

    const uint16_t other_len = buffer.readUint16();
    vector<uint8_t> other_data(other_len);
    if (other_len > 0) {
        buffer.readData(&other_data[0], other_len);
    }

    impl_ = new TSIGImpl(algorithm, time_signed, fudge, mac, original_id,
                         error, other_data);
}

TSIG::TSIG(const Name& algorithm, uint64_t time_signed, uint16_t fudge,
306
307
           uint16_t mac_size, const void* mac, uint16_t original_id,
           uint16_t error, uint16_t other_len, const void* other_data) :
308
309
    impl_(NULL)
{
310
311
    // Time Signed is a 48-bit value.
    if ((time_signed >> 48) != 0) {
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
        isc_throw(OutOfRange, "TSIG Time Signed is too large: " <<
                  time_signed);
    }
    if ((mac_size == 0 && mac != NULL) || (mac_size > 0 && mac == NULL)) {
        isc_throw(InvalidParameter, "TSIG MAC size and data inconsistent");
    }
    if ((other_len == 0 && other_data != NULL) ||
        (other_len > 0 && other_data == NULL)) {
        isc_throw(InvalidParameter,
                  "TSIG Other data length and data inconsistent");
    }
    impl_ = new TSIGImpl(algorithm, time_signed, fudge, mac_size, mac,
                         original_id, error, other_len, other_data);
}

327
328
329
330
331
/// \brief The copy constructor.
///
/// It internally allocates a resource, and if it fails a corresponding
/// standard exception will be thrown.
/// This constructor never throws an exception otherwise.
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
TSIG::TSIG(const TSIG& source) : Rdata(), impl_(new TSIGImpl(*source.impl_))
{}

TSIG&
TSIG::operator=(const TSIG& source) {
    if (impl_ == source.impl_) {
        return (*this);
    }

    TSIGImpl* newimpl = new TSIGImpl(*source.impl_);
    delete impl_;
    impl_ = newimpl;

    return (*this);
}

TSIG::~TSIG() {
    delete impl_;
}

352
353
/// \brief Convert the \c TSIG to a string.
///
354
/// The output of this method is formatted as described in the "from string"
355
356
357
358
359
360
/// constructor (\c TSIG(const std::string&))).
///
/// If internal resource allocation fails, a corresponding
/// standard exception will be thrown.
///
/// \return A \c string object that represents the \c TSIG object.
361
362
363
364
365
366
367
368
369
370
371
372
std::string
TSIG::toText() const {
    string result;

    result += impl_->algorithm_.toText() + " " +
        lexical_cast<string>(impl_->time_signed_) + " " +
        lexical_cast<string>(impl_->fudge_) + " " +
        lexical_cast<string>(impl_->mac_.size()) + " ";
    if (impl_->mac_.size() > 0) {
        result += encodeBase64(impl_->mac_) + " ";
    }
    result += lexical_cast<string>(impl_->original_id_) + " ";
373
    result += TSIGError(impl_->error_).toText() + " ";
374
375
376
377
378
379
380
381
    result += lexical_cast<string>(impl_->other_data_.size());
    if (impl_->other_data_.size() > 0) {
        result += " " + encodeBase64(impl_->other_data_);
    }

    return (result);
}

382
383
// Common sequence of toWire() operations used for the two versions of
// toWire().
384
385
template <typename Output>
void
386
TSIGImpl::toWireCommon(Output& output) const {
387
388
389
390
    output.writeUint16(time_signed_ >> 32);
    output.writeUint32(time_signed_ & 0xffffffff);
    output.writeUint16(fudge_);
    const uint16_t mac_size = mac_.size();
391
392
    output.writeUint16(mac_size);
    if (mac_size > 0) {
393
        output.writeData(&mac_[0], mac_size);
394
    }
395
396
397
    output.writeUint16(original_id_);
    output.writeUint16(error_);
    const uint16_t other_len = other_data_.size();
398
399
    output.writeUint16(other_len);
    if (other_len > 0) {
400
        output.writeData(&other_data_[0], other_len);
401
402
403
    }
}

404
405
406
407
408
409
410
/// \brief Render the \c TSIG in the wire format without name compression.
///
/// If internal resource allocation fails, a corresponding
/// standard exception will be thrown.
/// This method never throws an exception otherwise.
///
/// \param buffer An output buffer to store the wire data.
411
412
413
void
TSIG::toWire(OutputBuffer& buffer) const {
    impl_->algorithm_.toWire(buffer);
414
    impl_->toWireCommon<OutputBuffer>(buffer);
415
416
}

417
418
419
/// \brief Render the \c TSIG in the wire format with taking into account
/// compression.
///
420
/// As specified in RFC3597, the Algorithm field (a domain name) will not
421
422
/// be compressed.  However, the domain name could be a target of compression
/// of other compressible names (though pretty unlikely), the offset
423
/// information of the algorithm name may be recorded in \c renderer.
424
425
426
427
428
429
430
///
/// If internal resource allocation fails, a corresponding
/// standard exception will be thrown.
/// This method never throws an exception otherwise.
///
/// \param renderer DNS message rendering context that encapsulates the
/// output buffer and name compression information.
431
void
432
TSIG::toWire(AbstractMessageRenderer& renderer) const {
433
    renderer.writeName(impl_->algorithm_, false);
434
    impl_->toWireCommon<AbstractMessageRenderer>(renderer);
435
436
}

437
// A helper function commonly used for TSIG::compare().
438
439
440
441
442
443
444
445
446
447
448
449
450
int
vectorComp(const vector<uint8_t>& v1, const vector<uint8_t>& v2) {
    const size_t this_size = v1.size();
    const size_t other_size = v2.size();
    if (this_size != other_size) {
        return (this_size < other_size ? -1 : 1);
    }
    if (this_size > 0) {
        return (memcmp(&v1[0], &v2[0], this_size));
    }
    return (0);
}

451
452
453
/// \brief Compare two instances of \c TSIG RDATA.
///
/// This method compares \c this and the \c other \c TSIG objects
454
/// in terms of the DNSSEC sorting order as defined in RFC4034, and returns
455
456
/// the result as an integer.
///
457
/// This method is expected to be used in a polymorphic way, and the
458
459
460
461
462
463
464
465
466
467
/// parameter to compare against is therefore of the abstract \c Rdata class.
/// However, comparing two \c Rdata objects of different RR types
/// is meaningless, and \c other must point to a \c TSIG object;
/// otherwise, the standard \c bad_cast exception will be thrown.
/// This method never throws an exception otherwise.
///
/// \param other the right-hand operand to compare against.
/// \return < 0 if \c this would be sorted before \c other.
/// \return 0 if \c this is identical to \c other in terms of sorting order.
/// \return > 0 if \c this would be sorted after \c other.
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
int
TSIG::compare(const Rdata& other) const {
    const TSIG& other_tsig = dynamic_cast<const TSIG&>(other);

    const int ncmp = compareNames(impl_->algorithm_,
                                  other_tsig.impl_->algorithm_);
    if (ncmp != 0) {
        return (ncmp);
    }

    if (impl_->time_signed_ != other_tsig.impl_->time_signed_) {
        return (impl_->time_signed_ < other_tsig.impl_->time_signed_ ? -1 : 1);
    }
    if (impl_->fudge_ != other_tsig.impl_->fudge_) {
        return (impl_->fudge_ < other_tsig.impl_->fudge_ ? -1 : 1);
    }
    const int vcmp = vectorComp(impl_->mac_, other_tsig.impl_->mac_);
    if (vcmp != 0) {
        return (vcmp);
    }
    if (impl_->original_id_ != other_tsig.impl_->original_id_) {
        return (impl_->original_id_ < other_tsig.impl_->original_id_ ? -1 : 1);
    }
    if (impl_->error_ != other_tsig.impl_->error_) {
        return (impl_->error_ < other_tsig.impl_->error_ ? -1 : 1);
    }
494
    return (vectorComp(impl_->other_data_, other_tsig.impl_->other_data_));
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
}

const Name&
TSIG::getAlgorithm() const {
    return (impl_->algorithm_);
}

uint64_t
TSIG::getTimeSigned() const {
    return (impl_->time_signed_);
}

uint16_t
TSIG::getFudge() const {
    return (impl_->fudge_);
}

uint16_t
TSIG::getMACSize() const {
    return (impl_->mac_.size());
}

const void*
TSIG::getMAC() const {
    if (impl_->mac_.size() > 0) {
        return (&impl_->mac_[0]);
    } else {
        return (NULL);
    }
}

uint16_t
TSIG::getOriginalID() const {
    return (impl_->original_id_);
}

uint16_t
TSIG::getError() const {
    return (impl_->error_);
}

uint16_t
TSIG::getOtherLen() const {
    return (impl_->other_data_.size());
}

const void*
TSIG::getOtherData() const {
    if (impl_->other_data_.size() > 0) {
        return (&impl_->other_data_[0]);
    } else {
        return (NULL);
    }
}

// END_RDATA_NAMESPACE
// END_ISC_NAMESPACE