auth_srv.cc 34 KB

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