auth_srv.cc 33 KB

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