auth_srv.cc 33 KB

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