auth_srv.cc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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 <cc/proto_defs.h>
  21. #include <exceptions/exceptions.h>
  22. #include <util/buffer.h>
  23. #include <dns/edns.h>
  24. #include <dns/exceptions.h>
  25. #include <dns/messagerenderer.h>
  26. #include <dns/name.h>
  27. #include <dns/question.h>
  28. #include <dns/opcode.h>
  29. #include <dns/rcode.h>
  30. #include <dns/rrset.h>
  31. #include <dns/rrttl.h>
  32. #include <dns/message.h>
  33. #include <dns/tsig.h>
  34. #include <asiodns/dns_service.h>
  35. #include <datasrc/exceptions.h>
  36. #include <datasrc/client_list.h>
  37. #include <xfr/xfrout_client.h>
  38. #include <auth/common.h>
  39. #include <auth/auth_config.h>
  40. #include <auth/auth_srv.h>
  41. #include <auth/query.h>
  42. #include <auth/statistics.h>
  43. #include <auth/auth_log.h>
  44. #include <auth/datasrc_clients_mgr.h>
  45. #include <boost/bind.hpp>
  46. #include <boost/lexical_cast.hpp>
  47. #include <boost/scoped_ptr.hpp>
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <iostream>
  51. #include <vector>
  52. #include <memory>
  53. #include <sys/types.h>
  54. #include <netinet/in.h>
  55. using namespace std;
  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 boost::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 stats_attrs Object to store message attributes in for use
  263. /// with statistics
  264. /// \param done If true, it indicates there is a response.
  265. /// this value will be passed to server->resume(bool)
  266. void resumeServer(isc::asiodns::DNSServer* server,
  267. isc::dns::Message& message,
  268. MessageAttributes& stats_attrs,
  269. const bool done);
  270. /// Are we currently subscribed to the SegmentReader group?
  271. bool readers_group_subscribed_;
  272. private:
  273. bool xfrout_connected_;
  274. AbstractXfroutClient& xfrout_client_;
  275. auth::Query query_;
  276. };
  277. AuthSrvImpl::AuthSrvImpl(AbstractXfroutClient& xfrout_client,
  278. BaseSocketSessionForwarder& ddns_forwarder) :
  279. config_session_(NULL),
  280. xfrin_session_(NULL),
  281. counters_(),
  282. keyring_(NULL),
  283. datasrc_clients_mgr_(io_service_),
  284. ddns_base_forwarder_(ddns_forwarder),
  285. ddns_forwarder_(NULL),
  286. readers_group_subscribed_(false),
  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. AuthSrv::AuthSrv(isc::xfr::AbstractXfroutClient& xfrout_client,
  334. isc::util::io::BaseSocketSessionForwarder& ddns_forwarder) :
  335. dnss_(NULL)
  336. {
  337. impl_ = new AuthSrvImpl(xfrout_client, ddns_forwarder);
  338. dns_lookup_ = new MessageLookup(this);
  339. dns_answer_ = new MessageAnswer(this);
  340. }
  341. void
  342. AuthSrv::stop() {
  343. impl_->io_service_.stop();
  344. }
  345. AuthSrv::~AuthSrv() {
  346. delete impl_;
  347. delete dns_lookup_;
  348. delete dns_answer_;
  349. }
  350. namespace {
  351. class QuestionInserter {
  352. public:
  353. QuestionInserter(Message& message) : message_(message) {}
  354. void operator()(const QuestionPtr question) {
  355. message_.addQuestion(question);
  356. }
  357. Message& message_;
  358. };
  359. void
  360. makeErrorMessage(MessageRenderer& renderer, Message& message,
  361. OutputBuffer& buffer, const Rcode& rcode,
  362. MessageAttributes& stats_attrs,
  363. std::auto_ptr<TSIGContext> tsig_context =
  364. std::auto_ptr<TSIGContext>())
  365. {
  366. // extract the parameters that should be kept.
  367. // XXX: with the current implementation, it's not easy to set EDNS0
  368. // depending on whether the query had it. So we'll simply omit it.
  369. const qid_t qid = message.getQid();
  370. const bool rd = message.getHeaderFlag(Message::HEADERFLAG_RD);
  371. const bool cd = message.getHeaderFlag(Message::HEADERFLAG_CD);
  372. const Opcode& opcode = message.getOpcode();
  373. vector<QuestionPtr> questions;
  374. // If this is an error to a query or notify, we should also copy the
  375. // question section.
  376. if (opcode == Opcode::QUERY() || opcode == Opcode::NOTIFY()) {
  377. questions.assign(message.beginQuestion(), message.endQuestion());
  378. }
  379. message.clear(Message::RENDER);
  380. message.setQid(qid);
  381. message.setOpcode(opcode);
  382. message.setHeaderFlag(Message::HEADERFLAG_QR);
  383. if (rd) {
  384. message.setHeaderFlag(Message::HEADERFLAG_RD);
  385. }
  386. if (cd) {
  387. message.setHeaderFlag(Message::HEADERFLAG_CD);
  388. }
  389. for_each(questions.begin(), questions.end(), QuestionInserter(message));
  390. message.setRcode(rcode);
  391. RendererHolder holder(renderer, &buffer, stats_attrs);
  392. message.toWire(renderer, tsig_context.get());
  393. stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
  394. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_ERROR_RESPONSE)
  395. .arg(renderer.getLength()).arg(message);
  396. }
  397. }
  398. IOService&
  399. AuthSrv::getIOService() {
  400. return (impl_->io_service_);
  401. }
  402. isc::auth::DataSrcClientsMgr&
  403. AuthSrv::getDataSrcClientsMgr() {
  404. return (impl_->datasrc_clients_mgr_);
  405. }
  406. void
  407. AuthSrv::setXfrinSession(AbstractSession* xfrin_session) {
  408. impl_->xfrin_session_ = xfrin_session;
  409. }
  410. void
  411. AuthSrv::setConfigSession(ModuleCCSession* config_session) {
  412. impl_->config_session_ = config_session;
  413. }
  414. ModuleCCSession*
  415. AuthSrv::getConfigSession() const {
  416. return (impl_->config_session_);
  417. }
  418. void
  419. AuthSrv::processMessage(const IOMessage& io_message, Message& message,
  420. OutputBuffer& buffer, DNSServer* server)
  421. {
  422. InputBuffer request_buffer(io_message.getData(), io_message.getDataSize());
  423. MessageAttributes stats_attrs;
  424. stats_attrs.setRequestIPVersion(
  425. io_message.getRemoteEndpoint().getFamily());
  426. stats_attrs.setRequestTransportProtocol(
  427. io_message.getRemoteEndpoint().getProtocol());
  428. // First, check the header part. If we fail even for the base header,
  429. // just drop the message.
  430. try {
  431. message.parseHeader(request_buffer);
  432. // Ignore all responses.
  433. if (message.getHeaderFlag(Message::HEADERFLAG_QR)) {
  434. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_RECEIVED);
  435. impl_->resumeServer(server, message, stats_attrs, false);
  436. return;
  437. }
  438. } catch (const isc::Exception& ex) {
  439. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_HEADER_PARSE_FAIL)
  440. .arg(ex.what());
  441. impl_->resumeServer(server, message, stats_attrs, false);
  442. return;
  443. }
  444. stats_attrs.setRequestRD(message.getHeaderFlag(Message::HEADERFLAG_RD));
  445. const Opcode& opcode = message.getOpcode();
  446. // Get opcode at this point; for all requests regardless of message body
  447. // sanity check.
  448. stats_attrs.setRequestOpCode(opcode);
  449. try {
  450. // Parse the message.
  451. message.fromWire(request_buffer);
  452. } catch (const DNSProtocolError& error) {
  453. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PROTOCOL_FAILURE)
  454. .arg(error.getRcode().toText()).arg(error.what());
  455. makeErrorMessage(impl_->renderer_, message, buffer, error.getRcode(),
  456. stats_attrs);
  457. impl_->resumeServer(server, message, stats_attrs, true);
  458. return;
  459. } catch (const isc::Exception& ex) {
  460. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PARSE_FAILED)
  461. .arg(ex.what());
  462. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
  463. stats_attrs);
  464. impl_->resumeServer(server, message, stats_attrs, true);
  465. return;
  466. } // other exceptions will be handled at a higher layer.
  467. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_PACKET_RECEIVED)
  468. .arg(message);
  469. // Perform further protocol-level validation.
  470. // TSIG first
  471. // If this is set to something, we know we need to answer with TSIG as well
  472. std::auto_ptr<TSIGContext> tsig_context;
  473. const TSIGRecord* tsig_record(message.getTSIGRecord());
  474. TSIGError tsig_error(TSIGError::NOERROR());
  475. // Do we do TSIG?
  476. // The keyring can be null if we're in test
  477. if (impl_->keyring_ != NULL && tsig_record != NULL) {
  478. tsig_context.reset(new TSIGContext(tsig_record->getName(),
  479. tsig_record->getRdata().
  480. getAlgorithm(),
  481. **impl_->keyring_));
  482. tsig_error = tsig_context->verify(tsig_record, io_message.getData(),
  483. io_message.getDataSize());
  484. stats_attrs.setRequestTSIG(true, tsig_error != TSIGError::NOERROR());
  485. }
  486. if (tsig_error != TSIGError::NOERROR()) {
  487. makeErrorMessage(impl_->renderer_, message, buffer,
  488. tsig_error.toRcode(), stats_attrs, tsig_context);
  489. impl_->resumeServer(server, message, stats_attrs, true);
  490. return;
  491. }
  492. bool send_answer = true;
  493. try {
  494. // note: This can only be reliable after TSIG check succeeds.
  495. ConstEDNSPtr edns = message.getEDNS();
  496. if (edns) {
  497. stats_attrs.setRequestEDNS0(true);
  498. stats_attrs.setRequestDO(edns->getDNSSECAwareness());
  499. }
  500. // note: This can only be reliable after TSIG check succeeds.
  501. if (opcode == Opcode::NOTIFY()) {
  502. send_answer = impl_->processNotify(io_message, message, buffer,
  503. tsig_context, stats_attrs);
  504. } else if (opcode == Opcode::UPDATE()) {
  505. if (impl_->ddns_forwarder_) {
  506. send_answer = impl_->processUpdate(io_message);
  507. } else {
  508. makeErrorMessage(impl_->renderer_, message, buffer,
  509. Rcode::NOTIMP(), stats_attrs, tsig_context);
  510. }
  511. } else if (opcode != Opcode::QUERY()) {
  512. const IOEndpoint& remote_ep = io_message.getRemoteEndpoint();
  513. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_UNSUPPORTED_OPCODE)
  514. .arg(message.getOpcode().toText()).arg(remote_ep);
  515. makeErrorMessage(impl_->renderer_, message, buffer,
  516. Rcode::NOTIMP(), stats_attrs, tsig_context);
  517. } else if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
  518. makeErrorMessage(impl_->renderer_, message, buffer,
  519. Rcode::FORMERR(), stats_attrs, tsig_context);
  520. } else {
  521. ConstQuestionPtr question = *message.beginQuestion();
  522. const RRType& qtype = question->getType();
  523. if (qtype == RRType::AXFR()) {
  524. send_answer = impl_->processXfrQuery(io_message, message,
  525. buffer, tsig_context,
  526. stats_attrs);
  527. } else if (qtype == RRType::IXFR()) {
  528. send_answer = impl_->processXfrQuery(io_message, message,
  529. buffer, tsig_context,
  530. stats_attrs);
  531. } else {
  532. send_answer = impl_->processNormalQuery(io_message, edns,
  533. message, buffer,
  534. tsig_context,
  535. stats_attrs);
  536. }
  537. }
  538. } catch (const std::exception& ex) {
  539. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE)
  540. .arg(ex.what());
  541. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
  542. stats_attrs);
  543. } catch (...) {
  544. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE_UNKNOWN);
  545. makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
  546. stats_attrs);
  547. }
  548. impl_->resumeServer(server, message, stats_attrs, send_answer);
  549. }
  550. bool
  551. AuthSrvImpl::processNormalQuery(const IOMessage& io_message,
  552. ConstEDNSPtr remote_edns, Message& message,
  553. OutputBuffer& buffer,
  554. auto_ptr<TSIGContext> tsig_context,
  555. MessageAttributes& stats_attrs)
  556. {
  557. const bool dnssec_ok = remote_edns && remote_edns->getDNSSECAwareness();
  558. const uint16_t remote_bufsize = remote_edns ? remote_edns->getUDPSize() :
  559. Message::DEFAULT_MAX_UDPSIZE;
  560. message.makeResponse();
  561. message.setHeaderFlag(Message::HEADERFLAG_AA);
  562. message.setRcode(Rcode::NOERROR());
  563. if (remote_edns) {
  564. EDNSPtr local_edns = EDNSPtr(new EDNS());
  565. local_edns->setDNSSECAwareness(dnssec_ok);
  566. local_edns->setUDPSize(AuthSrvImpl::DEFAULT_LOCAL_UDPSIZE);
  567. message.setEDNS(local_edns);
  568. }
  569. // Get access to data source client list through the holder and keep
  570. // the holder until the processing and rendering is done to avoid
  571. // race with any other thread(s) such as the background loader.
  572. auth::DataSrcClientsMgr::Holder datasrc_holder(datasrc_clients_mgr_);
  573. try {
  574. const ConstQuestionPtr question = *message.beginQuestion();
  575. const boost::shared_ptr<datasrc::ClientList>
  576. list(datasrc_holder.findClientList(question->getClass()));
  577. if (list) {
  578. const RRType& qtype = question->getType();
  579. const Name& qname = question->getName();
  580. query_.process(*list, qname, qtype, message, dnssec_ok);
  581. } else {
  582. makeErrorMessage(renderer_, message, buffer, Rcode::REFUSED(),
  583. stats_attrs);
  584. return (true);
  585. }
  586. } catch (const isc::Exception& ex) {
  587. LOG_ERROR(auth_logger, AUTH_PROCESS_FAIL).arg(ex.what());
  588. makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL(),
  589. stats_attrs);
  590. return (true);
  591. }
  592. RendererHolder holder(renderer_, &buffer, stats_attrs);
  593. const bool udp_buffer =
  594. (io_message.getSocket().getProtocol() == IPPROTO_UDP);
  595. renderer_.setLengthLimit(udp_buffer ? remote_bufsize : 65535);
  596. message.toWire(renderer_, tsig_context.get());
  597. stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
  598. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_NORMAL_RESPONSE)
  599. .arg(renderer_.getLength()).arg(message);
  600. return (true);
  601. // The message can contain some data from the locked resource. But outside
  602. // this method, we touch only the RCode of it, so it should be safe.
  603. // Lock on datasrc_clients_mgr_ acquired by datasrc_holder is
  604. // released here upon its deletion.
  605. }
  606. bool
  607. AuthSrvImpl::processXfrQuery(const IOMessage& io_message, Message& message,
  608. OutputBuffer& buffer,
  609. auto_ptr<TSIGContext> tsig_context,
  610. MessageAttributes& stats_attrs)
  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. stats_attrs, 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_PROBLEM)
  637. .arg(err.what());
  638. makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL(),
  639. stats_attrs, 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. MessageAttributes& stats_attrs)
  649. {
  650. const IOEndpoint& remote_ep = io_message.getRemoteEndpoint(); // for logs
  651. // The incoming notify must contain exactly one question for SOA of the
  652. // zone name.
  653. if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
  654. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_QUESTIONS)
  655. .arg(message.getRRCount(Message::SECTION_QUESTION));
  656. makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
  657. stats_attrs, tsig_context);
  658. return (true);
  659. }
  660. ConstQuestionPtr question = *message.beginQuestion();
  661. if (question->getType() != RRType::SOA()) {
  662. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_RRTYPE)
  663. .arg(question->getType().toText());
  664. makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
  665. stats_attrs, tsig_context);
  666. return (true);
  667. }
  668. // According to RFC 1996, rcode should be "no error" and AA bit should be
  669. // on, but we don't check these conditions. This behavior is compatible
  670. // with BIND 9.
  671. // See if we have the specified zone in our data sources; if not return
  672. // NOTAUTH, following BIND 9 (this is not specified in RFC 1996).
  673. bool is_auth = false;
  674. {
  675. auth::DataSrcClientsMgr::Holder datasrc_holder(datasrc_clients_mgr_);
  676. const boost::shared_ptr<datasrc::ClientList> dsrc_clients =
  677. datasrc_holder.findClientList(question->getClass());
  678. is_auth = dsrc_clients &&
  679. dsrc_clients->find(question->getName(), true, false).exact_match_;
  680. }
  681. if (!is_auth) {
  682. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RECEIVED_NOTIFY_NOTAUTH)
  683. .arg(question->getName()).arg(question->getClass()).arg(remote_ep);
  684. makeErrorMessage(renderer_, message, buffer, Rcode::NOTAUTH(),
  685. stats_attrs, tsig_context);
  686. return (true);
  687. }
  688. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RECEIVED_NOTIFY)
  689. .arg(question->getName()).arg(question->getClass()).arg(remote_ep);
  690. // xfrin_session_ should have been set and never be replaced except in
  691. // tests; otherwise it's an internal bug. assert() may be too strong,
  692. // but processMessage() will catch all exceptions, so there's no better
  693. // way.
  694. assert(xfrin_session_);
  695. const string remote_ip_address = remote_ep.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. CC_INSTANCE_WILDCARD,
  710. CC_INSTANCE_WILDCARD, true);
  711. ConstElementPtr env, answer, parsed_answer;
  712. xfrin_session_->group_recvmsg(env, answer, false, seq);
  713. int rcode;
  714. parsed_answer = parseAnswer(rcode, answer);
  715. if (rcode == CC_REPLY_NO_RECPT) {
  716. // This can happen when Zonemgr is not running. When we support
  717. // notification-based membership framework, we should check if it's
  718. // supposed to be running and shouldn't even send the command if
  719. // not. Until then, we log this event at the debug level as we
  720. // don't know whether it's a real trouble or intentional
  721. // configuration. (Also, when it's done, maybe we should simply
  722. // propagate the exception and return SERVFAIL to suppress further
  723. // NOTIFY).
  724. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_ZONEMGR_NOTEXIST);
  725. return (false);
  726. } else if (rcode != CC_REPLY_SUCCESS) {
  727. LOG_ERROR(auth_logger, AUTH_ZONEMGR_ERROR)
  728. .arg(parsed_answer->str());
  729. return (false);
  730. }
  731. } catch (const isc::Exception& ex) {
  732. LOG_ERROR(auth_logger, AUTH_ZONEMGR_COMMS).arg(ex.what());
  733. return (false);
  734. }
  735. message.makeResponse();
  736. message.setHeaderFlag(Message::HEADERFLAG_AA);
  737. message.setRcode(Rcode::NOERROR());
  738. RendererHolder holder(renderer_, &buffer, stats_attrs);
  739. message.toWire(renderer_, tsig_context.get());
  740. stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
  741. return (true);
  742. }
  743. bool
  744. AuthSrvImpl::processUpdate(const IOMessage& io_message)
  745. {
  746. // Push the update request to a separate process via the forwarder.
  747. // On successful push, the request shouldn't be responded from b10-auth,
  748. // so we return false.
  749. ddns_forwarder_->push(io_message);
  750. return (false);
  751. }
  752. void
  753. AuthSrvImpl::resumeServer(DNSServer* server, Message& message,
  754. MessageAttributes& stats_attrs,
  755. const bool done) {
  756. counters_.inc(stats_attrs, message, done);
  757. server->resume(done);
  758. }
  759. ConstElementPtr
  760. AuthSrv::updateConfig(ConstElementPtr new_config) {
  761. try {
  762. // the ModuleCCSession has already checked if we have
  763. // the correct ElementPtr type as specified in our .spec file
  764. if (new_config) {
  765. configureAuthServer(*this, new_config);
  766. }
  767. return (isc::config::createAnswer());
  768. } catch (const isc::Exception& error) {
  769. LOG_ERROR(auth_logger, AUTH_CONFIG_UPDATE_FAIL).arg(error.what());
  770. return (isc::config::createAnswer(1, error.what()));
  771. }
  772. }
  773. ConstElementPtr AuthSrv::getStatistics() const {
  774. return (impl_->counters_.get());
  775. }
  776. const AddressList&
  777. AuthSrv::getListenAddresses() const {
  778. return (impl_->listen_addresses_);
  779. }
  780. void
  781. AuthSrv::setListenAddresses(const AddressList& addresses) {
  782. // For UDP servers we specify the "SYNC_OK" option because in our usage
  783. // it can act in the synchronous mode.
  784. installListenAddresses(addresses, impl_->listen_addresses_, *dnss_,
  785. DNSService::SERVER_SYNC_OK);
  786. }
  787. void
  788. AuthSrv::setDNSService(isc::asiodns::DNSServiceBase& dnss) {
  789. dnss_ = &dnss;
  790. }
  791. void
  792. AuthSrv::setTSIGKeyRing(const boost::shared_ptr<TSIGKeyRing>* keyring) {
  793. impl_->keyring_ = keyring;
  794. }
  795. void
  796. AuthSrv::createDDNSForwarder() {
  797. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_START_DDNS_FORWARDER);
  798. impl_->ddns_forwarder_.reset(
  799. new SocketSessionForwarderHolder("update",
  800. impl_->ddns_base_forwarder_));
  801. }
  802. void
  803. AuthSrv::destroyDDNSForwarder() {
  804. if (impl_->ddns_forwarder_) {
  805. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STOP_DDNS_FORWARDER);
  806. impl_->ddns_forwarder_.reset();
  807. }
  808. }
  809. void
  810. AuthSrv::setTCPRecvTimeout(size_t timeout) {
  811. dnss_->setTCPRecvTimeout(timeout);
  812. }
  813. namespace {
  814. bool
  815. hasMappedSegment(auth::DataSrcClientsMgr& mgr) {
  816. auth::DataSrcClientsMgr::Holder holder(mgr);
  817. const std::vector<dns::RRClass>& classes(holder.getClasses());
  818. BOOST_FOREACH(const dns::RRClass& rrclass, classes) {
  819. const boost::shared_ptr<datasrc::ConfigurableClientList>&
  820. list(holder.findClientList(rrclass));
  821. const std::vector<DataSourceStatus>& states(list->getStatus());
  822. BOOST_FOREACH(const datasrc::DataSourceStatus& status, states) {
  823. if (status.getSegmentState() != datasrc::SEGMENT_UNUSED &&
  824. status.getSegmentType() == "mapped")
  825. // We use some segment and it's not a local one, so it
  826. // must be remote.
  827. return true;
  828. }
  829. }
  830. // No remote segment found in any of the lists
  831. return false;
  832. }
  833. }
  834. void
  835. AuthSrv::listsReconfigured() {
  836. const bool has_remote = hasMappedSegment(impl_->datasrc_clients_mgr_);
  837. if (has_remote && !impl_->readers_group_subscribed_) {
  838. impl_->config_session_->subscribe("SegmentReader");
  839. impl_->config_session_->
  840. setUnhandledCallback(boost::bind(&AuthSrv::foreignCommand, this,
  841. _1, _2, _3));
  842. impl_->readers_group_subscribed_ = true;
  843. } else if (!has_remote && impl_->readers_group_subscribed_) {
  844. impl_->config_session_->unsubscribe("SegmentReader");
  845. impl_->config_session_->
  846. setUnhandledCallback(isc::config::ModuleCCSession::
  847. UnhandledCallback());
  848. impl_->readers_group_subscribed_ = false;
  849. }
  850. }
  851. void
  852. AuthSrv::reconfigureDone(ConstElementPtr params) {
  853. // ACK the segment
  854. impl_->config_session_->
  855. groupSendMsg(isc::config::createCommand("segment_info_update_ack",
  856. params), "MemMgr");
  857. }
  858. void
  859. AuthSrv::foreignCommand(const std::string& command, const std::string&,
  860. const ConstElementPtr& params)
  861. {
  862. if (command == "segment_info_update") {
  863. impl_->datasrc_clients_mgr_.
  864. segmentInfoUpdate(params, boost::bind(&AuthSrv::reconfigureDone,
  865. this, params));
  866. }
  867. }