1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Copyright (C) 2021-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Kea Hooks Basic
// Commercial End User License Agreement v2.0. See COPYING file in the premium/
// directory.

#include <config.h>

#include <asiolink/interval_timer.h>
#include <asiodns/io_fetch.h>
#include <d2srv/dns_client.h>
#include <d2srv/testutils/stats_test_utils.h>
#include <dns/rcode.h>
#include <gss_tsig_api_utils.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <managed_key.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <testutils/gss_tsig_dns_server.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <util/chrono_time_utils.h>

#include <chrono><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

namespace {

const char* TEST_ADDRESS = "127.0.0.1";
const uint16_t TEST_PORT = 5376;
const size_t MAX_SIZE = 1024;
const long TEST_TIMEOUT = 5 * 1000; // expressed in milliseconds.

using namespace isc;
using namespace isc::asiolink;
using namespace isc::asiodns;
using namespace isc::d2;
using namespace isc::d2::test;
using namespace isc::dns;
using namespace isc::gss_tsig;
using namespace isc::gss_tsig::test;
using namespace isc::util;

using namespace std;
using namespace std::chrono;

typedef std::function<void()> DNSCallback;

/// @brief Callback class used to handle the TKEY exchange status.
class NSUpdateTestCallback : public TKeyExchange::Callback {
public:
    /// @brief Constructor
    ///
    /// @param io_service The IOService which handles IO operations.
    /// @param callback The callback used as a continuation after the TKEY
    /// exchange is completed.
    /// @param status The expected status.
    NSUpdateTestCallback(IOServicePtr io_service, DNSCallback& callback,
                         TKeyExchange::Status status = TKeyExchange::SUCCESS) :
        io_service_(io_service), callback_(callback), status_(status) {
    }

    /// @brief Destructor.
    ~NSUpdateTestCallback() = default;

    /// @brief The callback function which retrieves the TKEY exchange status.
    void operator()(TKeyExchange::Status status) {
        if (status != status_) {
            ADD_FAILURE() << "key exchange returned " << status
                          << ", expected: " << status_;
            io_service_->stop();
            return;
        }

        if (status != TKeyExchange::SUCCESS) {
            io_service_->stop();
            return;
        }

        if (callback_) {
            callback_();
        } else {
            io_service_->stop();
        }
    }

    /// @brief The IOService which handles IO operations.
    IOServicePtr io_service_;

    /// @brief The callback called after the GSS-TSIG TKEY exchange has
    /// succeeded so that the GSS-TSIG DNS update is performed.
    DNSCallback& callback_;

    /// @brief The expected TKEY exchange status.
    TKeyExchange::Status status_;
};

/// @brief Test fixture for testing the GSS-API GSS-TSIG DNS update with
/// Kerberos 5.
class GssTsigDNSUpdateTest : public GssApiBaseTest, public DNSClient::Callback,
                             public D2StatTest {
public:
    /// @brief Constructor.
    GssTsigDNSUpdateTest() : io_service_(new IOService()),
                             test_timer_(io_service_), response_(),
                             dns_client_(new DNSClient(response_, this)),
                             expected_status_(DNSClient::SUCCESS),
                             success_(false), use_fallback_(false) {

        // Set the test timeout to break any running tasks if they hang.
        test_timer_.setup(std::bind(&GssTsigDNSUpdateTest::testTimeoutHandler, this),
                          TEST_TIMEOUT);
    }

    /// @brief Destructor.
    virtual ~GssTsigDNSUpdateTest() {
        key_->getTKeyExchange().reset();
        test_timer_.cancel();
        io_service_->stopAndPoll();
    }

    /// @brief Perform the DNS update.
    void doGssTsigDNSUpdate() {
        auto key = key_;
        if (use_fallback_) {
            key.reset();
        }
        // Create a request DNS Update message.
        D2UpdateMessage message(D2UpdateMessage::OUTBOUND);
        ASSERT_NO_THROW(message.setRcode(Rcode(Rcode::NOERROR_CODE)));
        ASSERT_NO_THROW(message.setZone(Name("example.com"), RRClass::IN()));

        // The socket is now ready to receive the data. Let's post some request
        // message then. Set timeout to some reasonable value to make sure that
        // there is sufficient amount of time for the test to generate a
        // response.
        const int timeout = 500;
        dns_client_->doUpdate(io_service_, IOAddress(TEST_ADDRESS), TEST_PORT,
                              message, timeout, key);
    }

    /// @brief Exchange completion callback
    ///
    /// This callback is called when the exchange with the DNS server is
    /// complete or an error occurred. This includes the occurrence of a timeout.
    ///
    /// @param status A status code returned by DNSClient.
    virtual void operator()(DNSClient::Status status) {
        io_service_->stop();
        EXPECT_EQ(expected_status_, status);
        if (expected_status_ == DNSClient::SUCCESS) {
            // We should have received a signed response.
            ASSERT_TRUE(response_);
            EXPECT_EQ(D2UpdateMessage::RESPONSE, response_->getQRFlag());
            ASSERT_EQ(1, response_->getRRCount(D2UpdateMessage::SECTION_ZONE));
            D2ZonePtr zone = response_->getZone();
            ASSERT_TRUE(zone);
            EXPECT_EQ("example.com.", zone->getName().toText());
            EXPECT_EQ(RRClass::IN().getCode(), zone->getClass().getCode());
            // DNS update has been signed on the server side and verified on the
            // client side.
            success_ = true;
        } else if (expected_status_ == DNSClient::INVALID_RESPONSE) {
            // We should have received an unsigned response.
            ASSERT_TRUE(response_);
            EXPECT_EQ(D2UpdateMessage::RESPONSE, response_->getQRFlag());
            ASSERT_EQ(1, response_->getRRCount(D2UpdateMessage::SECTION_ZONE));
            D2ZonePtr zone = response_->getZone();
            ASSERT_FALSE(zone);
        }
    }

    /// @brief Handler invoked when test timeout is hit.
    ///
    /// This callback stops all running (hanging) tasks on IO service.
    void testTimeoutHandler() {
        io_service_->stop();
        FAIL() << "Test timeout hit.";
    }

    /// @brief The IOService which handles IO operations.
    IOServicePtr io_service_;

    /// @brief The timeout timer.
    asiolink::IntervalTimer test_timer_;

    /// @brief DNS client response.
    D2UpdateMessagePtr response_;

    /// @brief The DNS client performing GSS-TSIG DNS update.
    DNSClientPtr dns_client_;

    /// @brief The DNS client key.
    ManagedKeyPtr key_;

    /// @brief The expected status of the DNS client update callback.
    DNSClient::Status expected_status_;

    /// @brief The flag which indicates that the DNS update has been
    /// successfully verified.
    bool success_;

    /// @brief The flag which indicates if the DNS update should fallback to non
    /// GSS-TSIG if the key is removed.
    bool use_fallback_;
};

/// @brief Check GSS-TSIG DNS update fails because the DNS server is not
/// responding to DNS updates.
TEST_F(GssTsigDNSUpdateTest, runGssTsigDNSUpdateTimeout) {<--- syntax error
    expected_status_ = DNSClient::TIMEOUT;
    string key_name("1234.sig-blu.example.nil.");
    key_.reset(new ManagedKey(key_name));
    DnsServerPtr server(new DnsServer("foo", {}, IOAddress(TEST_ADDRESS),
                                      TEST_PORT));
    server->setServerPrincipal("DNS/blu.example.nil@EXAMPLE.NIL");
    server->setKeyProto(IOFetch::Protocol::UDP);
    setKeytab();
    setAdministratorCCache();

    DNSCallback dns_callback = std::bind(&GssTsigDNSUpdateTest::doGssTsigDNSUpdate, this);
    NSUpdateTestCallback callback(io_service_, dns_callback);

    system_clock::time_point now = system_clock::now();
    key_->setInception(now);
    key_->setExpire(now + seconds(server->getKeyLifetime()));
    key_->getTKeyExchange().reset(new TKeyExchange(io_service_, server, key_,
                                                   &callback));
    key_->getTKeyExchange()->doExchange();

    // The server will sign the TKEY and stop responding to DNS updates.
    DummyDNSServer dns_server(io_service_, true, true, false, false);
    dns_server.start();
    io_service_->run();
    ASSERT_FALSE(success_);
    // Check statistics.
    StatMap stats_key = {
        { "update-sent", 1},
        { "update-success", 0},
        { "update-timeout", 1},
        { "update-error", 0}
    };
    checkStats(key_name, stats_key);
    StatMap stats_upd = {
        { "update-sent", 1},
        { "update-signed", 1},
        { "update-unsigned", 0},
        { "update-success", 0},
        { "update-timeout", 1},
        { "update-error", 0}
    };
    checkStats(stats_upd);
}

/// @brief Check GSS-TSIG DNS update fails because the DNS update is not signed.
TEST_F(GssTsigDNSUpdateTest, runGssTsigDNSUpdateFailure) {
    expected_status_ = DNSClient::INVALID_RESPONSE;
    string key_name("1234.sig-blu.example.nil.");
    key_.reset(new ManagedKey(key_name));
    DnsServerPtr server(new DnsServer("foo", {}, IOAddress(TEST_ADDRESS),
                                      TEST_PORT));
    server->setServerPrincipal("DNS/blu.example.nil@EXAMPLE.NIL");
    server->setKeyProto(IOFetch::Protocol::UDP);
    setKeytab();
    setAdministratorCCache();

    DNSCallback dns_callback = std::bind(&GssTsigDNSUpdateTest::doGssTsigDNSUpdate, this);
    NSUpdateTestCallback callback(io_service_, dns_callback);

    system_clock::time_point now = system_clock::now();
    key_->setInception(now);
    key_->setExpire(now + seconds(server->getKeyLifetime()));
    key_->getTKeyExchange().reset(new TKeyExchange(io_service_, server, key_,
                                                   &callback));
    key_->getTKeyExchange()->doExchange();

    // The server will sign the TKEY, but not sign the DNS update.
    DummyDNSServer dns_server(io_service_, true, false);
    dns_server.start();
    io_service_->run();
    ASSERT_FALSE(success_);
    // Check statistics.
    StatMap stats_key = {
        { "update-sent", 1},
        { "update-success", 0},
        { "update-timeout", 0},
        { "update-error", 1}
    };
    checkStats(key_name, stats_key);
    StatMap stats_upd = {
        { "update-sent", 1},
        { "update-signed", 1},
        { "update-unsigned", 0},
        { "update-success", 0},
        { "update-timeout", 0},
        { "update-error", 1}
    };
    checkStats(stats_upd);
}

/// @brief Check GSS-TSIG DNS update succeeds.
TEST_F(GssTsigDNSUpdateTest, runGssTsigDNSUpdateSuccess) {
    string key_name("1234.sig-blu.example.nil.");
    key_.reset(new ManagedKey(key_name));
    DnsServerPtr server(new DnsServer("foo", {}, IOAddress(TEST_ADDRESS),
                                      TEST_PORT));
    server->setServerPrincipal("DNS/blu.example.nil@EXAMPLE.NIL");
    server->setKeyProto(IOFetch::Protocol::UDP);
    setKeytab();
    setAdministratorCCache();

    DNSCallback dns_callback = std::bind(&GssTsigDNSUpdateTest::doGssTsigDNSUpdate, this);
    NSUpdateTestCallback callback(io_service_, dns_callback);

    system_clock::time_point now = system_clock::now();
    key_->setInception(now);
    key_->setExpire(now + seconds(server->getKeyLifetime()));
    key_->getTKeyExchange().reset(new TKeyExchange(io_service_, server, key_,
                                                   &callback));
    key_->getTKeyExchange()->doExchange();

    // The server will sign both the TKEY and the DNS update.
    DummyDNSServer dns_server(io_service_);
    dns_server.start();
    io_service_->run();
    ASSERT_TRUE(success_);
    // Check statistics.
    StatMap stats_key = {
        { "update-sent", 1},
        { "update-success", 1},
        { "update-timeout", 0},
        { "update-error", 0}
    };
    checkStats(key_name, stats_key);
    StatMap stats_upd = {
        { "update-sent", 1},
        { "update-signed", 1},
        { "update-unsigned", 0},
        { "update-success", 1},
        { "update-timeout", 0},
        { "update-error", 0}
    };
    checkStats(stats_upd);
}

/// @brief Check GSS-TSIG DNS update succeeds.
TEST_F(GssTsigDNSUpdateTest, runGssTsigDNSUpdateSuccessWithFallback) {
    string key_name("1234.sig-blu.example.nil.");
    key_.reset(new ManagedKey(key_name));
    DnsServerPtr server(new DnsServer("foo", {}, IOAddress(TEST_ADDRESS),
                                      TEST_PORT));
    server->setServerPrincipal("DNS/blu.example.nil@EXAMPLE.NIL");
    server->setKeyProto(IOFetch::Protocol::UDP);
    use_fallback_ = true;
    setKeytab();
    setAdministratorCCache();

    DNSCallback dns_callback = std::bind(&GssTsigDNSUpdateTest::doGssTsigDNSUpdate, this);
    NSUpdateTestCallback callback(io_service_, dns_callback);

    system_clock::time_point now = system_clock::now();
    key_->setInception(now);
    key_->setExpire(now + seconds(server->getKeyLifetime()));
    key_->getTKeyExchange().reset(new TKeyExchange(io_service_, server, key_,
                                                   &callback));
    key_->getTKeyExchange()->doExchange();

    // The server will sign the TKEY, but not sign the DNS update.
    DummyDNSServer dns_server(io_service_, true, false);
    dns_server.start();
    io_service_->run();
    ASSERT_TRUE(success_);
    // Check statistics.
    StatMap stats_key = {
        { "update-sent", 0},
        { "update-success", 0},
        { "update-timeout", 0},
        { "update-error", 0}
    };
    checkStats(key_name, stats_key);
    StatMap stats_upd = {
        { "update-sent", 1},
        { "update-signed", 0},
        { "update-unsigned", 1},
        { "update-success", 1},
        { "update-timeout", 0},
        { "update-error", 0}
    };
    checkStats(stats_upd);
}

}