auth_srv.cc 32 KB

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