auth_srv.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. // Copyright (C) 2009 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 <sys/types.h>
  16. #include <netinet/in.h>
  17. #include <algorithm>
  18. #include <cassert>
  19. #include <iostream>
  20. #include <vector>
  21. #include <memory>
  22. #include <boost/bind.hpp>
  23. #include <asiolink/asiolink.h>
  24. #include <config/ccsession.h>
  25. #include <cc/data.h>
  26. #include <exceptions/exceptions.h>
  27. #include <util/buffer.h>
  28. #include <dns/edns.h>
  29. #include <dns/exceptions.h>
  30. #include <dns/messagerenderer.h>
  31. #include <dns/name.h>
  32. #include <dns/question.h>
  33. #include <dns/opcode.h>
  34. #include <dns/rcode.h>
  35. #include <dns/rrset.h>
  36. #include <dns/rrttl.h>
  37. #include <dns/message.h>
  38. #include <dns/tsig.h>
  39. #include <asiodns/dns_service.h>
  40. #include <datasrc/query.h>
  41. #include <datasrc/data_source.h>
  42. #include <datasrc/memory_datasrc.h>
  43. #include <datasrc/static_datasrc.h>
  44. #include <datasrc/sqlite3_datasrc.h>
  45. #include <xfr/xfrout_client.h>
  46. #include <auth/common.h>
  47. #include <auth/auth_config.h>
  48. #include <auth/auth_srv.h>
  49. #include <auth/query.h>
  50. #include <auth/statistics.h>
  51. #include <auth/auth_log.h>
  52. using namespace std;
  53. using namespace isc;
  54. using namespace isc::cc;
  55. using namespace isc::datasrc;
  56. using namespace isc::dns;
  57. using namespace isc::util;
  58. using namespace isc::auth;
  59. using namespace isc::dns::rdata;
  60. using namespace isc::data;
  61. using namespace isc::config;
  62. using namespace isc::xfr;
  63. using namespace isc::asiolink;
  64. using namespace isc::asiodns;
  65. using namespace isc::server_common::portconfig;
  66. namespace {
  67. // A helper class for cleaning up message renderer.
  68. //
  69. // A temporary object of this class is expected to be created before starting
  70. // response message rendering. On construction, it (re)initialize the given
  71. // message renderer with the given buffer. On destruction, it releases
  72. // the previously set buffer and then release any internal resource in the
  73. // renderer, no matter what happened during the rendering, especially even
  74. // when it resulted in an exception.
  75. //
  76. // Note: if we need this helper in many other places we might consider making
  77. // it visible to other modules. As of this implementation this is the only
  78. // user of this class, so we hide it within the implementation.
  79. class RendererHolder {
  80. public:
  81. RendererHolder(MessageRenderer& renderer, OutputBuffer* buffer) :
  82. renderer_(renderer)
  83. {
  84. renderer.setBuffer(buffer);
  85. }
  86. ~RendererHolder() {
  87. renderer_.setBuffer(NULL);
  88. renderer_.clear();
  89. }
  90. private:
  91. MessageRenderer& renderer_;
  92. };
  93. }
  94. class AuthSrvImpl {
  95. private:
  96. // prohibit copy
  97. AuthSrvImpl(const AuthSrvImpl& source);
  98. AuthSrvImpl& operator=(const AuthSrvImpl& source);
  99. public:
  100. AuthSrvImpl(const bool use_cache, AbstractXfroutClient& xfrout_client);
  101. ~AuthSrvImpl();
  102. isc::data::ConstElementPtr setDbFile(isc::data::ConstElementPtr config);
  103. bool processNormalQuery(const IOMessage& io_message, Message& message,
  104. OutputBuffer& buffer,
  105. auto_ptr<TSIGContext> tsig_context);
  106. bool processXfrQuery(const IOMessage& io_message, Message& message,
  107. OutputBuffer& buffer,
  108. auto_ptr<TSIGContext> tsig_context);
  109. bool processNotify(const IOMessage& io_message, Message& message,
  110. OutputBuffer& buffer,
  111. auto_ptr<TSIGContext> tsig_context);
  112. IOService io_service_;
  113. MessageRenderer renderer_;
  114. /// Currently non-configurable, but will be.
  115. static const uint16_t DEFAULT_LOCAL_UDPSIZE = 4096;
  116. /// These members are public because AuthSrv accesses them directly.
  117. ModuleCCSession* config_session_;
  118. AbstractSession* xfrin_session_;
  119. /// In-memory data source. Currently class IN only for simplicity.
  120. const RRClass memory_client_class_;
  121. AuthSrv::InMemoryClientPtr memory_client_;
  122. /// Hot spot cache
  123. isc::datasrc::HotCache cache_;
  124. /// Interval timer for periodic submission of statistics counters.
  125. IntervalTimer statistics_timer_;
  126. /// Query counters for statistics
  127. AuthCounters counters_;
  128. /// Addresses we listen on
  129. AddressList listen_addresses_;
  130. /// The TSIG keyring
  131. const boost::shared_ptr<TSIGKeyRing>* keyring_;
  132. /// Bind the ModuleSpec object in config_session_ with
  133. /// isc:config::ModuleSpec::validateStatistics.
  134. void registerStatisticsValidator();
  135. /// \brief Resume the server
  136. ///
  137. /// This is a wrapper call for DNSServer::resume(done), if 'done' is true,
  138. /// the Rcode set in the given Message is counted in the statistics
  139. /// counter.
  140. ///
  141. /// This method is expected to be called by processMessage()
  142. ///
  143. /// \param server The DNSServer as passed to processMessage()
  144. /// \param message The response as constructed by processMessage()
  145. /// \param done If true, the Rcode from the given message is counted,
  146. /// this value is then passed to server->resume(bool)
  147. void resumeServer(isc::asiodns::DNSServer* server,
  148. isc::dns::Message& message,
  149. bool done);
  150. private:
  151. std::string db_file_;
  152. MetaDataSrc data_sources_;
  153. /// We keep a pointer to the currently running sqlite datasource
  154. /// so that we can specifically remove that one should the database
  155. /// file change
  156. ConstDataSrcPtr cur_datasrc_;
  157. bool xfrout_connected_;
  158. AbstractXfroutClient& xfrout_client_;
  159. /// Increment query counter
  160. void incCounter(const int protocol);
  161. // validateStatistics
  162. bool validateStatistics(isc::data::ConstElementPtr data) const;
  163. auth::Query query_;
  164. };
  165. AuthSrvImpl::AuthSrvImpl(const bool use_cache,
  166. AbstractXfroutClient& xfrout_client) :
  167. config_session_(NULL),
  168. xfrin_session_(NULL),
  169. memory_client_class_(RRClass::IN()),
  170. statistics_timer_(io_service_),
  171. counters_(),
  172. keyring_(NULL),
  173. xfrout_connected_(false),
  174. xfrout_client_(xfrout_client)
  175. {
  176. // cur_datasrc_ is automatically initialized by the default constructor,
  177. // effectively being an empty (sqlite) data source. once ccsession is up
  178. // the datasource will be set by the configuration setting
  179. // add static data source
  180. data_sources_.addDataSrc(ConstDataSrcPtr(new StaticDataSrc));
  181. // enable or disable the cache
  182. cache_.setEnabled(use_cache);
  183. }
  184. AuthSrvImpl::~AuthSrvImpl() {
  185. if (xfrout_connected_) {
  186. xfrout_client_.disconnect();
  187. xfrout_connected_ = false;
  188. }
  189. }
  190. // This is a derived class of \c DNSLookup, to serve as a
  191. // callback in the asiolink module. It calls
  192. // AuthSrv::processMessage() on a single DNS message.
  193. class MessageLookup : public DNSLookup {
  194. public:
  195. MessageLookup(AuthSrv* srv) : server_(srv) {}
  196. virtual void operator()(const IOMessage& io_message,
  197. MessagePtr message,
  198. MessagePtr, // Not used here
  199. OutputBufferPtr buffer,
  200. DNSServer* server) const
  201. {
  202. server_->processMessage(io_message, *message, *buffer, server);
  203. }
  204. private:
  205. AuthSrv* server_;
  206. };
  207. // This is a derived class of \c DNSAnswer, to serve as a callback in the
  208. // asiolink module. We actually shouldn't do anything in this class because
  209. // we build complete response messages in the process methods; otherwise
  210. // the response message will contain trailing garbage. In future, we should
  211. // probably even drop the reliance on DNSAnswer. We don't need the coroutine
  212. // tricks provided in that framework, and its overhead would be significant
  213. // in terms of performance consideration for the authoritative server
  214. // implementation.
  215. class MessageAnswer : public DNSAnswer {
  216. public:
  217. MessageAnswer(AuthSrv*) {}
  218. virtual void operator()(const IOMessage&, MessagePtr,
  219. MessagePtr, OutputBufferPtr) const
  220. {}
  221. };
  222. // This is a derived class of \c SimpleCallback, to serve
  223. // as a callback in the asiolink module. It checks for queued
  224. // configuration messages, and executes them if found.
  225. class ConfigChecker : public SimpleCallback {
  226. public:
  227. ConfigChecker(AuthSrv* srv) : server_(srv) {}
  228. virtual void operator()(const IOMessage&) const {
  229. ModuleCCSession* cfg_session = server_->getConfigSession();
  230. if (cfg_session != NULL && cfg_session->hasQueuedMsgs()) {
  231. cfg_session->checkCommand();
  232. }
  233. }
  234. private:
  235. AuthSrv* server_;
  236. };
  237. AuthSrv::AuthSrv(const bool use_cache, AbstractXfroutClient& xfrout_client)
  238. {
  239. impl_ = new AuthSrvImpl(use_cache, xfrout_client);
  240. checkin_ = new ConfigChecker(this);
  241. dns_lookup_ = new MessageLookup(this);
  242. dns_answer_ = new MessageAnswer(this);
  243. }
  244. void
  245. AuthSrv::stop() {
  246. impl_->io_service_.stop();
  247. }
  248. AuthSrv::~AuthSrv() {
  249. delete impl_;
  250. delete checkin_;
  251. delete dns_lookup_;
  252. delete dns_answer_;
  253. }
  254. namespace {
  255. class QuestionInserter {
  256. public:
  257. QuestionInserter(Message& message) : message_(message) {}
  258. void operator()(const QuestionPtr question) {
  259. message_.addQuestion(question);
  260. }
  261. Message& message_;
  262. };
  263. void
  264. makeErrorMessage(MessageRenderer& renderer, Message& message,
  265. OutputBuffer& buffer, const Rcode& rcode,
  266. std::auto_ptr<TSIGContext> tsig_context =
  267. std::auto_ptr<TSIGContext>())
  268. {
  269. // extract the parameters that should be kept.
  270. // XXX: with the current implementation, it's not easy to set EDNS0
  271. // depending on whether the query had it. So we'll simply omit it.
  272. const qid_t qid = message.getQid();
  273. const bool rd = message.getHeaderFlag(Message::HEADERFLAG_RD);
  274. const bool cd = message.getHeaderFlag(Message::HEADERFLAG_CD);
  275. const Opcode& opcode = message.getOpcode();
  276. vector<QuestionPtr> questions;
  277. // If this is an error to a query or notify, we should also copy the
  278. // question section.
  279. if (opcode == Opcode::QUERY() || opcode == Opcode::NOTIFY()) {
  280. questions.assign(message.beginQuestion(), message.endQuestion());
  281. }
  282. message.clear(Message::RENDER);
  283. message.setQid(qid);
  284. message.setOpcode(opcode);
  285. message.setHeaderFlag(Message::HEADERFLAG_QR);
  286. if (rd) {
  287. message.setHeaderFlag(Message::HEADERFLAG_RD);
  288. }
  289. if (cd) {
  290. message.setHeaderFlag(Message::HEADERFLAG_CD);
  291. }
  292. for_each(questions.begin(), questions.end(), QuestionInserter(message));
  293. message.setRcode(rcode);
  294. RendererHolder holder(renderer, &buffer);
  295. if (tsig_context.get() != NULL) {
  296. message.toWire(renderer, *tsig_context);
  297. } else {
  298. message.toWire(renderer);
  299. }
  300. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_ERROR_RESPONSE)
  301. .arg(renderer.getLength()).arg(message);
  302. }
  303. }
  304. IOService&
  305. AuthSrv::getIOService() {
  306. return (impl_->io_service_);
  307. }
  308. void
  309. AuthSrv::setCacheSlots(const size_t slots) {
  310. impl_->cache_.setSlots(slots);
  311. }
  312. size_t
  313. AuthSrv::getCacheSlots() const {
  314. return (impl_->cache_.getSlots());
  315. }
  316. void
  317. AuthSrv::setXfrinSession(AbstractSession* xfrin_session) {
  318. impl_->xfrin_session_ = xfrin_session;
  319. }
  320. void
  321. AuthSrv::setConfigSession(ModuleCCSession* config_session) {
  322. impl_->config_session_ = config_session;
  323. impl_->registerStatisticsValidator();
  324. }
  325. void
  326. AuthSrv::setStatisticsSession(AbstractSession* statistics_session) {
  327. impl_->counters_.setStatisticsSession(statistics_session);
  328. }
  329. ModuleCCSession*
  330. AuthSrv::getConfigSession() const {
  331. return (impl_->config_session_);
  332. }
  333. AuthSrv::InMemoryClientPtr
  334. AuthSrv::getInMemoryClient(const RRClass& rrclass) {
  335. // XXX: for simplicity, we only support the IN class right now.
  336. if (rrclass != impl_->memory_client_class_) {
  337. isc_throw(InvalidParameter,
  338. "Memory data source is not supported for RR class "
  339. << rrclass);
  340. }
  341. return (impl_->memory_client_);
  342. }
  343. void
  344. AuthSrv::setInMemoryClient(const isc::dns::RRClass& rrclass,
  345. InMemoryClientPtr memory_client)
  346. {
  347. // XXX: see above
  348. if (rrclass != impl_->memory_client_class_) {
  349. isc_throw(InvalidParameter,
  350. "Memory data source is not supported for RR class "
  351. << rrclass);
  352. } else if (!impl_->memory_client_ && memory_client) {
  353. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_MEM_DATASRC_ENABLED)
  354. .arg(rrclass);
  355. } else if (impl_->memory_client_ && !memory_client) {
  356. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_MEM_DATASRC_DISABLED)
  357. .arg(rrclass);
  358. }
  359. impl_->memory_client_ = memory_client;
  360. }
  361. uint32_t
  362. AuthSrv::getStatisticsTimerInterval() const {
  363. return (impl_->statistics_timer_.getInterval() / 1000);
  364. }
  365. void
  366. AuthSrv::setStatisticsTimerInterval(uint32_t interval) {
  367. if (interval == impl_->statistics_timer_.getInterval()) {
  368. return;
  369. }
  370. if (interval > 86400) {
  371. // It can't occur since the value is checked in
  372. // statisticsIntervalConfig::build().
  373. isc_throw(InvalidParameter, "Too long interval: " << interval);
  374. }
  375. if (interval == 0) {
  376. impl_->statistics_timer_.cancel();
  377. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STATS_TIMER_DISABLED);
  378. } else {
  379. impl_->statistics_timer_.setup(boost::bind(&AuthSrv::submitStatistics,
  380. this),
  381. interval * 1000);
  382. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STATS_TIMER_SET)
  383. .arg(interval);
  384. }
  385. }
  386. void
  387. AuthSrv::processMessage(const IOMessage& io_message, Message& message,
  388. OutputBuffer& buffer, DNSServer* server)
  389. {
  390. InputBuffer request_buffer(io_message.getData(), io_message.getDataSize());
  391. // First, check the header part. If we fail even for the base header,
  392. // just drop the message.
  393. try {
  394. message.parseHeader(request_buffer);
  395. // Ignore all responses.
  396. if (message.getHeaderFlag(Message::HEADERFLAG_QR)) {
  397. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_RECEIVED);
  398. impl_->resumeServer(server, message, false);
  399. return;
  400. }
  401. } catch (const Exception& ex) {
  402. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_HEADER_PARSE_FAIL)
  403. .arg(ex.what());
  404. impl_->resumeServer(server, message, false);
  405. return;
  406. }
  407. try {
  408. // Parse the message.
  409. message.fromWire(request_buffer);
  410. } catch (const DNSProtocolError& error) {
  411. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PROTOCOL_ERROR)
  412. .arg(error.getRcode().toText()).arg(error.what());
  413. makeErrorMessage(impl_->renderer_, message, buffer, error.getRcode());
  414. impl_->resumeServer(server, message, true);
  415. return;
  416. } catch (const Exception& ex) {
  417. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PARSE_ERROR)
  418. .arg(ex.what());
  419. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL());
  420. impl_->resumeServer(server, message, true);
  421. return;
  422. } // other exceptions will be handled at a higher layer.
  423. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_PACKET_RECEIVED)
  424. .arg(message);
  425. // Perform further protocol-level validation.
  426. // TSIG first
  427. // If this is set to something, we know we need to answer with TSIG as well
  428. std::auto_ptr<TSIGContext> tsig_context;
  429. const TSIGRecord* tsig_record(message.getTSIGRecord());
  430. TSIGError tsig_error(TSIGError::NOERROR());
  431. // Do we do TSIG?
  432. // The keyring can be null if we're in test
  433. if (impl_->keyring_ != NULL && tsig_record != NULL) {
  434. tsig_context.reset(new TSIGContext(tsig_record->getName(),
  435. tsig_record->getRdata().
  436. getAlgorithm(),
  437. **impl_->keyring_));
  438. tsig_error = tsig_context->verify(tsig_record, io_message.getData(),
  439. io_message.getDataSize());
  440. }
  441. if (tsig_error != TSIGError::NOERROR()) {
  442. makeErrorMessage(impl_->renderer_, message, buffer,
  443. tsig_error.toRcode(), tsig_context);
  444. impl_->resumeServer(server, message, true);
  445. return;
  446. }
  447. bool send_answer = true;
  448. try {
  449. // update per opcode statistics counter. This can only be reliable
  450. // after TSIG check succeeds.
  451. impl_->counters_.inc(message.getOpcode());
  452. if (message.getOpcode() == Opcode::NOTIFY()) {
  453. send_answer = impl_->processNotify(io_message, message, buffer,
  454. tsig_context);
  455. } else if (message.getOpcode() != Opcode::QUERY()) {
  456. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_UNSUPPORTED_OPCODE)
  457. .arg(message.getOpcode().toText());
  458. makeErrorMessage(impl_->renderer_, message, buffer,
  459. Rcode::NOTIMP(), tsig_context);
  460. } else if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
  461. makeErrorMessage(impl_->renderer_, message, buffer,
  462. Rcode::FORMERR(), tsig_context);
  463. } else {
  464. ConstQuestionPtr question = *message.beginQuestion();
  465. const RRType &qtype = question->getType();
  466. if (qtype == RRType::AXFR()) {
  467. send_answer = impl_->processXfrQuery(io_message, message,
  468. buffer, tsig_context);
  469. } else if (qtype == RRType::IXFR()) {
  470. send_answer = impl_->processXfrQuery(io_message, message,
  471. buffer, tsig_context);
  472. } else {
  473. send_answer = impl_->processNormalQuery(io_message, message,
  474. buffer, tsig_context);
  475. }
  476. }
  477. } catch (const std::exception& ex) {
  478. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE)
  479. .arg(ex.what());
  480. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL());
  481. } catch (...) {
  482. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE_UNKNOWN);
  483. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL());
  484. }
  485. impl_->resumeServer(server, message, send_answer);
  486. }
  487. bool
  488. AuthSrvImpl::processNormalQuery(const IOMessage& io_message, Message& message,
  489. OutputBuffer& buffer,
  490. auto_ptr<TSIGContext> tsig_context)
  491. {
  492. ConstEDNSPtr remote_edns = message.getEDNS();
  493. const bool dnssec_ok = remote_edns && remote_edns->getDNSSECAwareness();
  494. const uint16_t remote_bufsize = remote_edns ? remote_edns->getUDPSize() :
  495. Message::DEFAULT_MAX_UDPSIZE;
  496. message.makeResponse();
  497. message.setHeaderFlag(Message::HEADERFLAG_AA);
  498. message.setRcode(Rcode::NOERROR());
  499. // Increment query counter.
  500. incCounter(io_message.getSocket().getProtocol());
  501. if (remote_edns) {
  502. EDNSPtr local_edns = EDNSPtr(new EDNS());
  503. local_edns->setDNSSECAwareness(dnssec_ok);
  504. local_edns->setUDPSize(AuthSrvImpl::DEFAULT_LOCAL_UDPSIZE);
  505. message.setEDNS(local_edns);
  506. }
  507. try {
  508. // If a memory data source is configured call the separate
  509. // Query::process()
  510. const ConstQuestionPtr question = *message.beginQuestion();
  511. if (memory_client_ && memory_client_class_ == question->getClass()) {
  512. const RRType& qtype = question->getType();
  513. const Name& qname = question->getName();
  514. query_.process(*memory_client_, qname, qtype, message, dnssec_ok);
  515. } else {
  516. datasrc::Query query(message, cache_, dnssec_ok);
  517. data_sources_.doQuery(query);
  518. }
  519. } catch (const Exception& ex) {
  520. LOG_ERROR(auth_logger, AUTH_PROCESS_FAIL).arg(ex.what());
  521. makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL());
  522. return (true);
  523. }
  524. RendererHolder holder(renderer_, &buffer);
  525. const bool udp_buffer =
  526. (io_message.getSocket().getProtocol() == IPPROTO_UDP);
  527. renderer_.setLengthLimit(udp_buffer ? remote_bufsize : 65535);
  528. if (tsig_context.get() != NULL) {
  529. message.toWire(renderer_, *tsig_context);
  530. } else {
  531. message.toWire(renderer_);
  532. }
  533. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_NORMAL_RESPONSE)
  534. .arg(renderer_.getLength()).arg(message);
  535. return (true);
  536. }
  537. bool
  538. AuthSrvImpl::processXfrQuery(const IOMessage& io_message, Message& message,
  539. OutputBuffer& buffer,
  540. auto_ptr<TSIGContext> tsig_context)
  541. {
  542. // Increment query counter.
  543. incCounter(io_message.getSocket().getProtocol());
  544. if (io_message.getSocket().getProtocol() == IPPROTO_UDP) {
  545. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_UDP);
  546. makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
  547. tsig_context);
  548. return (true);
  549. }
  550. try {
  551. if (!xfrout_connected_) {
  552. xfrout_client_.connect();
  553. xfrout_connected_ = true;
  554. }
  555. xfrout_client_.sendXfroutRequestInfo(
  556. io_message.getSocket().getNative(),
  557. io_message.getData(),
  558. io_message.getDataSize());
  559. } catch (const XfroutError& err) {
  560. if (xfrout_connected_) {
  561. // disconnect() may trigger an exception, but since we try it
  562. // only if we've successfully opened it, it shouldn't happen in
  563. // normal condition. Should this occur, we'll propagate it to the
  564. // upper layer.
  565. xfrout_client_.disconnect();
  566. xfrout_connected_ = false;
  567. }
  568. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_ERROR)
  569. .arg(err.what());
  570. makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL(),
  571. tsig_context);
  572. return (true);
  573. }
  574. return (false);
  575. }
  576. bool
  577. AuthSrvImpl::processNotify(const IOMessage& io_message, Message& message,
  578. OutputBuffer& buffer,
  579. std::auto_ptr<TSIGContext> tsig_context)
  580. {
  581. // The incoming notify must contain exactly one question for SOA of the
  582. // zone name.
  583. if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
  584. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_QUESTIONS)
  585. .arg(message.getRRCount(Message::SECTION_QUESTION));
  586. makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
  587. tsig_context);
  588. return (true);
  589. }
  590. ConstQuestionPtr question = *message.beginQuestion();
  591. if (question->getType() != RRType::SOA()) {
  592. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_RRTYPE)
  593. .arg(question->getType().toText());
  594. makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
  595. tsig_context);
  596. return (true);
  597. }
  598. // According to RFC 1996, rcode should be "no error" and AA bit should be
  599. // on, but we don't check these conditions. This behavior is compatible
  600. // with BIND 9.
  601. // TODO check with the conf-mgr whether current server is the auth of the
  602. // zone
  603. // In the code that follows, we simply ignore the notify if any internal
  604. // error happens rather than returning (e.g.) SERVFAIL. RFC 1996 is
  605. // silent about such cases, but there doesn't seem to be anything we can
  606. // improve at the primary server side by sending an error anyway.
  607. if (xfrin_session_ == NULL) {
  608. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NO_XFRIN);
  609. return (false);
  610. }
  611. const string remote_ip_address =
  612. io_message.getRemoteEndpoint().getAddress().toText();
  613. static const string command_template_start =
  614. "{\"command\": [\"notify\", {\"zone_name\" : \"";
  615. static const string command_template_master = "\", \"master\" : \"";
  616. static const string command_template_rrclass = "\", \"zone_class\" : \"";
  617. static const string command_template_end = "\"}]}";
  618. try {
  619. ConstElementPtr notify_command = Element::fromJSON(
  620. command_template_start + question->getName().toText() +
  621. command_template_master + remote_ip_address +
  622. command_template_rrclass + question->getClass().toText() +
  623. command_template_end);
  624. const unsigned int seq =
  625. xfrin_session_->group_sendmsg(notify_command, "Zonemgr",
  626. "*", "*");
  627. ConstElementPtr env, answer, parsed_answer;
  628. xfrin_session_->group_recvmsg(env, answer, false, seq);
  629. int rcode;
  630. parsed_answer = parseAnswer(rcode, answer);
  631. if (rcode != 0) {
  632. LOG_ERROR(auth_logger, AUTH_ZONEMGR_ERROR)
  633. .arg(parsed_answer->str());
  634. return (false);
  635. }
  636. } catch (const Exception& ex) {
  637. LOG_ERROR(auth_logger, AUTH_ZONEMGR_COMMS).arg(ex.what());
  638. return (false);
  639. }
  640. message.makeResponse();
  641. message.setHeaderFlag(Message::HEADERFLAG_AA);
  642. message.setRcode(Rcode::NOERROR());
  643. RendererHolder holder(renderer_, &buffer);
  644. if (tsig_context.get() != NULL) {
  645. message.toWire(renderer_, *tsig_context);
  646. } else {
  647. message.toWire(renderer_);
  648. }
  649. return (true);
  650. }
  651. void
  652. AuthSrvImpl::incCounter(const int protocol) {
  653. // Increment query counter.
  654. if (protocol == IPPROTO_UDP) {
  655. counters_.inc(AuthCounters::SERVER_UDP_QUERY);
  656. } else if (protocol == IPPROTO_TCP) {
  657. counters_.inc(AuthCounters::SERVER_TCP_QUERY);
  658. } else {
  659. // unknown protocol
  660. isc_throw(Unexpected, "Unknown protocol: " << protocol);
  661. }
  662. }
  663. void
  664. AuthSrvImpl::registerStatisticsValidator() {
  665. counters_.registerStatisticsValidator(
  666. boost::bind(&AuthSrvImpl::validateStatistics, this, _1));
  667. }
  668. bool
  669. AuthSrvImpl::validateStatistics(isc::data::ConstElementPtr data) const {
  670. if (config_session_ == NULL) {
  671. return (false);
  672. }
  673. return (
  674. config_session_->getModuleSpec().validateStatistics(
  675. data, true));
  676. }
  677. ConstElementPtr
  678. AuthSrvImpl::setDbFile(ConstElementPtr config) {
  679. ConstElementPtr answer = isc::config::createAnswer();
  680. if (config && config->contains("database_file")) {
  681. db_file_ = config->get("database_file")->stringValue();
  682. } else if (config_session_ != NULL) {
  683. bool is_default;
  684. string item("database_file");
  685. ConstElementPtr value = config_session_->getValue(is_default, item);
  686. ElementPtr final = Element::createMap();
  687. // If the value is the default, and we are running from
  688. // a specific directory ('from build'), we need to use
  689. // a different value than the default (which may not exist)
  690. // (btw, this should not be done here in the end, i think
  691. // the from-source script should have a check for this,
  692. // but for that we need offline access to config, so for
  693. // now this is a decent solution)
  694. if (is_default && getenv("B10_FROM_BUILD")) {
  695. value = Element::create(string(getenv("B10_FROM_BUILD")) +
  696. "/bind10_zones.sqlite3");
  697. }
  698. final->set(item, value);
  699. config = final;
  700. db_file_ = value->stringValue();
  701. } else {
  702. return (answer);
  703. }
  704. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_DATA_SOURCE).arg(db_file_);
  705. // create SQL data source
  706. // Note: the following step is tricky to be exception-safe and to ensure
  707. // exception guarantee: We first need to perform all operations that can
  708. // fail, while acquiring resources in the RAII manner. We then perform
  709. // delete and swap operations which should not fail.
  710. DataSrcPtr datasrc_ptr(DataSrcPtr(new Sqlite3DataSrc));
  711. datasrc_ptr->init(config);
  712. data_sources_.addDataSrc(datasrc_ptr);
  713. // The following code should be exception free.
  714. if (cur_datasrc_ != NULL) {
  715. data_sources_.removeDataSrc(cur_datasrc_);
  716. }
  717. cur_datasrc_ = datasrc_ptr;
  718. return (answer);
  719. }
  720. void
  721. AuthSrvImpl::resumeServer(DNSServer* server, Message& message, bool done) {
  722. if (done) {
  723. counters_.inc(message.getRcode());
  724. }
  725. server->resume(done);
  726. }
  727. ConstElementPtr
  728. AuthSrv::updateConfig(ConstElementPtr new_config) {
  729. try {
  730. // the ModuleCCSession has already checked if we have
  731. // the correct ElementPtr type as specified in our .spec file
  732. if (new_config) {
  733. configureAuthServer(*this, new_config);
  734. }
  735. return (impl_->setDbFile(new_config));
  736. } catch (const isc::Exception& error) {
  737. LOG_ERROR(auth_logger, AUTH_CONFIG_UPDATE_FAIL).arg(error.what());
  738. return (isc::config::createAnswer(1, error.what()));
  739. }
  740. }
  741. bool AuthSrv::submitStatistics() const {
  742. return (impl_->counters_.submitStatistics());
  743. }
  744. uint64_t
  745. AuthSrv::getCounter(const AuthCounters::ServerCounterType type) const {
  746. return (impl_->counters_.getCounter(type));
  747. }
  748. uint64_t
  749. AuthSrv::getCounter(const Opcode opcode) const {
  750. return (impl_->counters_.getCounter(opcode));
  751. }
  752. uint64_t
  753. AuthSrv::getCounter(const Rcode rcode) const {
  754. return (impl_->counters_.getCounter(rcode));
  755. }
  756. const AddressList&
  757. AuthSrv::getListenAddresses() const {
  758. return (impl_->listen_addresses_);
  759. }
  760. void
  761. AuthSrv::setListenAddresses(const AddressList& addresses) {
  762. // For UDP servers we specify the "SYNC_OK" option because in our usage
  763. // it can act in the synchronous mode.
  764. installListenAddresses(addresses, impl_->listen_addresses_, *dnss_,
  765. DNSService::SERVER_SYNC_OK);
  766. }
  767. void
  768. AuthSrv::setDNSService(isc::asiodns::DNSServiceBase& dnss) {
  769. dnss_ = &dnss;
  770. }
  771. void
  772. AuthSrv::setTSIGKeyRing(const boost::shared_ptr<TSIGKeyRing>* keyring) {
  773. impl_->keyring_ = keyring;
  774. }