auth_srv.cc 33 KB

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