auth_srv_unittest.cc 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  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 <config.h>
  15. #include <util/io/sockaddr_util.h>
  16. #include <util/memory_segment_local.h>
  17. #include <dns/message.h>
  18. #include <dns/messagerenderer.h>
  19. #include <dns/name.h>
  20. #include <dns/opcode.h>
  21. #include <dns/rrclass.h>
  22. #include <dns/rrtype.h>
  23. #include <dns/rrttl.h>
  24. #include <dns/rdataclass.h>
  25. #include <dns/tsig.h>
  26. #include <server_common/portconfig.h>
  27. #include <server_common/keyring.h>
  28. #include <datasrc/memory_datasrc.h>
  29. #include <datasrc/client_list.h>
  30. #include <auth/auth_srv.h>
  31. #include <auth/command.h>
  32. #include <auth/common.h>
  33. #include <auth/statistics.h>
  34. #include <auth/datasrc_config.h>
  35. #include <util/unittests/mock_socketsession.h>
  36. #include <util/threads/lock.h>
  37. #include <dns/tests/unittest_util.h>
  38. #include <testutils/dnsmessage_test.h>
  39. #include <testutils/srv_test.h>
  40. #include <testutils/mockups.h>
  41. #include <testutils/portconfig.h>
  42. #include <testutils/socket_request.h>
  43. #include <gtest/gtest.h>
  44. #include <boost/lexical_cast.hpp>
  45. #include <boost/shared_ptr.hpp>
  46. #include <boost/scoped_ptr.hpp>
  47. #include <boost/foreach.hpp>
  48. #include <vector>
  49. #include <sys/types.h>
  50. #include <sys/socket.h>
  51. #include <netdb.h>
  52. using namespace std;
  53. using namespace isc::cc;
  54. using namespace isc::dns;
  55. using namespace isc::datasrc;
  56. using namespace isc::util;
  57. using namespace isc::util::io::internal;
  58. using namespace isc::util::unittests;
  59. using namespace isc::dns::rdata;
  60. using namespace isc::data;
  61. using namespace isc::xfr;
  62. using namespace isc::asiodns;
  63. using namespace isc::asiolink;
  64. using namespace isc::testutils;
  65. using namespace isc::server_common::portconfig;
  66. using isc::UnitTestUtil;
  67. using boost::scoped_ptr;
  68. namespace {
  69. const char* const CONFIG_TESTDB =
  70. "{\"database_file\": \"" TEST_DATA_DIR "/example.sqlite3\"}";
  71. // The following file must be non existent and must be non"creatable" (see
  72. // the sqlite3 test).
  73. const char* const BADCONFIG_TESTDB =
  74. "{ \"database_file\": \"" TEST_DATA_DIR "/nodir/notexist\"}";
  75. const char* const STATIC_DSRC_FILE = DSRC_DIR "/static.zone";
  76. // This is a configuration that uses the in-memory data source containing
  77. // a signed example zone.
  78. const char* const CONFIG_INMEMORY_EXAMPLE = TEST_DATA_DIR "/rfc5155-example.zone.signed";
  79. // shortcut commonly used in tests
  80. typedef boost::shared_ptr<ConfigurableClientList> ListPtr;
  81. class AuthSrvTest : public SrvTestBase {
  82. protected:
  83. AuthSrvTest() :
  84. dnss_(),
  85. server(xfrout, ddns_forwarder),
  86. // The empty string is expected value of the parameter of
  87. // requestSocket, not the app_name (there's no fallback, it checks
  88. // the empty string is passed).
  89. sock_requestor_(dnss_, address_store_, 53210, "")
  90. {
  91. server.setDNSService(dnss_);
  92. server.setXfrinSession(&notify_session);
  93. server.createDDNSForwarder();
  94. }
  95. ~AuthSrvTest() {
  96. server.destroyDDNSForwarder();
  97. }
  98. virtual void processMessage() {
  99. // If processMessage has been called before, parse_message needs
  100. // to be reset. If it hasn't, there's no harm in doing so
  101. parse_message->clear(Message::PARSE);
  102. server.processMessage(*io_message, *parse_message, *response_obuffer,
  103. &dnsserv);
  104. }
  105. // Helper for checking Rcode statistic counters;
  106. // Checks for one specific Rcode statistics counter value
  107. void checkRcodeCounter(const Rcode& rcode, int expected_value) const {
  108. EXPECT_EQ(expected_value, server.getCounter(rcode)) <<
  109. "Expected Rcode count for " << rcode.toText() <<
  110. " " << expected_value << ", was: " <<
  111. server.getCounter(rcode);
  112. }
  113. // Checks whether all Rcode counters are set to zero
  114. void checkAllRcodeCountersZero() const {
  115. for (int i = 0; i < 17; i++) {
  116. checkRcodeCounter(Rcode(i), 0);
  117. }
  118. }
  119. // Checks whether all Rcode counters are set to zero except the given
  120. // rcode (it is checked to be set to 'value')
  121. void checkAllRcodeCountersZeroExcept(const Rcode& rcode, int value) const {
  122. for (int i = 0; i < 17; i++) {
  123. const Rcode rc(i);
  124. if (rc == rcode) {
  125. checkRcodeCounter(Rcode(i), value);
  126. } else {
  127. checkRcodeCounter(Rcode(i), 0);
  128. }
  129. }
  130. }
  131. // Convenience method for tests that expect to return SERVFAIL
  132. // It calls processMessage, checks if there is an answer, and
  133. // check the header for default SERVFAIL data
  134. void processAndCheckSERVFAIL() {
  135. processMessage();
  136. EXPECT_TRUE(dnsserv.hasAnswer());
  137. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  138. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  139. }
  140. // Convenient shortcut of creating a simple request and having the
  141. // server process it.
  142. void createAndSendRequest(RRType req_type, Opcode opcode = Opcode::QUERY(),
  143. const Name& req_name = Name("example.com"),
  144. RRClass req_class = RRClass::IN(),
  145. int protocol = IPPROTO_UDP,
  146. const char* const remote_address =
  147. DEFAULT_REMOTE_ADDRESS,
  148. uint16_t remote_port = DEFAULT_REMOTE_PORT)
  149. {
  150. UnitTestUtil::createRequestMessage(request_message, opcode,
  151. default_qid, req_name,
  152. req_class, req_type);
  153. createRequestPacket(request_message, protocol, NULL,
  154. remote_address, remote_port);
  155. parse_message->clear(Message::PARSE);
  156. server.processMessage(*io_message, *parse_message, *response_obuffer,
  157. &dnsserv);
  158. }
  159. MockDNSService dnss_;
  160. MockXfroutClient xfrout;
  161. MockSocketSessionForwarder ddns_forwarder;
  162. AuthSrv server;
  163. vector<uint8_t> response_data;
  164. AddressList address_store_;
  165. TestSocketRequestor sock_requestor_;
  166. };
  167. // A helper function that builds a response to version.bind/TXT/CH that
  168. // should be identical to the response from our builtin (static) data source
  169. // by default. The resulting wire-format data will be stored in 'data'.
  170. void
  171. createBuiltinVersionResponse(const qid_t qid, vector<uint8_t>& data) {
  172. const Name version_name("VERSION.BIND.");
  173. const Name apex_name("BIND.");
  174. Message message(Message::RENDER);
  175. UnitTestUtil::createRequestMessage(message, Opcode::QUERY(),
  176. qid, version_name,
  177. RRClass::CH(), RRType::TXT());
  178. message.setHeaderFlag(Message::HEADERFLAG_QR);
  179. message.setHeaderFlag(Message::HEADERFLAG_AA);
  180. RRsetPtr rrset_version = RRsetPtr(new RRset(version_name, RRClass::CH(),
  181. RRType::TXT(), RRTTL(0)));
  182. rrset_version->addRdata(generic::TXT(PACKAGE_STRING));
  183. message.addRRset(Message::SECTION_ANSWER, rrset_version);
  184. RRsetPtr rrset_version_ns = RRsetPtr(new RRset(apex_name, RRClass::CH(),
  185. RRType::NS(), RRTTL(0)));
  186. rrset_version_ns->addRdata(generic::NS(apex_name));
  187. message.addRRset(Message::SECTION_AUTHORITY, rrset_version_ns);
  188. MessageRenderer renderer;
  189. message.toWire(renderer);
  190. data.clear();
  191. data.assign(static_cast<const uint8_t*>(renderer.getData()),
  192. static_cast<const uint8_t*>(renderer.getData()) +
  193. renderer.getLength());
  194. }
  195. // We did not configure any client lists. Therefore it should be REFUSED
  196. TEST_F(AuthSrvTest, noClientList) {
  197. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  198. default_qid, Name("version.bind"),
  199. RRClass::CH(), RRType::TXT());
  200. createRequestPacket(request_message, IPPROTO_UDP);
  201. server.processMessage(*io_message, *parse_message, *response_obuffer,
  202. &dnsserv);
  203. EXPECT_TRUE(dnsserv.hasAnswer());
  204. headerCheck(*parse_message, default_qid, Rcode::REFUSED(),
  205. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  206. }
  207. // Unsupported requests. Should result in NOTIMP.
  208. TEST_F(AuthSrvTest, unsupportedRequest) {
  209. unsupportedRequest();
  210. // unsupportedRequest tries 13 different opcodes
  211. checkAllRcodeCountersZeroExcept(Rcode::NOTIMP(), 13);
  212. }
  213. // Multiple questions. Should result in FORMERR.
  214. TEST_F(AuthSrvTest, multiQuestion) {
  215. multiQuestion();
  216. checkAllRcodeCountersZeroExcept(Rcode::FORMERR(), 1);
  217. }
  218. // Incoming data doesn't even contain the complete header. Must be silently
  219. // dropped.
  220. TEST_F(AuthSrvTest, shortMessage) {
  221. shortMessage();
  222. checkAllRcodeCountersZero();
  223. }
  224. // Response messages. Must be silently dropped, whether it's a valid response
  225. // or malformed or could otherwise cause a protocol error.
  226. TEST_F(AuthSrvTest, response) {
  227. response();
  228. checkAllRcodeCountersZero();
  229. }
  230. // Query with a broken question
  231. TEST_F(AuthSrvTest, shortQuestion) {
  232. shortQuestion();
  233. checkAllRcodeCountersZeroExcept(Rcode::FORMERR(), 1);
  234. }
  235. // Query with a broken answer section
  236. TEST_F(AuthSrvTest, shortAnswer) {
  237. shortAnswer();
  238. checkAllRcodeCountersZeroExcept(Rcode::FORMERR(), 1);
  239. }
  240. // Query with unsupported version of EDNS.
  241. TEST_F(AuthSrvTest, ednsBadVers) {
  242. ednsBadVers();
  243. checkAllRcodeCountersZeroExcept(Rcode::BADVERS(), 1);
  244. }
  245. TEST_F(AuthSrvTest, AXFROverUDP) {
  246. axfrOverUDP();
  247. }
  248. TEST_F(AuthSrvTest, AXFRSuccess) {
  249. EXPECT_FALSE(xfrout.isConnected());
  250. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  251. Name("example.com"), RRClass::IN(),
  252. RRType::AXFR());
  253. createRequestPacket(request_message, IPPROTO_TCP);
  254. // On success, the AXFR query has been passed to a separate process,
  255. // so we shouldn't have to respond.
  256. server.processMessage(*io_message, *parse_message, *response_obuffer,
  257. &dnsserv);
  258. EXPECT_FALSE(dnsserv.hasAnswer());
  259. EXPECT_TRUE(xfrout.isConnected());
  260. checkAllRcodeCountersZero();
  261. }
  262. // Give the server a signed request, but don't give it the key. It will
  263. // not be able to verify it, returning BADKEY
  264. TEST_F(AuthSrvTest, TSIGSignedBadKey) {
  265. TSIGKey key("key:c2VjcmV0Cg==:hmac-sha1");
  266. TSIGContext context(key);
  267. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  268. Name("version.bind"), RRClass::CH(),
  269. RRType::TXT());
  270. createRequestPacket(request_message, IPPROTO_UDP, &context);
  271. // Process the message, but use a different key there
  272. boost::shared_ptr<TSIGKeyRing> keyring(new TSIGKeyRing);
  273. server.setTSIGKeyRing(&keyring);
  274. server.processMessage(*io_message, *parse_message, *response_obuffer,
  275. &dnsserv);
  276. EXPECT_TRUE(dnsserv.hasAnswer());
  277. headerCheck(*parse_message, default_qid, TSIGError::BAD_KEY().toRcode(),
  278. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  279. // We need to parse the message ourself, or getTSIGRecord won't work
  280. InputBuffer ib(response_obuffer->getData(), response_obuffer->getLength());
  281. Message m(Message::PARSE);
  282. m.fromWire(ib);
  283. const TSIGRecord* tsig = m.getTSIGRecord();
  284. ASSERT_TRUE(tsig != NULL) <<
  285. "Missing TSIG signature (we should have one even at error)";
  286. EXPECT_EQ(TSIGError::BAD_KEY_CODE, tsig->getRdata().getError());
  287. EXPECT_EQ(0, tsig->getRdata().getMACSize()) <<
  288. "It should be unsigned with this error";
  289. checkAllRcodeCountersZeroExcept(Rcode::NOTAUTH(), 1);
  290. }
  291. // Give the server a signed request, but signed by a different key
  292. // (with the same name). It should return BADSIG
  293. TEST_F(AuthSrvTest, TSIGBadSig) {
  294. TSIGKey key("key:c2VjcmV0Cg==:hmac-sha1");
  295. TSIGContext context(key);
  296. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  297. Name("version.bind"), RRClass::CH(),
  298. RRType::TXT());
  299. createRequestPacket(request_message, IPPROTO_UDP, &context);
  300. // Process the message, but use a different key there
  301. boost::shared_ptr<TSIGKeyRing> keyring(new TSIGKeyRing);
  302. keyring->add(TSIGKey("key:QkFECg==:hmac-sha1"));
  303. server.setTSIGKeyRing(&keyring);
  304. server.processMessage(*io_message, *parse_message, *response_obuffer,
  305. &dnsserv);
  306. EXPECT_TRUE(dnsserv.hasAnswer());
  307. headerCheck(*parse_message, default_qid, TSIGError::BAD_SIG().toRcode(),
  308. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  309. // We need to parse the message ourself, or getTSIGRecord won't work
  310. InputBuffer ib(response_obuffer->getData(), response_obuffer->getLength());
  311. Message m(Message::PARSE);
  312. m.fromWire(ib);
  313. const TSIGRecord* tsig = m.getTSIGRecord();
  314. ASSERT_TRUE(tsig != NULL) <<
  315. "Missing TSIG signature (we should have one even at error)";
  316. EXPECT_EQ(TSIGError::BAD_SIG_CODE, tsig->getRdata().getError());
  317. EXPECT_EQ(0, tsig->getRdata().getMACSize()) <<
  318. "It should be unsigned with this error";
  319. checkAllRcodeCountersZeroExcept(Rcode::NOTAUTH(), 1);
  320. }
  321. // Give the server a signed unsupported request with a bad signature.
  322. // This checks the server first verifies the signature before anything
  323. // else.
  324. TEST_F(AuthSrvTest, TSIGCheckFirst) {
  325. TSIGKey key("key:c2VjcmV0Cg==:hmac-sha1");
  326. TSIGContext context(key);
  327. // Pass a wrong opcode there. The server shouldn't know what to do
  328. // about it.
  329. UnitTestUtil::createRequestMessage(request_message, Opcode::RESERVED14(),
  330. default_qid, Name("version.bind"),
  331. RRClass::CH(), RRType::TXT());
  332. createRequestPacket(request_message, IPPROTO_UDP, &context);
  333. // Process the message, but use a different key there
  334. boost::shared_ptr<TSIGKeyRing> keyring(new TSIGKeyRing);
  335. keyring->add(TSIGKey("key:QkFECg==:hmac-sha1"));
  336. server.setTSIGKeyRing(&keyring);
  337. server.processMessage(*io_message, *parse_message, *response_obuffer,
  338. &dnsserv);
  339. EXPECT_TRUE(dnsserv.hasAnswer());
  340. headerCheck(*parse_message, default_qid, TSIGError::BAD_SIG().toRcode(),
  341. Opcode::RESERVED14().getCode(), QR_FLAG, 0, 0, 0, 0);
  342. // We need to parse the message ourself, or getTSIGRecord won't work
  343. InputBuffer ib(response_obuffer->getData(), response_obuffer->getLength());
  344. Message m(Message::PARSE);
  345. m.fromWire(ib);
  346. const TSIGRecord* tsig = m.getTSIGRecord();
  347. ASSERT_TRUE(tsig != NULL) <<
  348. "Missing TSIG signature (we should have one even at error)";
  349. EXPECT_EQ(TSIGError::BAD_SIG_CODE, tsig->getRdata().getError());
  350. EXPECT_EQ(0, tsig->getRdata().getMACSize()) <<
  351. "It should be unsigned with this error";
  352. // TSIG should have failed, and so the per opcode counter shouldn't be
  353. // incremented.
  354. EXPECT_EQ(0, server.getCounter(Opcode::RESERVED14()));
  355. checkAllRcodeCountersZeroExcept(Rcode::NOTAUTH(), 1);
  356. }
  357. TEST_F(AuthSrvTest, AXFRConnectFail) {
  358. EXPECT_FALSE(xfrout.isConnected()); // check prerequisite
  359. xfrout.disableConnect();
  360. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  361. Name("example.com"), RRClass::IN(),
  362. RRType::AXFR());
  363. createRequestPacket(request_message, IPPROTO_TCP);
  364. server.processMessage(*io_message, *parse_message, *response_obuffer,
  365. &dnsserv);
  366. EXPECT_TRUE(dnsserv.hasAnswer());
  367. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  368. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  369. EXPECT_FALSE(xfrout.isConnected());
  370. }
  371. TEST_F(AuthSrvTest, AXFRSendFail) {
  372. // first send a valid query, making the connection with the xfr process
  373. // open.
  374. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  375. Name("example.com"), RRClass::IN(),
  376. RRType::AXFR());
  377. createRequestPacket(request_message, IPPROTO_TCP);
  378. server.processMessage(*io_message, *parse_message, *response_obuffer,
  379. &dnsserv);
  380. EXPECT_TRUE(xfrout.isConnected());
  381. xfrout.disableSend();
  382. parse_message->clear(Message::PARSE);
  383. response_obuffer->clear();
  384. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  385. Name("example.com"), RRClass::IN(),
  386. RRType::AXFR());
  387. createRequestPacket(request_message, IPPROTO_TCP);
  388. server.processMessage(*io_message, *parse_message, *response_obuffer,
  389. &dnsserv);
  390. EXPECT_TRUE(dnsserv.hasAnswer());
  391. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  392. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  393. // The connection should have been closed due to the send failure.
  394. EXPECT_FALSE(xfrout.isConnected());
  395. }
  396. TEST_F(AuthSrvTest, AXFRDisconnectFail) {
  397. // In our usage disconnect() shouldn't fail. But even if it does,
  398. // it should not disrupt service (so processMessage should have caught it)
  399. xfrout.disableSend();
  400. xfrout.disableDisconnect();
  401. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  402. Name("example.com"), RRClass::IN(),
  403. RRType::AXFR());
  404. createRequestPacket(request_message, IPPROTO_TCP);
  405. EXPECT_NO_THROW(server.processMessage(*io_message, *parse_message,
  406. *response_obuffer, &dnsserv));
  407. // Since the disconnect failed, we should still be 'connected'
  408. EXPECT_TRUE(xfrout.isConnected());
  409. // XXX: we need to re-enable disconnect. otherwise an exception would be
  410. // thrown via the destructor of the server.
  411. xfrout.enableDisconnect();
  412. }
  413. TEST_F(AuthSrvTest, IXFRConnectFail) {
  414. EXPECT_FALSE(xfrout.isConnected()); // check prerequisite
  415. xfrout.disableConnect();
  416. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  417. Name("example.com"), RRClass::IN(),
  418. RRType::IXFR());
  419. createRequestPacket(request_message, IPPROTO_TCP);
  420. server.processMessage(*io_message, *parse_message, *response_obuffer,
  421. &dnsserv);
  422. EXPECT_TRUE(dnsserv.hasAnswer());
  423. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  424. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  425. EXPECT_FALSE(xfrout.isConnected());
  426. }
  427. TEST_F(AuthSrvTest, IXFRSendFail) {
  428. // first send a valid query, making the connection with the xfr process
  429. // open.
  430. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  431. Name("example.com"), RRClass::IN(),
  432. RRType::IXFR());
  433. createRequestPacket(request_message, IPPROTO_TCP);
  434. server.processMessage(*io_message, *parse_message, *response_obuffer,
  435. &dnsserv);
  436. EXPECT_TRUE(xfrout.isConnected());
  437. xfrout.disableSend();
  438. parse_message->clear(Message::PARSE);
  439. response_obuffer->clear();
  440. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  441. Name("example.com"), RRClass::IN(),
  442. RRType::IXFR());
  443. createRequestPacket(request_message, IPPROTO_TCP);
  444. server.processMessage(*io_message, *parse_message, *response_obuffer,
  445. &dnsserv);
  446. EXPECT_TRUE(dnsserv.hasAnswer());
  447. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  448. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  449. // The connection should have been closed due to the send failure.
  450. EXPECT_FALSE(xfrout.isConnected());
  451. }
  452. TEST_F(AuthSrvTest, IXFRDisconnectFail) {
  453. // In our usage disconnect() shouldn't fail, but even if it does,
  454. // procesMessage() should catch it.
  455. xfrout.disableSend();
  456. xfrout.disableDisconnect();
  457. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  458. Name("example.com"), RRClass::IN(),
  459. RRType::IXFR());
  460. createRequestPacket(request_message, IPPROTO_TCP);
  461. EXPECT_NO_THROW(server.processMessage(*io_message, *parse_message,
  462. *response_obuffer, &dnsserv));
  463. EXPECT_TRUE(xfrout.isConnected());
  464. // XXX: we need to re-enable disconnect. otherwise an exception would be
  465. // thrown via the destructor of the server.
  466. xfrout.enableDisconnect();
  467. }
  468. TEST_F(AuthSrvTest, notify) {
  469. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  470. default_qid, Name("example.com"),
  471. RRClass::IN(), RRType::SOA());
  472. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  473. createRequestPacket(request_message, IPPROTO_UDP);
  474. server.processMessage(*io_message, *parse_message, *response_obuffer,
  475. &dnsserv);
  476. EXPECT_TRUE(dnsserv.hasAnswer());
  477. // An internal command message should have been created and sent to an
  478. // external module. Check them.
  479. EXPECT_EQ("Zonemgr", notify_session.getMessageDest());
  480. EXPECT_EQ("notify",
  481. notify_session.getSentMessage()->get("command")->get(0)->stringValue());
  482. ConstElementPtr notify_args =
  483. notify_session.getSentMessage()->get("command")->get(1);
  484. EXPECT_EQ("example.com.", notify_args->get("zone_name")->stringValue());
  485. EXPECT_EQ(DEFAULT_REMOTE_ADDRESS,
  486. notify_args->get("master")->stringValue());
  487. EXPECT_EQ("IN", notify_args->get("zone_class")->stringValue());
  488. // On success, the server should return a response to the notify.
  489. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  490. Opcode::NOTIFY().getCode(), QR_FLAG | AA_FLAG, 1, 0, 0, 0);
  491. // The question must be identical to that of the received notify
  492. ConstQuestionPtr question = *parse_message->beginQuestion();
  493. EXPECT_EQ(Name("example.com"), question->getName());
  494. EXPECT_EQ(RRClass::IN(), question->getClass());
  495. EXPECT_EQ(RRType::SOA(), question->getType());
  496. checkAllRcodeCountersZeroExcept(Rcode::NOERROR(), 1);
  497. }
  498. TEST_F(AuthSrvTest, notifyForCHClass) {
  499. // Same as the previous test, but for the CH RRClass.
  500. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  501. default_qid, Name("example.com"),
  502. RRClass::CH(), RRType::SOA());
  503. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  504. createRequestPacket(request_message, IPPROTO_UDP);
  505. server.processMessage(*io_message, *parse_message, *response_obuffer,
  506. &dnsserv);
  507. EXPECT_TRUE(dnsserv.hasAnswer());
  508. // Other conditions should be the same, so simply confirm the RR class is
  509. // set correctly.
  510. ConstElementPtr notify_args =
  511. notify_session.getSentMessage()->get("command")->get(1);
  512. EXPECT_EQ("CH", notify_args->get("zone_class")->stringValue());
  513. }
  514. TEST_F(AuthSrvTest, notifyEmptyQuestion) {
  515. request_message.clear(Message::RENDER);
  516. request_message.setOpcode(Opcode::NOTIFY());
  517. request_message.setRcode(Rcode::NOERROR());
  518. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  519. request_message.setQid(default_qid);
  520. request_message.toWire(request_renderer);
  521. createRequestPacket(request_message, IPPROTO_UDP);
  522. server.processMessage(*io_message, *parse_message, *response_obuffer,
  523. &dnsserv);
  524. EXPECT_TRUE(dnsserv.hasAnswer());
  525. headerCheck(*parse_message, default_qid, Rcode::FORMERR(),
  526. Opcode::NOTIFY().getCode(), QR_FLAG, 0, 0, 0, 0);
  527. }
  528. TEST_F(AuthSrvTest, notifyMultiQuestions) {
  529. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  530. default_qid, Name("example.com"),
  531. RRClass::IN(), RRType::SOA());
  532. // add one more SOA question
  533. request_message.addQuestion(Question(Name("example.com"), RRClass::IN(),
  534. RRType::SOA()));
  535. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  536. createRequestPacket(request_message, IPPROTO_UDP);
  537. server.processMessage(*io_message, *parse_message, *response_obuffer,
  538. &dnsserv);
  539. EXPECT_TRUE(dnsserv.hasAnswer());
  540. headerCheck(*parse_message, default_qid, Rcode::FORMERR(),
  541. Opcode::NOTIFY().getCode(), QR_FLAG, 2, 0, 0, 0);
  542. }
  543. TEST_F(AuthSrvTest, notifyNonSOAQuestion) {
  544. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  545. default_qid, Name("example.com"),
  546. RRClass::IN(), RRType::NS());
  547. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  548. createRequestPacket(request_message, IPPROTO_UDP);
  549. server.processMessage(*io_message, *parse_message, *response_obuffer,
  550. &dnsserv);
  551. EXPECT_TRUE(dnsserv.hasAnswer());
  552. headerCheck(*parse_message, default_qid, Rcode::FORMERR(),
  553. Opcode::NOTIFY().getCode(), QR_FLAG, 1, 0, 0, 0);
  554. }
  555. TEST_F(AuthSrvTest, notifyWithoutAA) {
  556. // implicitly leave the AA bit off. our implementation will accept it.
  557. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  558. default_qid, Name("example.com"),
  559. RRClass::IN(), RRType::SOA());
  560. createRequestPacket(request_message, IPPROTO_UDP);
  561. server.processMessage(*io_message, *parse_message, *response_obuffer,
  562. &dnsserv);
  563. EXPECT_TRUE(dnsserv.hasAnswer());
  564. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  565. Opcode::NOTIFY().getCode(), QR_FLAG | AA_FLAG, 1, 0, 0, 0);
  566. }
  567. TEST_F(AuthSrvTest, notifyWithErrorRcode) {
  568. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  569. default_qid, Name("example.com"),
  570. RRClass::IN(), RRType::SOA());
  571. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  572. request_message.setRcode(Rcode::SERVFAIL());
  573. createRequestPacket(request_message, IPPROTO_UDP);
  574. server.processMessage(*io_message, *parse_message, *response_obuffer,
  575. &dnsserv);
  576. EXPECT_TRUE(dnsserv.hasAnswer());
  577. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  578. Opcode::NOTIFY().getCode(), QR_FLAG | AA_FLAG, 1, 0, 0, 0);
  579. }
  580. TEST_F(AuthSrvTest, notifyWithoutSession) {
  581. server.setXfrinSession(NULL);
  582. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  583. default_qid, Name("example.com"),
  584. RRClass::IN(), RRType::SOA());
  585. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  586. createRequestPacket(request_message, IPPROTO_UDP);
  587. // we simply ignore the notify and let it be resent if an internal error
  588. // happens.
  589. server.processMessage(*io_message, *parse_message, *response_obuffer,
  590. &dnsserv);
  591. EXPECT_FALSE(dnsserv.hasAnswer());
  592. }
  593. TEST_F(AuthSrvTest, notifySendFail) {
  594. notify_session.disableSend();
  595. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  596. default_qid, Name("example.com"),
  597. RRClass::IN(), RRType::SOA());
  598. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  599. createRequestPacket(request_message, IPPROTO_UDP);
  600. server.processMessage(*io_message, *parse_message, *response_obuffer,
  601. &dnsserv);
  602. EXPECT_FALSE(dnsserv.hasAnswer());
  603. }
  604. TEST_F(AuthSrvTest, notifyReceiveFail) {
  605. notify_session.disableReceive();
  606. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  607. default_qid, Name("example.com"),
  608. RRClass::IN(), RRType::SOA());
  609. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  610. createRequestPacket(request_message, IPPROTO_UDP);
  611. server.processMessage(*io_message, *parse_message, *response_obuffer,
  612. &dnsserv);
  613. EXPECT_FALSE(dnsserv.hasAnswer());
  614. }
  615. TEST_F(AuthSrvTest, notifyWithBogusSessionMessage) {
  616. notify_session.setMessage(Element::fromJSON("{\"foo\": 1}"));
  617. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  618. default_qid, Name("example.com"),
  619. RRClass::IN(), RRType::SOA());
  620. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  621. createRequestPacket(request_message, IPPROTO_UDP);
  622. server.processMessage(*io_message, *parse_message, *response_obuffer,
  623. &dnsserv);
  624. EXPECT_FALSE(dnsserv.hasAnswer());
  625. }
  626. TEST_F(AuthSrvTest, notifyWithSessionMessageError) {
  627. notify_session.setMessage(
  628. Element::fromJSON("{\"result\": [1, \"FAIL\"]}"));
  629. UnitTestUtil::createRequestMessage(request_message, Opcode::NOTIFY(),
  630. default_qid, Name("example.com"),
  631. RRClass::IN(), RRType::SOA());
  632. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  633. createRequestPacket(request_message, IPPROTO_UDP);
  634. server.processMessage(*io_message, *parse_message, *response_obuffer,
  635. &dnsserv);
  636. EXPECT_FALSE(dnsserv.hasAnswer());
  637. }
  638. void
  639. installDataSrcClientLists(AuthSrv& server,
  640. AuthSrv::DataSrcClientListsPtr lists)
  641. {
  642. thread::Mutex::Locker locker(server.getClientListMutex());
  643. server.swapDataSrcClientLists(lists);
  644. }
  645. void
  646. updateDatabase(AuthSrv& server, const char* params) {
  647. const ConstElementPtr config(Element::fromJSON("{"
  648. "\"IN\": [{"
  649. " \"type\": \"sqlite3\","
  650. " \"params\": " + string(params) +
  651. "}]}"));
  652. installDataSrcClientLists(server, configureDataSource(server, config));
  653. }
  654. void
  655. updateInMemory(AuthSrv& server, const char* origin, const char* filename) {
  656. const ConstElementPtr config(Element::fromJSON("{"
  657. "\"IN\": [{"
  658. " \"type\": \"MasterFiles\","
  659. " \"params\": {"
  660. " \"" + string(origin) + "\": \"" + string(filename) + "\""
  661. " },"
  662. " \"cache-enable\": true"
  663. "}],"
  664. "\"CH\": [{"
  665. " \"type\": \"static\","
  666. " \"params\": \"" + string(STATIC_DSRC_FILE) + "\""
  667. "}]}"));
  668. installDataSrcClientLists(server, configureDataSource(server, config));
  669. }
  670. void
  671. updateBuiltin(AuthSrv& server) {
  672. const ConstElementPtr config(Element::fromJSON("{"
  673. "\"CH\": [{"
  674. " \"type\": \"static\","
  675. " \"params\": \"" + string(STATIC_DSRC_FILE) + "\""
  676. "}]}"));
  677. installDataSrcClientLists(server, configureDataSource(server, config));
  678. }
  679. // Try giving the server a TSIG signed request and see it can anwer signed as
  680. // well
  681. #ifdef USE_STATIC_LINK
  682. TEST_F(AuthSrvTest, DISABLED_TSIGSigned) { // Needs builtin
  683. #else
  684. TEST_F(AuthSrvTest, TSIGSigned) {
  685. #endif
  686. // Prepare key, the client message, etc
  687. updateBuiltin(server);
  688. const TSIGKey key("key:c2VjcmV0Cg==:hmac-sha1");
  689. TSIGContext context(key);
  690. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  691. Name("VERSION.BIND."), RRClass::CH(),
  692. RRType::TXT());
  693. createRequestPacket(request_message, IPPROTO_UDP, &context);
  694. // Run the message through the server
  695. boost::shared_ptr<TSIGKeyRing> keyring(new TSIGKeyRing);
  696. keyring->add(key);
  697. server.setTSIGKeyRing(&keyring);
  698. server.processMessage(*io_message, *parse_message, *response_obuffer,
  699. &dnsserv);
  700. // What did we get?
  701. EXPECT_TRUE(dnsserv.hasAnswer());
  702. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  703. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 1, 0);
  704. // We need to parse the message ourself, or getTSIGRecord won't work
  705. InputBuffer ib(response_obuffer->getData(), response_obuffer->getLength());
  706. Message m(Message::PARSE);
  707. m.fromWire(ib);
  708. const TSIGRecord* tsig = m.getTSIGRecord();
  709. ASSERT_TRUE(tsig != NULL) << "Missing TSIG signature";
  710. TSIGError error(context.verify(tsig, response_obuffer->getData(),
  711. response_obuffer->getLength()));
  712. EXPECT_EQ(TSIGError::NOERROR(), error) <<
  713. "The server signed the response, but it doesn't seem to be valid";
  714. checkAllRcodeCountersZeroExcept(Rcode::NOERROR(), 1);
  715. }
  716. // Same test emulating the UDPServer class behavior (defined in libasiolink).
  717. // This is not a good test in that it assumes internal implementation details
  718. // of UDPServer, but we've encountered a regression due to the introduction
  719. // of that class, so we add a test for that case to prevent such a regression
  720. // in future.
  721. // Besides, the generalization of UDPServer is probably too much for the
  722. // authoritative only server in terms of performance, and it's quite likely
  723. // we need to drop it for the authoritative server implementation.
  724. // At that point we can drop this test, too.
  725. #ifdef USE_STATIC_LINK
  726. TEST_F(AuthSrvTest, DISABLED_builtInQueryViaDNSServer) {
  727. #else
  728. TEST_F(AuthSrvTest, builtInQueryViaDNSServer) {
  729. #endif
  730. updateBuiltin(server);
  731. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  732. default_qid, Name("VERSION.BIND."),
  733. RRClass::CH(), RRType::TXT());
  734. createRequestPacket(request_message, IPPROTO_UDP);
  735. (*server.getDNSLookupProvider())(*io_message, parse_message,
  736. response_message,
  737. response_obuffer, &dnsserv);
  738. (*server.getDNSAnswerProvider())(*io_message, parse_message,
  739. response_message, response_obuffer);
  740. createBuiltinVersionResponse(default_qid, response_data);
  741. EXPECT_PRED_FORMAT4(UnitTestUtil::matchWireData,
  742. response_obuffer->getData(),
  743. response_obuffer->getLength(),
  744. &response_data[0], response_data.size());
  745. // After it has been run, the message should be cleared
  746. EXPECT_EQ(0, parse_message->getRRCount(Message::SECTION_QUESTION));
  747. }
  748. // In the following tests we confirm the response data is rendered in
  749. // wire format in the expected way.
  750. // The most primitive check: checking the result of the processMessage()
  751. // method
  752. #ifdef USE_STATIC_LINK
  753. TEST_F(AuthSrvTest, DISABLED_builtInQuery) {
  754. #else
  755. TEST_F(AuthSrvTest, builtInQuery) {
  756. #endif
  757. updateBuiltin(server);
  758. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  759. default_qid, Name("VERSION.BIND."),
  760. RRClass::CH(), RRType::TXT());
  761. createRequestPacket(request_message, IPPROTO_UDP);
  762. server.processMessage(*io_message, *parse_message, *response_obuffer,
  763. &dnsserv);
  764. createBuiltinVersionResponse(default_qid, response_data);
  765. EXPECT_PRED_FORMAT4(UnitTestUtil::matchWireData,
  766. response_obuffer->getData(),
  767. response_obuffer->getLength(),
  768. &response_data[0], response_data.size());
  769. checkAllRcodeCountersZeroExcept(Rcode::NOERROR(), 1);
  770. }
  771. // Same type of test as builtInQueryViaDNSServer but for an error response.
  772. #ifdef USE_STATIC_LINK
  773. TEST_F(AuthSrvTest, DISABLED_iqueryViaDNSServer) { // Needs builtin
  774. #else
  775. TEST_F(AuthSrvTest, iqueryViaDNSServer) { // Needs builtin
  776. #endif
  777. updateBuiltin(server);
  778. createDataFromFile("iquery_fromWire.wire");
  779. (*server.getDNSLookupProvider())(*io_message, parse_message,
  780. response_message,
  781. response_obuffer, &dnsserv);
  782. (*server.getDNSAnswerProvider())(*io_message, parse_message,
  783. response_message, response_obuffer);
  784. UnitTestUtil::readWireData("iquery_response_fromWire.wire",
  785. response_data);
  786. EXPECT_PRED_FORMAT4(UnitTestUtil::matchWireData,
  787. response_obuffer->getData(),
  788. response_obuffer->getLength(),
  789. &response_data[0], response_data.size());
  790. }
  791. // Install a Sqlite3 data source with testing data.
  792. #ifdef USE_STATIC_LINK
  793. TEST_F(AuthSrvTest, DISABLED_updateConfig) {
  794. #else
  795. TEST_F(AuthSrvTest, updateConfig) {
  796. #endif
  797. updateDatabase(server, CONFIG_TESTDB);
  798. // query for existent data in the installed data source. The resulting
  799. // response should have the AA flag on, and have an RR in each answer
  800. // and authority section.
  801. createDataFromFile("examplequery_fromWire.wire");
  802. server.processMessage(*io_message, *parse_message, *response_obuffer,
  803. &dnsserv);
  804. EXPECT_TRUE(dnsserv.hasAnswer());
  805. headerCheck(*parse_message, default_qid, Rcode::NOERROR(), opcode.getCode(),
  806. QR_FLAG | AA_FLAG, 1, 1, 1, 0);
  807. }
  808. #ifdef USE_STATIC_LINK
  809. TEST_F(AuthSrvTest, DISABLED_datasourceFail) {
  810. #else
  811. TEST_F(AuthSrvTest, datasourceFail) {
  812. #endif
  813. updateDatabase(server, CONFIG_TESTDB);
  814. // This query will hit a corrupted entry of the data source (the zoneload
  815. // tool and the data source itself naively accept it). This will result
  816. // in a SERVFAIL response, and the answer and authority sections should
  817. // be empty.
  818. createDataFromFile("badExampleQuery_fromWire.wire");
  819. server.processMessage(*io_message, *parse_message, *response_obuffer,
  820. &dnsserv);
  821. EXPECT_TRUE(dnsserv.hasAnswer());
  822. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  823. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  824. }
  825. #ifdef USE_STATIC_LINK
  826. TEST_F(AuthSrvTest, DISABLED_updateConfigFail) {
  827. #else
  828. TEST_F(AuthSrvTest, updateConfigFail) {
  829. #endif
  830. // First, load a valid data source.
  831. updateDatabase(server, CONFIG_TESTDB);
  832. // Next, try to update it with a non-existent one. This should fail.
  833. EXPECT_THROW(updateDatabase(server, BADCONFIG_TESTDB),
  834. isc::datasrc::DataSourceError);
  835. // The original data source should still exist.
  836. createDataFromFile("examplequery_fromWire.wire");
  837. server.processMessage(*io_message, *parse_message, *response_obuffer,
  838. &dnsserv);
  839. EXPECT_TRUE(dnsserv.hasAnswer());
  840. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  841. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 1, 0);
  842. }
  843. TEST_F(AuthSrvTest, updateWithInMemoryClient) {
  844. // Test configuring memory data source. Detailed test cases are covered
  845. // in the configuration tests. We only check the AuthSrv interface here.
  846. // Create an empty in-memory
  847. const ConstElementPtr config(Element::fromJSON("{"
  848. "\"IN\": [{"
  849. " \"type\": \"MasterFiles\","
  850. " \"params\": {},"
  851. " \"cache-enable\": true"
  852. "}]}"));
  853. installDataSrcClientLists(server, configureDataSource(server, config));
  854. // after successful configuration, we should have one (with empty zoneset).
  855. // The memory data source is empty, should return REFUSED rcode.
  856. createDataFromFile("examplequery_fromWire.wire");
  857. server.processMessage(*io_message, *parse_message, *response_obuffer,
  858. &dnsserv);
  859. EXPECT_TRUE(dnsserv.hasAnswer());
  860. headerCheck(*parse_message, default_qid, Rcode::REFUSED(),
  861. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  862. }
  863. #ifdef USE_STATIC_LINK
  864. TEST_F(AuthSrvTest, DISABLED_queryWithInMemoryClientNoDNSSEC) {
  865. #else
  866. TEST_F(AuthSrvTest, queryWithInMemoryClientNoDNSSEC) {
  867. #endif
  868. // In this example, we do simple check that query is handled from the
  869. // query handler class, and confirm it returns no error and a non empty
  870. // answer section. Detailed examination on the response content
  871. // for various types of queries are tested in the query tests.
  872. updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
  873. createDataFromFile("nsec3query_nodnssec_fromWire.wire");
  874. server.processMessage(*io_message, *parse_message, *response_obuffer,
  875. &dnsserv);
  876. EXPECT_TRUE(dnsserv.hasAnswer());
  877. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  878. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 2, 1);
  879. }
  880. #ifdef USE_STATIC_LINK
  881. TEST_F(AuthSrvTest, DISABLED_queryWithInMemoryClientDNSSEC) {
  882. #else
  883. TEST_F(AuthSrvTest, queryWithInMemoryClientDNSSEC) {
  884. #endif
  885. // Similar to the previous test, but the query has the DO bit on.
  886. // The response should contain RRSIGs, and should have more RRs than
  887. // the previous case.
  888. updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
  889. createDataFromFile("nsec3query_fromWire.wire");
  890. server.processMessage(*io_message, *parse_message, *response_obuffer,
  891. &dnsserv);
  892. EXPECT_TRUE(dnsserv.hasAnswer());
  893. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  894. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 2, 3, 3);
  895. }
  896. TEST_F(AuthSrvTest,
  897. #ifdef USE_STATIC_LINK
  898. DISABLED_chQueryWithInMemoryClient
  899. #else
  900. chQueryWithInMemoryClient
  901. #endif
  902. )
  903. {
  904. // Set up the in-memory
  905. updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
  906. // This shouldn't affect the result of class CH query
  907. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  908. default_qid, Name("VERSION.BIND."),
  909. RRClass::CH(), RRType::TXT());
  910. createRequestPacket(request_message, IPPROTO_UDP);
  911. server.processMessage(*io_message, *parse_message, *response_obuffer,
  912. &dnsserv);
  913. EXPECT_TRUE(dnsserv.hasAnswer());
  914. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  915. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 1, 0);
  916. }
  917. // Submit UDP normal query and check query counter
  918. TEST_F(AuthSrvTest, queryCounterUDPNormal) {
  919. // The counter should be initialized to 0.
  920. EXPECT_EQ(0, server.getCounter(AuthCounters::SERVER_UDP_QUERY));
  921. // Create UDP message and process.
  922. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  923. default_qid, Name("example.com"),
  924. RRClass::IN(), RRType::NS());
  925. createRequestPacket(request_message, IPPROTO_UDP);
  926. server.processMessage(*io_message, *parse_message, *response_obuffer,
  927. &dnsserv);
  928. // After processing UDP query, the counter should be 1.
  929. EXPECT_EQ(1, server.getCounter(AuthCounters::SERVER_UDP_QUERY));
  930. // The counter for opcode Query should also be one
  931. EXPECT_EQ(1, server.getCounter(Opcode::QUERY()));
  932. // The counter for REFUSED responses should also be one, the rest zero
  933. checkAllRcodeCountersZeroExcept(Rcode::REFUSED(), 1);
  934. }
  935. // Submit TCP normal query and check query counter
  936. TEST_F(AuthSrvTest, queryCounterTCPNormal) {
  937. // The counter should be initialized to 0.
  938. EXPECT_EQ(0, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  939. // Create TCP message and process.
  940. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  941. default_qid, Name("example.com"),
  942. RRClass::IN(), RRType::NS());
  943. createRequestPacket(request_message, IPPROTO_TCP);
  944. server.processMessage(*io_message, *parse_message, *response_obuffer,
  945. &dnsserv);
  946. // After processing TCP query, the counter should be 1.
  947. EXPECT_EQ(1, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  948. // The counter for SUCCESS responses should also be one
  949. EXPECT_EQ(1, server.getCounter(Opcode::QUERY()));
  950. // The counter for REFUSED responses should also be one, the rest zero
  951. checkAllRcodeCountersZeroExcept(Rcode::REFUSED(), 1);
  952. }
  953. // Submit TCP AXFR query and check query counter
  954. TEST_F(AuthSrvTest, queryCounterTCPAXFR) {
  955. // The counter should be initialized to 0.
  956. EXPECT_EQ(0, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  957. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  958. Name("example.com"), RRClass::IN(), RRType::AXFR());
  959. createRequestPacket(request_message, IPPROTO_TCP);
  960. // On success, the AXFR query has been passed to a separate process,
  961. // so auth itself shouldn't respond.
  962. server.processMessage(*io_message, *parse_message, *response_obuffer,
  963. &dnsserv);
  964. EXPECT_FALSE(dnsserv.hasAnswer());
  965. // After processing TCP AXFR query, the counter should be 1.
  966. EXPECT_EQ(1, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  967. // No rcodes should be incremented
  968. checkAllRcodeCountersZero();
  969. }
  970. // Submit TCP IXFR query and check query counter
  971. TEST_F(AuthSrvTest, queryCounterTCPIXFR) {
  972. // The counter should be initialized to 0.
  973. EXPECT_EQ(0, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  974. UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
  975. Name("example.com"), RRClass::IN(), RRType::IXFR());
  976. createRequestPacket(request_message, IPPROTO_TCP);
  977. // On success, the IXFR query has been passed to a separate process,
  978. // so auth itself shouldn't respond.
  979. server.processMessage(*io_message, *parse_message, *response_obuffer,
  980. &dnsserv);
  981. EXPECT_FALSE(dnsserv.hasAnswer());
  982. // After processing TCP IXFR query, the counter should be 1.
  983. EXPECT_EQ(1, server.getCounter(AuthCounters::SERVER_TCP_QUERY));
  984. }
  985. TEST_F(AuthSrvTest, queryCounterOpcodes) {
  986. for (int i = 0; i < 16; ++i) {
  987. // The counter should be initialized to 0.
  988. EXPECT_EQ(0, server.getCounter(Opcode(i)));
  989. // For each possible opcode, create a request message and send it
  990. UnitTestUtil::createRequestMessage(request_message, Opcode(i),
  991. default_qid, Name("example.com"),
  992. RRClass::IN(), RRType::NS());
  993. createRequestPacket(request_message, IPPROTO_UDP);
  994. // "send" the request N-th times where N is i + 1 for i-th code.
  995. // we intentionally use different values for each code
  996. for (int j = 0; j <= i; ++j) {
  997. parse_message->clear(Message::PARSE);
  998. server.processMessage(*io_message, *parse_message,
  999. *response_obuffer,
  1000. &dnsserv);
  1001. }
  1002. // Confirm the counter.
  1003. EXPECT_EQ(i + 1, server.getCounter(Opcode(i)));
  1004. }
  1005. }
  1006. // class for queryCounterUnexpected test
  1007. // getProtocol() returns IPPROTO_IP
  1008. class DummyUnknownSocket : public IOSocket {
  1009. public:
  1010. DummyUnknownSocket() {}
  1011. virtual int getNative() const { return (0); }
  1012. virtual int getProtocol() const { return (IPPROTO_IP); }
  1013. };
  1014. // function for queryCounterUnexpected test
  1015. // returns a reference to a static object of DummyUnknownSocket
  1016. IOSocket&
  1017. getDummyUnknownSocket() {
  1018. static DummyUnknownSocket socket;
  1019. return (socket);
  1020. }
  1021. // Submit unexpected type of query and check it is ignored
  1022. TEST_F(AuthSrvTest, queryCounterUnexpected) {
  1023. // This code isn't exception safe, but we'd rather keep the code
  1024. // simpler and more readable as this is only for tests
  1025. // Create UDP query packet.
  1026. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  1027. default_qid, Name("example.com"),
  1028. RRClass::IN(), RRType::NS());
  1029. createRequestPacket(request_message, IPPROTO_UDP);
  1030. // Modify the message.
  1031. delete io_message;
  1032. endpoint = IOEndpoint::create(IPPROTO_UDP,
  1033. IOAddress(DEFAULT_REMOTE_ADDRESS), 53210);
  1034. io_message = new IOMessage(request_renderer.getData(),
  1035. request_renderer.getLength(),
  1036. getDummyUnknownSocket(), *endpoint);
  1037. EXPECT_FALSE(dnsserv.hasAnswer());
  1038. }
  1039. TEST_F(AuthSrvTest, stop) {
  1040. // normal case is covered in command_unittest.cc. we should primarily
  1041. // test it here, but the current design of the stop test takes time,
  1042. // so we consolidate the cases in the command tests.
  1043. // If/when the interval timer has finer granularity we'll probably add
  1044. // our own tests here, so we keep this empty test case.
  1045. }
  1046. TEST_F(AuthSrvTest, listenAddresses) {
  1047. isc::testutils::portconfig::listenAddresses(server);
  1048. // Check it requests the correct addresses
  1049. const char* tokens[] = {
  1050. "TCP:127.0.0.1:53210:1",
  1051. "UDP:127.0.0.1:53210:2",
  1052. "TCP:::1:53210:3",
  1053. "UDP:::1:53210:4",
  1054. NULL
  1055. };
  1056. sock_requestor_.checkTokens(tokens, sock_requestor_.given_tokens_,
  1057. "Given tokens");
  1058. // It returns back to empty set of addresses afterwards, so
  1059. // they should be released
  1060. sock_requestor_.checkTokens(tokens, sock_requestor_.released_tokens_,
  1061. "Released tokens");
  1062. }
  1063. TEST_F(AuthSrvTest, processNormalQuery_reuseRenderer1) {
  1064. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  1065. default_qid, Name("example.com"),
  1066. RRClass::IN(), RRType::NS());
  1067. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  1068. createRequestPacket(request_message, IPPROTO_UDP);
  1069. server.processMessage(*io_message, *parse_message, *response_obuffer,
  1070. &dnsserv);
  1071. EXPECT_NE(request_message.getRcode(), parse_message->getRcode());
  1072. }
  1073. TEST_F(AuthSrvTest, processNormalQuery_reuseRenderer2) {
  1074. UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
  1075. default_qid, Name("example.com"),
  1076. RRClass::IN(), RRType::SOA());
  1077. request_message.setHeaderFlag(Message::HEADERFLAG_AA);
  1078. createRequestPacket(request_message, IPPROTO_UDP);
  1079. server.processMessage(*io_message, *parse_message, *response_obuffer,
  1080. &dnsserv);
  1081. ConstQuestionPtr question = *parse_message->beginQuestion();
  1082. EXPECT_STRNE(question->getType().toText().c_str(),
  1083. RRType::NS().toText().c_str());
  1084. }
  1085. //
  1086. // Tests for catching exceptions in various stages of the query processing
  1087. //
  1088. // These tests work by defining two proxy classes, that act as an in-memory
  1089. // client by default, but can throw exceptions at various points.
  1090. //
  1091. namespace {
  1092. /// The possible methods to throw in, either in FakeClient or
  1093. /// FakeZoneFinder
  1094. enum ThrowWhen {
  1095. THROW_NEVER,
  1096. THROW_AT_FIND_ZONE,
  1097. THROW_AT_GET_ORIGIN,
  1098. THROW_AT_GET_CLASS,
  1099. THROW_AT_FIND,
  1100. THROW_AT_FIND_ALL,
  1101. THROW_AT_FIND_NSEC3
  1102. };
  1103. /// convenience function to check whether and what to throw
  1104. void
  1105. checkThrow(ThrowWhen method, ThrowWhen throw_at, bool isc_exception) {
  1106. if (method == throw_at) {
  1107. if (isc_exception) {
  1108. isc_throw(isc::Exception, "foo");
  1109. } else {
  1110. throw std::exception();
  1111. }
  1112. }
  1113. }
  1114. /// \brief proxy class for the ZoneFinder returned by the Client
  1115. /// proxied by FakeClient
  1116. ///
  1117. /// See the documentation for FakeClient for more information,
  1118. /// all methods simply check whether they should throw, and if not, call
  1119. /// their proxied equivalent.
  1120. class FakeZoneFinder : public isc::datasrc::ZoneFinder {
  1121. public:
  1122. FakeZoneFinder(isc::datasrc::ZoneFinderPtr zone_finder,
  1123. ThrowWhen throw_when, bool isc_exception,
  1124. ConstRRsetPtr fake_rrset) :
  1125. real_zone_finder_(zone_finder),
  1126. throw_when_(throw_when),
  1127. isc_exception_(isc_exception),
  1128. fake_rrset_(fake_rrset)
  1129. {}
  1130. virtual isc::dns::Name
  1131. getOrigin() const {
  1132. checkThrow(THROW_AT_GET_ORIGIN, throw_when_, isc_exception_);
  1133. return (real_zone_finder_->getOrigin());
  1134. }
  1135. virtual isc::dns::RRClass
  1136. getClass() const {
  1137. checkThrow(THROW_AT_GET_CLASS, throw_when_, isc_exception_);
  1138. return (real_zone_finder_->getClass());
  1139. }
  1140. virtual isc::datasrc::ZoneFinderContextPtr
  1141. find(const isc::dns::Name& name,
  1142. const isc::dns::RRType& type,
  1143. isc::datasrc::ZoneFinder::FindOptions options)
  1144. {
  1145. using namespace isc::datasrc;
  1146. checkThrow(THROW_AT_FIND, throw_when_, isc_exception_);
  1147. // If faked RRset was specified on construction and it matches the
  1148. // query, return it instead of searching the real data source.
  1149. if (fake_rrset_ && fake_rrset_->getName() == name &&
  1150. fake_rrset_->getType() == type)
  1151. {
  1152. return (ZoneFinderContextPtr(new ZoneFinder::GenericContext(
  1153. *this, options,
  1154. ResultContext(SUCCESS,
  1155. fake_rrset_))));
  1156. }
  1157. return (real_zone_finder_->find(name, type, options));
  1158. }
  1159. virtual isc::datasrc::ZoneFinderContextPtr
  1160. findAll(const isc::dns::Name& name,
  1161. std::vector<isc::dns::ConstRRsetPtr> &target,
  1162. const FindOptions options = FIND_DEFAULT)
  1163. {
  1164. checkThrow(THROW_AT_FIND_ALL, throw_when_, isc_exception_);
  1165. return (real_zone_finder_->findAll(name, target, options));
  1166. }
  1167. virtual FindNSEC3Result
  1168. findNSEC3(const isc::dns::Name& name, bool recursive) {
  1169. checkThrow(THROW_AT_FIND_NSEC3, throw_when_, isc_exception_);
  1170. return (real_zone_finder_->findNSEC3(name, recursive));
  1171. }
  1172. private:
  1173. isc::datasrc::ZoneFinderPtr real_zone_finder_;
  1174. ThrowWhen throw_when_;
  1175. bool isc_exception_;
  1176. ConstRRsetPtr fake_rrset_;
  1177. };
  1178. /// \brief Proxy FakeClient that can throw exceptions at specified times
  1179. ///
  1180. /// Currently it is used as an 'InMemoryClient' using setInMemoryClient,
  1181. /// but it is in effect a general datasource client.
  1182. class FakeClient : public isc::datasrc::DataSourceClient {
  1183. public:
  1184. /// \brief Create a proxy memory client
  1185. ///
  1186. /// \param real_client The real (in-memory) client to proxy
  1187. /// \param throw_when if set to any value other than never, that is
  1188. /// the method that will throw an exception (either in this
  1189. /// class or the related FakeZoneFinder)
  1190. /// \param isc_exception if true, throw isc::Exception, otherwise,
  1191. /// throw std::exception
  1192. /// \param fake_rrset If non NULL, it will be used as an answer to
  1193. /// find() for that name and type.
  1194. FakeClient(const DataSourceClient* real_client,
  1195. ThrowWhen throw_when, bool isc_exception,
  1196. ConstRRsetPtr fake_rrset = ConstRRsetPtr()) :
  1197. real_client_ptr_(real_client),
  1198. throw_when_(throw_when),
  1199. isc_exception_(isc_exception),
  1200. fake_rrset_(fake_rrset)
  1201. {}
  1202. /// \brief proxy call for findZone
  1203. ///
  1204. /// if this instance was constructed with throw_when set to find_zone,
  1205. /// this method will throw. Otherwise, it will return a FakeZoneFinder
  1206. /// instance which will throw at the method specified at the
  1207. /// construction of this instance.
  1208. virtual FindResult
  1209. findZone(const isc::dns::Name& name) const {
  1210. checkThrow(THROW_AT_FIND_ZONE, throw_when_, isc_exception_);
  1211. const FindResult result =
  1212. real_client_ptr_->findZone(name);
  1213. return (FindResult(result.code, isc::datasrc::ZoneFinderPtr(
  1214. new FakeZoneFinder(result.zone_finder,
  1215. throw_when_,
  1216. isc_exception_,
  1217. fake_rrset_))));
  1218. }
  1219. isc::datasrc::ZoneUpdaterPtr
  1220. getUpdater(const isc::dns::Name&, bool, bool) const {
  1221. isc_throw(isc::NotImplemented,
  1222. "Update attempt on in fake data source");
  1223. }
  1224. std::pair<isc::datasrc::ZoneJournalReader::Result,
  1225. isc::datasrc::ZoneJournalReaderPtr>
  1226. getJournalReader(const isc::dns::Name&, uint32_t, uint32_t) const {
  1227. isc_throw(isc::NotImplemented, "Journaling isn't supported for "
  1228. "fake data source");
  1229. }
  1230. private:
  1231. const DataSourceClient* real_client_ptr_;
  1232. ThrowWhen throw_when_;
  1233. bool isc_exception_;
  1234. ConstRRsetPtr fake_rrset_;
  1235. };
  1236. class FakeList : public isc::datasrc::ConfigurableClientList {
  1237. public:
  1238. /// \brief Creates a fake list for the given in-memory client
  1239. ///
  1240. /// It will create a FakeClient for each client in the original list,
  1241. /// with the given arguments, which is used when searching for the
  1242. /// corresponding data source.
  1243. FakeList(const boost::shared_ptr<isc::datasrc::ConfigurableClientList>
  1244. real_list, ThrowWhen throw_when, bool isc_exception,
  1245. ConstRRsetPtr fake_rrset = ConstRRsetPtr()) :
  1246. ConfigurableClientList(RRClass::IN()),
  1247. real_(real_list)
  1248. {
  1249. BOOST_FOREACH(const DataSourceInfo& info, real_->getDataSources()) {
  1250. const isc::datasrc::DataSourceClientPtr
  1251. client(new FakeClient(info.data_src_client_ != NULL ?
  1252. info.data_src_client_ :
  1253. info.getCacheClient(),
  1254. throw_when, isc_exception, fake_rrset));
  1255. clients_.push_back(client);
  1256. data_sources_.push_back(
  1257. DataSourceInfo(client.get(),
  1258. isc::datasrc::DataSourceClientContainerPtr(),
  1259. false, RRClass::IN(), mem_sgmt_));
  1260. }
  1261. }
  1262. private:
  1263. const boost::shared_ptr<isc::datasrc::ConfigurableClientList> real_;
  1264. vector<isc::datasrc::DataSourceClientPtr> clients_;
  1265. MemorySegmentLocal mem_sgmt_;
  1266. };
  1267. } // end anonymous namespace for throwing proxy classes
  1268. // Test for the tests
  1269. //
  1270. // Set the proxies to never throw, this should have the same result as
  1271. // queryWithInMemoryClientNoDNSSEC, and serves to test the two proxy classes
  1272. TEST_F(AuthSrvTest,
  1273. #ifdef USE_STATIC_LINK
  1274. DISABLED_queryWithInMemoryClientProxy
  1275. #else
  1276. queryWithInMemoryClientProxy
  1277. #endif
  1278. )
  1279. {
  1280. // Set real inmem client to proxy
  1281. updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
  1282. {
  1283. isc::util::thread::Mutex::Locker locker(server.getClientListMutex());
  1284. boost::shared_ptr<isc::datasrc::ConfigurableClientList>
  1285. list(new FakeList(server.getClientList(RRClass::IN()), THROW_NEVER,
  1286. false));
  1287. AuthSrv::DataSrcClientListsPtr lists(new std::map<RRClass, ListPtr>);
  1288. lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
  1289. server.swapDataSrcClientLists(lists);
  1290. }
  1291. createDataFromFile("nsec3query_nodnssec_fromWire.wire");
  1292. server.processMessage(*io_message, *parse_message, *response_obuffer,
  1293. &dnsserv);
  1294. EXPECT_TRUE(dnsserv.hasAnswer());
  1295. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  1296. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 2, 1);
  1297. }
  1298. // Convenience function for the rest of the tests, set up a proxy
  1299. // to throw in the given method
  1300. // If isc_exception is true, it will throw isc::Exception, otherwise
  1301. // it will throw std::exception
  1302. // If non null rrset is given, it will be passed to the proxy so it can
  1303. // return some faked response.
  1304. void
  1305. setupThrow(AuthSrv& server, ThrowWhen throw_when, bool isc_exception,
  1306. ConstRRsetPtr rrset = ConstRRsetPtr())
  1307. {
  1308. updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
  1309. isc::util::thread::Mutex::Locker locker(server.getClientListMutex());
  1310. boost::shared_ptr<isc::datasrc::ConfigurableClientList>
  1311. list(new FakeList(server.getClientList(RRClass::IN()), throw_when,
  1312. isc_exception, rrset));
  1313. AuthSrv::DataSrcClientListsPtr lists(new std::map<RRClass, ListPtr>);
  1314. lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
  1315. server.swapDataSrcClientLists(lists);
  1316. }
  1317. TEST_F(AuthSrvTest,
  1318. #ifdef USE_STATIC_LINK
  1319. DISABLED_queryWithThrowingProxyServfails
  1320. #else
  1321. queryWithThrowingProxyServfails
  1322. #endif
  1323. )
  1324. {
  1325. // Test the common cases, all of which should simply return SERVFAIL
  1326. // Use THROW_NEVER as end marker
  1327. ThrowWhen throws[] = { THROW_AT_FIND_ZONE,
  1328. THROW_AT_GET_ORIGIN,
  1329. THROW_AT_FIND,
  1330. THROW_AT_FIND_NSEC3,
  1331. THROW_NEVER };
  1332. UnitTestUtil::createDNSSECRequestMessage(request_message, opcode,
  1333. default_qid, Name("foo.example."),
  1334. RRClass::IN(), RRType::TXT());
  1335. for (ThrowWhen* when(throws); *when != THROW_NEVER; ++when) {
  1336. createRequestPacket(request_message, IPPROTO_UDP);
  1337. setupThrow(server, *when, true);
  1338. processAndCheckSERVFAIL();
  1339. // To be sure, check same for non-isc-exceptions
  1340. createRequestPacket(request_message, IPPROTO_UDP);
  1341. setupThrow(server, *when, false);
  1342. processAndCheckSERVFAIL();
  1343. }
  1344. }
  1345. // Throw isc::Exception in getClass(). (Currently?) getClass is not called
  1346. // in the processMessage path, so this should result in a normal answer
  1347. TEST_F(AuthSrvTest,
  1348. #ifdef USE_STATIC_LINK
  1349. DISABLED_queryWithInMemoryClientProxyGetClass
  1350. #else
  1351. queryWithInMemoryClientProxyGetClass
  1352. #endif
  1353. )
  1354. {
  1355. createDataFromFile("nsec3query_nodnssec_fromWire.wire");
  1356. setupThrow(server, THROW_AT_GET_CLASS, true);
  1357. // getClass is not called so it should just answer
  1358. server.processMessage(*io_message, *parse_message, *response_obuffer,
  1359. &dnsserv);
  1360. EXPECT_TRUE(dnsserv.hasAnswer());
  1361. headerCheck(*parse_message, default_qid, Rcode::NOERROR(),
  1362. opcode.getCode(), QR_FLAG | AA_FLAG, 1, 1, 2, 1);
  1363. }
  1364. TEST_F(AuthSrvTest,
  1365. #ifdef USE_STATIC_LINK
  1366. DISABLED_queryWithThrowingInToWire
  1367. #else
  1368. queryWithThrowingInToWire
  1369. #endif
  1370. )
  1371. {
  1372. // Set up a faked data source. It will return an empty RRset for the
  1373. // query.
  1374. ConstRRsetPtr empty_rrset(new RRset(Name("foo.example"),
  1375. RRClass::IN(), RRType::TXT(),
  1376. RRTTL(0)));
  1377. setupThrow(server, THROW_NEVER, true, empty_rrset);
  1378. // Repeat the query processing two times. Due to the faked RRset,
  1379. // toWire() should throw, and it should result in SERVFAIL.
  1380. OutputBufferPtr orig_buffer;
  1381. for (int i = 0; i < 2; ++i) {
  1382. UnitTestUtil::createDNSSECRequestMessage(request_message, opcode,
  1383. default_qid,
  1384. Name("foo.example."),
  1385. RRClass::IN(), RRType::TXT());
  1386. createRequestPacket(request_message, IPPROTO_UDP);
  1387. server.processMessage(*io_message, *parse_message, *response_obuffer,
  1388. &dnsserv);
  1389. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  1390. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  1391. // Make a backup of the original buffer for latest tests and replace
  1392. // it with a new one
  1393. if (!orig_buffer) {
  1394. orig_buffer = response_obuffer;
  1395. response_obuffer.reset(new OutputBuffer(0));
  1396. }
  1397. request_message.clear(Message::RENDER);
  1398. parse_message->clear(Message::PARSE);
  1399. }
  1400. // Now check if the original buffer is intact
  1401. parse_message->clear(Message::PARSE);
  1402. InputBuffer ibuffer(orig_buffer->getData(), orig_buffer->getLength());
  1403. parse_message->fromWire(ibuffer);
  1404. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  1405. opcode.getCode(), QR_FLAG, 1, 0, 0, 0);
  1406. }
  1407. //
  1408. // DDNS related tests
  1409. //
  1410. // Helper subroutine to check if the given socket address has the expected
  1411. // address and port. It depends on specific output of getnameinfo() (while
  1412. // there can be multiple textual representation of the same address) but
  1413. // in practice it should be reliable.
  1414. void
  1415. checkAddrPort(const struct sockaddr& actual_sa,
  1416. const string& expected_addr, uint16_t expected_port)
  1417. {
  1418. char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
  1419. const int error = getnameinfo(&actual_sa, getSALength(actual_sa), hbuf,
  1420. sizeof(hbuf), sbuf, sizeof(sbuf),
  1421. NI_NUMERICHOST | NI_NUMERICSERV);
  1422. if (error != 0) {
  1423. isc_throw(isc::Unexpected, "getnameinfo failed: " <<
  1424. gai_strerror(error));
  1425. }
  1426. EXPECT_EQ(expected_addr, hbuf);
  1427. EXPECT_EQ(boost::lexical_cast<string>(expected_port), sbuf);
  1428. }
  1429. TEST_F(AuthSrvTest, DDNSForward) {
  1430. EXPECT_FALSE(ddns_forwarder.isConnected());
  1431. // Repeat sending an update request 4 times, differing some network
  1432. // parameters: UDP/IPv4, TCP/IPv4, UDP/IPv6, TCP/IPv6, in this order.
  1433. // By doing that we can also confirm the forwarder connection will be
  1434. // established exactly once, and kept established.
  1435. for (size_t i = 0; i < 4; ++i) {
  1436. // Use different names for some different cases
  1437. const Name zone_name = Name(i < 2 ? "example.com" : "example.org");
  1438. const socklen_t family = (i < 2) ? AF_INET : AF_INET6;
  1439. const char* const remote_addr =
  1440. (family == AF_INET) ? "192.0.2.1" : "2001:db8::1";
  1441. const uint16_t remote_port =
  1442. (family == AF_INET) ? 53214 : 53216;
  1443. const int protocol = ((i % 2) == 0) ? IPPROTO_UDP : IPPROTO_TCP;
  1444. createAndSendRequest(RRType::SOA(), Opcode::UPDATE(), zone_name,
  1445. RRClass::IN(), protocol, remote_addr,
  1446. remote_port);
  1447. EXPECT_FALSE(dnsserv.hasAnswer());
  1448. EXPECT_TRUE(ddns_forwarder.isConnected());
  1449. // Examine the pushed data (note: currently "local end" has a dummy
  1450. // value equal to remote)
  1451. EXPECT_EQ(family, ddns_forwarder.getPushedFamily());
  1452. const int expected_type =
  1453. (protocol == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
  1454. EXPECT_EQ(expected_type, ddns_forwarder.getPushedType());
  1455. EXPECT_EQ(protocol, ddns_forwarder.getPushedProtocol());
  1456. checkAddrPort(ddns_forwarder.getPushedRemoteend(),
  1457. remote_addr, remote_port);
  1458. checkAddrPort(ddns_forwarder.getPushedLocalend(),
  1459. remote_addr, remote_port);
  1460. EXPECT_EQ(io_message->getDataSize(),
  1461. ddns_forwarder.getPushedData().size());
  1462. EXPECT_EQ(0, memcmp(io_message->getData(),
  1463. &ddns_forwarder.getPushedData()[0],
  1464. ddns_forwarder.getPushedData().size()));
  1465. }
  1466. }
  1467. TEST_F(AuthSrvTest, DDNSForwardConnectFail) {
  1468. // make connect attempt fail. It should result in SERVFAIL. Note that
  1469. // the question (zone) section should be cleared for opcode of update.
  1470. ddns_forwarder.disableConnect();
  1471. createAndSendRequest(RRType::SOA(), Opcode::UPDATE());
  1472. EXPECT_TRUE(dnsserv.hasAnswer());
  1473. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  1474. Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
  1475. EXPECT_FALSE(ddns_forwarder.isConnected());
  1476. // Now make connect okay again. Despite the previous failure the new
  1477. // connection should now be established.
  1478. ddns_forwarder.enableConnect();
  1479. createAndSendRequest(RRType::SOA(), Opcode::UPDATE());
  1480. EXPECT_FALSE(dnsserv.hasAnswer());
  1481. EXPECT_TRUE(ddns_forwarder.isConnected());
  1482. }
  1483. TEST_F(AuthSrvTest, DDNSForwardPushFail) {
  1484. // Make first request succeed, which will establish the connection.
  1485. EXPECT_FALSE(ddns_forwarder.isConnected());
  1486. createAndSendRequest(RRType::SOA(), Opcode::UPDATE());
  1487. EXPECT_TRUE(ddns_forwarder.isConnected());
  1488. // make connect attempt fail. It should result in SERVFAIL. The
  1489. // connection should be closed. Use IPv6 address for varying log output.
  1490. ddns_forwarder.disablePush();
  1491. createAndSendRequest(RRType::SOA(), Opcode::UPDATE(), Name("example.com"),
  1492. RRClass::IN(), IPPROTO_UDP, "2001:db8::2");
  1493. EXPECT_TRUE(dnsserv.hasAnswer());
  1494. headerCheck(*parse_message, default_qid, Rcode::SERVFAIL(),
  1495. Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
  1496. EXPECT_FALSE(ddns_forwarder.isConnected());
  1497. // Allow push again. Connection will be reopened, and the request will
  1498. // be forwarded successfully.
  1499. ddns_forwarder.enablePush();
  1500. createAndSendRequest(RRType::SOA(), Opcode::UPDATE());
  1501. EXPECT_FALSE(dnsserv.hasAnswer());
  1502. EXPECT_TRUE(ddns_forwarder.isConnected());
  1503. }
  1504. TEST_F(AuthSrvTest, DDNSForwardClose) {
  1505. scoped_ptr<AuthSrv> tmp_server(new AuthSrv(xfrout, ddns_forwarder));
  1506. tmp_server->createDDNSForwarder();
  1507. UnitTestUtil::createRequestMessage(request_message, Opcode::UPDATE(),
  1508. default_qid, Name("example.com"),
  1509. RRClass::IN(), RRType::SOA());
  1510. createRequestPacket(request_message, IPPROTO_UDP);
  1511. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1512. &dnsserv);
  1513. EXPECT_FALSE(dnsserv.hasAnswer());
  1514. EXPECT_TRUE(ddns_forwarder.isConnected());
  1515. // Destroy the server. The forwarder should close the connection.
  1516. tmp_server.reset();
  1517. EXPECT_FALSE(ddns_forwarder.isConnected());
  1518. }
  1519. namespace {
  1520. // Send a basic command without arguments, and check the response has
  1521. // result code 0
  1522. void sendSimpleCommand(AuthSrv& server, const std::string& command) {
  1523. ConstElementPtr response = execAuthServerCommand(server, command,
  1524. ConstElementPtr());
  1525. int command_result = -1;
  1526. isc::config::parseAnswer(command_result, response);
  1527. EXPECT_EQ(0, command_result);
  1528. }
  1529. } // end anonymous namespace
  1530. TEST_F(AuthSrvTest, DDNSForwardCreateDestroy) {
  1531. // Test that AuthSrv returns NOTIMP before ddns forwarder is created,
  1532. // that the ddns_forwarder is connected when the 'start_ddns_forwarder'
  1533. // command has been sent, and that it is no longer connected and auth
  1534. // returns NOTIMP after the stop_ddns_forwarding command is sent.
  1535. scoped_ptr<AuthSrv> tmp_server(new AuthSrv(xfrout, ddns_forwarder));
  1536. // Prepare update message to send
  1537. UnitTestUtil::createRequestMessage(request_message, Opcode::UPDATE(),
  1538. default_qid, Name("example.com"),
  1539. RRClass::IN(), RRType::SOA());
  1540. createRequestPacket(request_message, IPPROTO_UDP);
  1541. // before creating forwarder. isConnected() should be false and
  1542. // rcode to UPDATE should be NOTIMP
  1543. parse_message->clear(Message::PARSE);
  1544. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1545. &dnsserv);
  1546. EXPECT_FALSE(ddns_forwarder.isConnected());
  1547. EXPECT_TRUE(dnsserv.hasAnswer());
  1548. headerCheck(*parse_message, default_qid, Rcode::NOTIMP(),
  1549. Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
  1550. // now create forwarder
  1551. sendSimpleCommand(*tmp_server, "start_ddns_forwarder");
  1552. // our mock does not respond, and since auth is supposed to send it on,
  1553. // there should now be no result when an UPDATE is sent
  1554. parse_message->clear(Message::PARSE);
  1555. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1556. &dnsserv);
  1557. EXPECT_FALSE(dnsserv.hasAnswer());
  1558. EXPECT_TRUE(ddns_forwarder.isConnected());
  1559. // If we send a start again, the connection should be recreated,
  1560. // visible because isConnected() reports false until an actual message
  1561. // has been forwarded
  1562. sendSimpleCommand(*tmp_server, "start_ddns_forwarder");
  1563. EXPECT_FALSE(ddns_forwarder.isConnected());
  1564. parse_message->clear(Message::PARSE);
  1565. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1566. &dnsserv);
  1567. EXPECT_FALSE(dnsserv.hasAnswer());
  1568. EXPECT_TRUE(ddns_forwarder.isConnected());
  1569. // Now tell it to stop forwarder, should respond with NOTIMP again
  1570. sendSimpleCommand(*tmp_server, "stop_ddns_forwarder");
  1571. parse_message->clear(Message::PARSE);
  1572. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1573. &dnsserv);
  1574. EXPECT_FALSE(ddns_forwarder.isConnected());
  1575. EXPECT_TRUE(dnsserv.hasAnswer());
  1576. headerCheck(*parse_message, default_qid, Rcode::NOTIMP(),
  1577. Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
  1578. // Sending stop again should make no difference
  1579. sendSimpleCommand(*tmp_server, "stop_ddns_forwarder");
  1580. parse_message->clear(Message::PARSE);
  1581. tmp_server->processMessage(*io_message, *parse_message, *response_obuffer,
  1582. &dnsserv);
  1583. EXPECT_FALSE(ddns_forwarder.isConnected());
  1584. EXPECT_TRUE(dnsserv.hasAnswer());
  1585. headerCheck(*parse_message, default_qid, Rcode::NOTIMP(),
  1586. Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
  1587. }
  1588. // Check the client list accessors
  1589. TEST_F(AuthSrvTest, clientList) {
  1590. // We need to lock the mutex to make the (get|set)ClientList happy.
  1591. // There's a debug-build only check in them to make sure everything
  1592. // locks them and we call them directly here.
  1593. isc::util::thread::Mutex::Locker locker(server.getClientListMutex());
  1594. AuthSrv::DataSrcClientListsPtr lists; // initially empty
  1595. // The lists don't exist. Therefore, the list of RRClasses is empty.
  1596. EXPECT_TRUE(server.swapDataSrcClientLists(lists)->empty());
  1597. // Put something in.
  1598. const ListPtr list(new ConfigurableClientList(RRClass::IN()));
  1599. const ListPtr list2(new ConfigurableClientList(RRClass::CH()));
  1600. lists.reset(new std::map<RRClass, ListPtr>);
  1601. lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
  1602. lists->insert(pair<RRClass, ListPtr>(RRClass::CH(), list2));
  1603. server.swapDataSrcClientLists(lists);
  1604. // And the lists can be retrieved.
  1605. EXPECT_EQ(list, server.getClientList(RRClass::IN()));
  1606. EXPECT_EQ(list2, server.getClientList(RRClass::CH()));
  1607. // Replace the lists with new lists containing only one list.
  1608. lists.reset(new std::map<RRClass, ListPtr>);
  1609. lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
  1610. lists = server.swapDataSrcClientLists(lists);
  1611. // Old one had two lists. That confirms our swap for IN and CH classes
  1612. // (i.e., no other entries were there).
  1613. EXPECT_EQ(2, lists->size());
  1614. // The CH list really got deleted.
  1615. EXPECT_EQ(list, server.getClientList(RRClass::IN()));
  1616. EXPECT_FALSE(server.getClientList(RRClass::CH()));
  1617. }
  1618. // We just test the mutex can be locked (exactly once).
  1619. TEST_F(AuthSrvTest, mutex) {
  1620. isc::util::thread::Mutex::Locker l1(server.getClientListMutex());
  1621. // TODO: Once we have non-debug build, this one will not work, since
  1622. // we currently use the fact that we can't lock twice from the same
  1623. // thread. In the non-debug mode, this would deadlock.
  1624. // Skip then.
  1625. EXPECT_THROW({
  1626. isc::util::thread::Mutex::Locker l2(server.getClientListMutex());
  1627. }, isc::InvalidOperation);
  1628. }
  1629. }