dhcp6_test_utils.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // Copyright (C) 2013-2014 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. /// @file dhcp6_test_utils.h
  15. ///
  16. /// @brief This file contains utility classes used for DHCPv6 server testing
  17. #ifndef DHCP6_TEST_UTILS_H
  18. #define DHCP6_TEST_UTILS_H
  19. #include <gtest/gtest.h>
  20. #include <dhcp/pkt6.h>
  21. #include <dhcp/option6_ia.h>
  22. #include <dhcp/option6_iaaddr.h>
  23. #include <dhcp/option6_iaprefix.h>
  24. #include <dhcp/option_int_array.h>
  25. #include <dhcp/option_custom.h>
  26. #include <dhcp/iface_mgr.h>
  27. #include <dhcpsrv/cfgmgr.h>
  28. #include <dhcpsrv/lease_mgr.h>
  29. #include <dhcpsrv/lease_mgr_factory.h>
  30. #include <dhcp6/dhcp6_srv.h>
  31. #include <hooks/hooks_manager.h>
  32. #include <config/ccsession.h>
  33. #include <list>
  34. namespace isc {
  35. namespace test {
  36. /// @brief "naked" Dhcpv6Srv class that exposes internal members
  37. class NakedDhcpv6Srv: public isc::dhcp::Dhcpv6Srv {
  38. public:
  39. NakedDhcpv6Srv(uint16_t port) : isc::dhcp::Dhcpv6Srv(port) {
  40. // Open the "memfile" database for leases
  41. std::string memfile = "type=memfile";
  42. isc::dhcp::LeaseMgrFactory::create(memfile);
  43. }
  44. /// @brief fakes packet reception
  45. /// @param timeout ignored
  46. ///
  47. /// The method receives all packets queued in receive
  48. /// queue, one after another. Once the queue is empty,
  49. /// it initiates the shutdown procedure.
  50. ///
  51. /// See fake_received_ field for description
  52. virtual isc::dhcp::Pkt6Ptr receivePacket(int /*timeout*/) {
  53. // If there is anything prepared as fake incoming
  54. // traffic, use it
  55. if (!fake_received_.empty()) {
  56. isc::dhcp::Pkt6Ptr pkt = fake_received_.front();
  57. fake_received_.pop_front();
  58. return (pkt);
  59. }
  60. // If not, just trigger shutdown and
  61. // return immediately
  62. shutdown();
  63. return (isc::dhcp::Pkt6Ptr());
  64. }
  65. /// @brief fake packet sending
  66. ///
  67. /// Pretend to send a packet, but instead just store
  68. /// it in fake_send_ list where test can later inspect
  69. /// server's response.
  70. virtual void sendPacket(const isc::dhcp::Pkt6Ptr& pkt) {
  71. fake_sent_.push_back(pkt);
  72. }
  73. /// @brief adds a packet to fake receive queue
  74. ///
  75. /// See fake_received_ field for description
  76. void fakeReceive(const isc::dhcp::Pkt6Ptr& pkt) {
  77. fake_received_.push_back(pkt);
  78. }
  79. virtual ~NakedDhcpv6Srv() {
  80. // Close the lease database
  81. isc::dhcp::LeaseMgrFactory::destroy();
  82. }
  83. using Dhcpv6Srv::processSolicit;
  84. using Dhcpv6Srv::processRequest;
  85. using Dhcpv6Srv::processRenew;
  86. using Dhcpv6Srv::processRelease;
  87. using Dhcpv6Srv::processClientFqdn;
  88. using Dhcpv6Srv::createNameChangeRequests;
  89. using Dhcpv6Srv::createRemovalNameChangeRequest;
  90. using Dhcpv6Srv::createStatusCode;
  91. using Dhcpv6Srv::selectSubnet;
  92. using Dhcpv6Srv::testServerID;
  93. using Dhcpv6Srv::sanityCheck;
  94. using Dhcpv6Srv::classifyPacket;
  95. using Dhcpv6Srv::loadServerID;
  96. using Dhcpv6Srv::writeServerID;
  97. using Dhcpv6Srv::unpackOptions;
  98. using Dhcpv6Srv::name_change_reqs_;
  99. using Dhcpv6Srv::VENDOR_CLASS_PREFIX;
  100. /// @brief packets we pretend to receive
  101. ///
  102. /// Instead of setting up sockets on interfaces that change between
  103. /// OSes, it is much easier to fake packet reception. This is a list
  104. /// of packets that we pretend to have received. You can schedule
  105. /// new packets to be received using fakeReceive() and
  106. /// NakedDhcpv6Srv::receivePacket() methods.
  107. std::list<isc::dhcp::Pkt6Ptr> fake_received_;
  108. std::list<isc::dhcp::Pkt6Ptr> fake_sent_;
  109. };
  110. static const char* DUID_FILE = "server-id-test.txt";
  111. // test fixture for any tests requiring blank/empty configuration
  112. // serves as base class for additional tests
  113. class NakedDhcpv6SrvTest : public ::testing::Test {
  114. public:
  115. NakedDhcpv6SrvTest() : rcode_(-1) {
  116. // it's ok if that fails. There should not be such a file anyway
  117. unlink(DUID_FILE);
  118. const isc::dhcp::IfaceMgr::IfaceCollection& ifaces =
  119. isc::dhcp::IfaceMgr::instance().getIfaces();
  120. // There must be some interface detected
  121. if (ifaces.empty()) {
  122. // We can't use ASSERT in constructor
  123. ADD_FAILURE() << "No interfaces detected.";
  124. }
  125. valid_iface_ = ifaces.begin()->getName();
  126. }
  127. // Generate IA_NA or IA_PD option with specified parameters
  128. boost::shared_ptr<isc::dhcp::Option6IA> generateIA
  129. (uint16_t type, uint32_t iaid, uint32_t t1, uint32_t t2);
  130. /// @brief generates interface-id option, based on text
  131. ///
  132. /// @param iface_id textual representation of the interface-id content
  133. ///
  134. /// @return pointer to the option object
  135. isc::dhcp::OptionPtr generateInterfaceId(const std::string& iface_id) {
  136. isc::dhcp::OptionBuffer tmp(iface_id.begin(), iface_id.end());
  137. return (isc::dhcp::OptionPtr
  138. (new isc::dhcp::Option(isc::dhcp::Option::V6,
  139. D6O_INTERFACE_ID, tmp)));
  140. }
  141. // Generate client-id option
  142. isc::dhcp::OptionPtr generateClientId(size_t duid_size = 32) {
  143. isc::dhcp::OptionBuffer clnt_duid(duid_size);
  144. for (int i = 0; i < duid_size; i++) {
  145. clnt_duid[i] = 100 + i;
  146. }
  147. duid_ = isc::dhcp::DuidPtr(new isc::dhcp::DUID(clnt_duid));
  148. return (isc::dhcp::OptionPtr
  149. (new isc::dhcp::Option(isc::dhcp::Option::V6, D6O_CLIENTID,
  150. clnt_duid.begin(),
  151. clnt_duid.begin() + duid_size)));
  152. }
  153. // Checks if server response (ADVERTISE or REPLY) includes proper
  154. // server-id.
  155. void checkServerId(const isc::dhcp::Pkt6Ptr& rsp,
  156. const isc::dhcp::OptionPtr& expected_srvid)
  157. {
  158. // check that server included its server-id
  159. isc::dhcp::OptionPtr tmp = rsp->getOption(D6O_SERVERID);
  160. EXPECT_EQ(tmp->getType(), expected_srvid->getType() );
  161. ASSERT_EQ(tmp->len(), expected_srvid->len() );
  162. EXPECT_TRUE(tmp->getData() == expected_srvid->getData());
  163. }
  164. // Checks if server response (ADVERTISE or REPLY) includes proper
  165. // client-id.
  166. void checkClientId(const isc::dhcp::Pkt6Ptr& rsp,
  167. const isc::dhcp::OptionPtr& expected_clientid)
  168. {
  169. // check that server included our own client-id
  170. isc::dhcp::OptionPtr tmp = rsp->getOption(D6O_CLIENTID);
  171. ASSERT_TRUE(tmp);
  172. EXPECT_EQ(expected_clientid->getType(), tmp->getType());
  173. ASSERT_EQ(expected_clientid->len(), tmp->len());
  174. // check that returned client-id is valid
  175. EXPECT_TRUE(expected_clientid->getData() == tmp->getData());
  176. }
  177. // Checks if server response is a NAK
  178. void checkNakResponse(const isc::dhcp::Pkt6Ptr& rsp,
  179. uint8_t expected_message_type,
  180. uint32_t expected_transid,
  181. uint16_t expected_status_code)
  182. {
  183. // Check if we get response at all
  184. checkResponse(rsp, expected_message_type, expected_transid);
  185. // Check that IA_NA was returned
  186. isc::dhcp::OptionPtr option_ia_na = rsp->getOption(D6O_IA_NA);
  187. ASSERT_TRUE(option_ia_na);
  188. // check that the status is no address available
  189. boost::shared_ptr<isc::dhcp::Option6IA> ia =
  190. boost::dynamic_pointer_cast<isc::dhcp::Option6IA>(option_ia_na);
  191. ASSERT_TRUE(ia);
  192. checkIA_NAStatusCode(ia, expected_status_code);
  193. }
  194. // Checks that server rejected IA_NA, i.e. that it has no addresses and
  195. // that expected status code really appears there. In some limited cases
  196. // (reply to RELEASE) it may be used to verify positive case, where
  197. // IA_NA response is expected to not include address.
  198. //
  199. // Status code indicates type of error encountered (in theory it can also
  200. // indicate success, but servers typically don't send success status
  201. // as this is the default result and it saves bandwidth)
  202. void checkIA_NAStatusCode
  203. (const boost::shared_ptr<isc::dhcp::Option6IA>& ia,
  204. uint16_t expected_status_code)
  205. {
  206. // Make sure there is no address assigned.
  207. EXPECT_FALSE(ia->getOption(D6O_IAADDR));
  208. // T1, T2 should be zeroed
  209. EXPECT_EQ(0, ia->getT1());
  210. EXPECT_EQ(0, ia->getT2());
  211. isc::dhcp::OptionCustomPtr status =
  212. boost::dynamic_pointer_cast<isc::dhcp::OptionCustom>
  213. (ia->getOption(D6O_STATUS_CODE));
  214. // It is ok to not include status success as this is the default
  215. // behavior
  216. if (expected_status_code == STATUS_Success && !status) {
  217. return;
  218. }
  219. EXPECT_TRUE(status);
  220. if (status) {
  221. // We don't have dedicated class for status code, so let's
  222. // just interpret first 2 bytes as status. Remainder of the
  223. // status code option content is just a text explanation
  224. // what went wrong.
  225. EXPECT_EQ(static_cast<uint16_t>(expected_status_code),
  226. status->readInteger<uint16_t>(0));
  227. }
  228. }
  229. void checkMsgStatusCode(const isc::dhcp::Pkt6Ptr& msg,
  230. uint16_t expected_status)
  231. {
  232. isc::dhcp::OptionCustomPtr status =
  233. boost::dynamic_pointer_cast<isc::dhcp::OptionCustom>
  234. (msg->getOption(D6O_STATUS_CODE));
  235. // It is ok to not include status success as this is the default
  236. // behavior
  237. if (expected_status == STATUS_Success && !status) {
  238. return;
  239. }
  240. EXPECT_TRUE(status);
  241. if (status) {
  242. // We don't have dedicated class for status code, so let's
  243. // just interpret first 2 bytes as status. Remainder of the
  244. // status code option content is just a text explanation
  245. // what went wrong.
  246. EXPECT_EQ(static_cast<uint16_t>(expected_status),
  247. status->readInteger<uint16_t>(0));
  248. }
  249. }
  250. // Basic checks for generated response (message type and transaction-id).
  251. void checkResponse(const isc::dhcp::Pkt6Ptr& rsp,
  252. uint8_t expected_message_type,
  253. uint32_t expected_transid) {
  254. ASSERT_TRUE(rsp);
  255. EXPECT_EQ(expected_message_type, rsp->getType());
  256. EXPECT_EQ(expected_transid, rsp->getTransid());
  257. }
  258. virtual ~NakedDhcpv6SrvTest() {
  259. // Let's clean up if there is such a file.
  260. unlink(DUID_FILE);
  261. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  262. .deregisterAllCallouts("buffer6_receive");
  263. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  264. .deregisterAllCallouts("buffer6_send");
  265. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  266. .deregisterAllCallouts("lease6_renew");
  267. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  268. .deregisterAllCallouts("lease6_release");
  269. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  270. .deregisterAllCallouts("pkt6_receive");
  271. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  272. .deregisterAllCallouts("pkt6_send");
  273. isc::hooks::HooksManager::preCalloutsLibraryHandle()
  274. .deregisterAllCallouts("subnet6_select");
  275. };
  276. // A DUID used in most tests (typically as client-id)
  277. isc::dhcp::DuidPtr duid_;
  278. int rcode_;
  279. isc::data::ConstElementPtr comment_;
  280. // Name of a valid network interface
  281. std::string valid_iface_;
  282. };
  283. // Provides suport for tests against a preconfigured subnet6
  284. // extends upon NakedDhcp6SrvTest
  285. class Dhcpv6SrvTest : public NakedDhcpv6SrvTest {
  286. public:
  287. /// Name of the server-id file (used in server-id tests)
  288. /// @brief Constructor that initalizes a simple default configuration
  289. ///
  290. /// Sets up a single subnet6 with one pool for addresses and second
  291. /// pool for prefixes.
  292. Dhcpv6SrvTest();
  293. /// @brief destructor
  294. ///
  295. /// Removes existing configuration.
  296. ~Dhcpv6SrvTest() {
  297. isc::dhcp::CfgMgr::instance().deleteSubnets6();
  298. };
  299. /// @brief Runs DHCPv6 configuration from the JSON string.
  300. ///
  301. /// @param config String holding server configuration in JSON format.
  302. void
  303. configure(const std::string& config);
  304. /// @brief Checks that server response (ADVERTISE or REPLY) contains proper
  305. /// IA_NA option
  306. ///
  307. /// @param rsp server's response
  308. /// @param expected_iaid expected IAID value
  309. /// @param expected_t1 expected T1 value
  310. /// @param expected_t2 expected T2 value
  311. /// @return IAADDR option for easy chaining with checkIAAddr method
  312. boost::shared_ptr<isc::dhcp::Option6IAAddr>
  313. checkIA_NA(const isc::dhcp::Pkt6Ptr& rsp, uint32_t expected_iaid,
  314. uint32_t expected_t1, uint32_t expected_t2);
  315. /// @brief Checks that server response (ADVERTISE or REPLY) contains proper
  316. /// IA_PD option
  317. ///
  318. /// @param rsp server's response
  319. /// @param expected_iaid expected IAID value
  320. /// @param expected_t1 expected T1 value
  321. /// @param expected_t2 expected T2 value
  322. /// @return IAPREFIX option for easy chaining with checkIAAddr method
  323. boost::shared_ptr<isc::dhcp::Option6IAPrefix>
  324. checkIA_PD(const isc::dhcp::Pkt6Ptr& rsp, uint32_t expected_iaid,
  325. uint32_t expected_t1, uint32_t expected_t2);
  326. // Check that generated IAADDR option contains expected address
  327. // and lifetime values match the configured subnet
  328. void checkIAAddr(const boost::shared_ptr<isc::dhcp::Option6IAAddr>& addr,
  329. const isc::asiolink::IOAddress& expected_addr,
  330. isc::dhcp::Lease::Type type) {
  331. // Check that the assigned address is indeed from the configured pool.
  332. // Note that when comparing addresses, we compare the textual
  333. // representation. IOAddress does not support being streamed to
  334. // an ostream, which means it can't be used in EXPECT_EQ.
  335. EXPECT_TRUE(subnet_->inPool(type, addr->getAddress()));
  336. EXPECT_EQ(expected_addr.toText(), addr->getAddress().toText());
  337. EXPECT_EQ(addr->getPreferred(), subnet_->getPreferred());
  338. EXPECT_EQ(addr->getValid(), subnet_->getValid());
  339. }
  340. // Checks if the lease sent to client is present in the database
  341. // and is valid when checked agasint the configured subnet
  342. isc::dhcp::Lease6Ptr checkLease
  343. (const isc::dhcp::DuidPtr& duid, const isc::dhcp::OptionPtr& ia_na,
  344. boost::shared_ptr<isc::dhcp::Option6IAAddr> addr);
  345. /// @brief Verifies received IAPrefix option
  346. ///
  347. /// Verifies if the received IAPrefix option matches the lease in the
  348. /// database.
  349. ///
  350. /// @param duid client's DUID
  351. /// @param ia_pd IA_PD option that contains the IAPRefix option
  352. /// @param prefix pointer to the IAPREFIX option
  353. /// @return corresponding IPv6 lease (if found)
  354. isc::dhcp::Lease6Ptr checkPdLease
  355. (const isc::dhcp::DuidPtr& duid, const isc::dhcp::OptionPtr& ia_pd,
  356. boost::shared_ptr<isc::dhcp::Option6IAPrefix> prefix);
  357. /// @brief Creates a message with specified IA
  358. ///
  359. /// A utility function that creates a message of the specified type with
  360. /// a specified container (IA_NA or IA_PD) and an address or prefix
  361. /// inside it.
  362. ///
  363. /// @param message_type type of the message (e.g. DHCPV6_SOLICIT)
  364. /// @param lease_type type of a lease (TYPE_NA or TYPE_PD)
  365. /// @param addr address or prefix to use in IADDRESS or IAPREFIX options
  366. /// @param prefix_len length of the prefix (used for prefixes only)
  367. /// @param iaid IA identifier (used in IA_XX option)
  368. /// @return created message
  369. isc::dhcp::Pkt6Ptr
  370. createMessage(uint8_t message_type, isc::dhcp::Lease::Type lease_type,
  371. const isc::asiolink::IOAddress& addr,
  372. const uint8_t prefix_len, uint32_t iaid);
  373. /// @brief Performs basic (positive) RENEW test
  374. ///
  375. /// See renewBasic and pdRenewBasic tests for detailed explanation.
  376. /// In essence the test attempts to perform a successful RENEW scenario.
  377. ///
  378. /// This method does not throw, but uses gtest macros to signify failures.
  379. ///
  380. /// @param type type (TYPE_NA or TYPE_PD)
  381. /// @param existing_addr address to be preinserted into the database
  382. /// @param renew_addr address being sent in RENEW
  383. /// @param prefix_len length of the prefix (128 for addresses)
  384. void
  385. testRenewBasic(isc::dhcp::Lease::Type type,
  386. const std::string& existing_addr,
  387. const std::string& renew_addr, const uint8_t prefix_len);
  388. /// @brief Performs negative RENEW test
  389. ///
  390. /// See renewReject and pdRenewReject tests for detailed explanation.
  391. /// In essence the test attempts to perform couple failed RENEW scenarios.
  392. ///
  393. /// This method does not throw, but uses gtest macros to signify failures.
  394. ///
  395. /// @param type type (TYPE_NA or TYPE_PD)
  396. /// @param addr address being sent in RENEW
  397. void
  398. testRenewReject(isc::dhcp::Lease::Type type,
  399. const isc::asiolink::IOAddress& addr);
  400. /// @brief Performs basic (positive) RELEASE test
  401. ///
  402. /// See releaseBasic and pdReleaseBasic tests for detailed explanation.
  403. /// In essence the test attempts to perform a successful RELEASE scenario.
  404. ///
  405. /// This method does not throw, but uses gtest macros to signify failures.
  406. ///
  407. /// @param type type (TYPE_NA or TYPE_PD)
  408. /// @param existing address to be preinserted into the database
  409. /// @param release_addr address being sent in RELEASE
  410. void
  411. testReleaseBasic(isc::dhcp::Lease::Type type,
  412. const isc::asiolink::IOAddress& existing,
  413. const isc::asiolink::IOAddress& release_addr);
  414. /// @brief Performs negative RELEASE test
  415. ///
  416. /// See releaseReject and pdReleaseReject tests for detailed
  417. /// explanation. In essence the test attempts to perform couple
  418. /// failed RELEASE scenarios.
  419. ///
  420. /// This method does not throw, but uses gtest macros to signify failures.
  421. ///
  422. /// @param type type (TYPE_NA or TYPE_PD)
  423. /// @param addr address being sent in RELEASE
  424. void
  425. testReleaseReject(isc::dhcp::Lease::Type type,
  426. const isc::asiolink::IOAddress& addr);
  427. // see wireshark.cc for descriptions
  428. // The descriptions are too large and too closely related to the
  429. // code, so it is kept in .cc rather than traditionally in .h
  430. isc::dhcp::Pkt6Ptr captureSimpleSolicit();
  431. isc::dhcp::Pkt6Ptr captureRelayedSolicit();
  432. isc::dhcp::Pkt6Ptr captureDocsisRelayedSolicit();
  433. isc::dhcp::Pkt6Ptr captureeRouterRelayedSolicit();
  434. isc::dhcp::Pkt6Ptr captureCableLabsShortVendorClass();
  435. /// @brief Auxiliary method that sets Pkt6 fields
  436. ///
  437. /// Used to reconstruct captured packets. Sets UDP ports, interface names,
  438. /// and other fields to some believable values.
  439. /// @param pkt packet that will have its fields set
  440. void captureSetDefaultFields(const isc::dhcp::Pkt6Ptr& pkt);
  441. /// A subnet used in most tests
  442. isc::dhcp::Subnet6Ptr subnet_;
  443. /// A normal, non-temporary pool used in most tests
  444. isc::dhcp::Pool6Ptr pool_;
  445. /// A prefix pool used in most tests
  446. isc::dhcp::Pool6Ptr pd_pool_;
  447. /// @brief Server object under test.
  448. NakedDhcpv6Srv srv_;
  449. };
  450. }; // end of isc::test namespace
  451. }; // end of isc namespace
  452. #endif // DHCP6_TEST_UTILS_H