NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
command-authenticator.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2021, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
27 #include "common/logger.hpp"
28 
29 #include <ndn-cxx/tag.hpp>
36 #include <ndn-cxx/util/io.hpp>
37 
38 #include <boost/filesystem.hpp>
39 
40 namespace security = ndn::security;
41 
42 namespace nfd {
43 
45 // INFO: configuration change, etc
46 // DEBUG: per authentication request result
47 
51 
54 static optional<std::string>
55 getSignerFromTag(const Interest& interest)
56 {
57  shared_ptr<SignerTag> signerTag = interest.getTag<SignerTag>();
58  if (signerTag == nullptr) {
59  return nullopt;
60  }
61  else {
62  return signerTag->get().toUri();
63  }
64 }
65 
68 class CommandAuthenticatorValidationPolicy final : public security::ValidationPolicy
69 {
70 public:
71  void
72  checkPolicy(const Interest& interest, const shared_ptr<security::ValidationState>& state,
73  const ValidationContinuation& continueValidation) final
74  {
75  Name klName = getKeyLocatorName(interest, *state);
76  if (!state->getOutcome()) { // already failed
77  return;
78  }
79 
80  // SignerTag must be placed on the 'original Interest' in ValidationState to be available for
81  // InterestValidationSuccessCallback. The 'interest' parameter refers to a different instance
82  // which is copied into 'original Interest'.
83  auto state1 = dynamic_pointer_cast<security::InterestValidationState>(state);
84  state1->getOriginalInterest().setTag(make_shared<SignerTag>(klName));
85 
86  continueValidation(make_shared<security::CertificateRequest>(klName), state);
87  }
88 
89  void
90  checkPolicy(const Data&, const shared_ptr<security::ValidationState>&,
91  const ValidationContinuation&) final
92  {
93  // Non-certificate Data are not handled by CommandAuthenticator.
94  // Non-anchor certificates cannot be retrieved by offline fetcher.
95  BOOST_ASSERT_MSG(false, "Data should not be passed to this policy");
96  }
97 };
98 
99 shared_ptr<CommandAuthenticator>
101 {
102  return shared_ptr<CommandAuthenticator>(new CommandAuthenticator);
103 }
104 
105 CommandAuthenticator::CommandAuthenticator() = default;
106 
107 void
109 {
110  configFile.addSectionHandler("authorizations", [this] (auto&&... args) {
111  processConfig(std::forward<decltype(args)>(args)...);
112  });
113 }
114 
115 void
116 CommandAuthenticator::processConfig(const ConfigSection& section, bool isDryRun, const std::string& filename)
117 {
118  if (!isDryRun) {
119  NFD_LOG_DEBUG("resetting authorizations");
120  for (auto& kv : m_validators) {
121  kv.second = make_shared<security::Validator>(
122  make_unique<security::ValidationPolicyCommandInterest>(make_unique<CommandAuthenticatorValidationPolicy>()),
123  make_unique<security::CertificateFetcherOffline>());
124  }
125  }
126 
127  if (section.empty()) {
128  NDN_THROW(ConfigFile::Error("'authorize' is missing under 'authorizations'"));
129  }
130 
131  int authSectionIndex = 0;
132  for (const auto& kv : section) {
133  if (kv.first != "authorize") {
134  NDN_THROW(ConfigFile::Error("'" + kv.first + "' section is not permitted under 'authorizations'"));
135  }
136  const ConfigSection& authSection = kv.second;
137 
138  std::string certfile;
139  try {
140  certfile = authSection.get<std::string>("certfile");
141  }
142  catch (const boost::property_tree::ptree_error&) {
143  NDN_THROW(ConfigFile::Error("'certfile' is missing under authorize[" +
144  to_string(authSectionIndex) + "]"));
145  }
146 
147  bool isAny = false;
148  shared_ptr<security::Certificate> cert;
149  if (certfile == "any") {
150  isAny = true;
151  NFD_LOG_WARN("'certfile any' is intended for demo purposes only and "
152  "SHOULD NOT be used in production environments");
153  }
154  else {
155  using namespace boost::filesystem;
156  path certfilePath = absolute(certfile, path(filename).parent_path());
157  cert = ndn::io::load<security::Certificate>(certfilePath.string());
158  if (cert == nullptr) {
159  NDN_THROW(ConfigFile::Error("cannot load certfile " + certfilePath.string() +
160  " for authorize[" + to_string(authSectionIndex) + "]"));
161  }
162  }
163 
164  const ConfigSection* privSection = nullptr;
165  try {
166  privSection = &authSection.get_child("privileges");
167  }
168  catch (const boost::property_tree::ptree_error&) {
169  NDN_THROW(ConfigFile::Error("'privileges' is missing under authorize[" +
170  to_string(authSectionIndex) + "]"));
171  }
172 
173  if (privSection->empty()) {
174  NFD_LOG_WARN("No privileges granted to certificate " << certfile);
175  }
176  for (const auto& kv : *privSection) {
177  const std::string& module = kv.first;
178  auto found = m_validators.find(module);
179  if (found == m_validators.end()) {
180  NDN_THROW(ConfigFile::Error("unknown module '" + module +
181  "' under authorize[" + to_string(authSectionIndex) + "]"));
182  }
183 
184  if (isDryRun) {
185  continue;
186  }
187 
188  if (isAny) {
189  found->second = make_shared<security::Validator>(make_unique<security::ValidationPolicyAcceptAll>(),
190  make_unique<security::CertificateFetcherOffline>());
191  NFD_LOG_INFO("authorize module=" << module << " signer=any");
192  }
193  else {
194  const Name& keyName = cert->getKeyName();
195  security::Certificate certCopy = *cert;
196  found->second->loadAnchor(certfile, std::move(certCopy));
197  NFD_LOG_INFO("authorize module=" << module << " signer=" << keyName << " certfile=" << certfile);
198  }
199  }
200 
201  ++authSectionIndex;
202  }
203 }
204 
206 CommandAuthenticator::makeAuthorization(const std::string& module, const std::string& verb)
207 {
208  m_validators[module]; // declares module, so that privilege is recognized
209 
210  auto self = this->shared_from_this();
211  return [=] (const Name&, const Interest& interest,
214  const ndn::mgmt::RejectContinuation& reject) {
215  auto validator = self->m_validators.at(module);
216 
217  auto successCb = [accept, validator] (const Interest& interest1) {
218  auto signer1 = getSignerFromTag(interest1);
219  BOOST_ASSERT(signer1 || // signer must be available unless 'certfile any'
220  dynamic_cast<security::ValidationPolicyAcceptAll*>(&validator->getPolicy()) != nullptr);
221  std::string signer = signer1.value_or("*");
222  NFD_LOG_DEBUG("accept " << interest1.getName() << " signer=" << signer);
223  accept(signer);
224  };
225 
226  auto failureCb = [reject] (const Interest& interest1, const security::ValidationError& err) {
228  RejectReply reply = RejectReply::STATUS403;
229  switch (err.getCode()) {
230  case security::ValidationError::NO_SIGNATURE:
231  case security::ValidationError::INVALID_KEY_LOCATOR:
232  reply = RejectReply::SILENT;
233  break;
234  case security::ValidationError::POLICY_ERROR:
235  if (interest1.getName().size() < ndn::command_interest::MIN_SIZE) { // "name too short"
236  reply = RejectReply::SILENT;
237  }
238  break;
239  }
240  NFD_LOG_DEBUG("reject " << interest1.getName() << " signer=" <<
241  getSignerFromTag(interest1).value_or("?") << " reason=" << err);
242  reject(reply);
243  };
244 
245  if (validator) {
246  validator->validate(interest, successCb, failureCb);
247  }
248  else {
249  NFD_LOG_DEBUG("reject " << interest.getName() << " signer=" <<
250  getSignerFromTag(interest).value_or("?") << " reason=Unauthorized");
252  }
253  };
254 }
255 
256 } // namespace nfd
shared_ptr< T > getTag() const
get a tag item
Definition: tag-host.hpp:66
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::string to_string(const T &val)
Definition: backports.hpp:86
Accept any value the remote endpoint offers.
Definition: enabled.hpp:207
RejectReply
indicate how to reply in case authorization is rejected
Definition: dispatcher.hpp:49
reply with a ControlResponse where StatusCode is 403
configuration file parsing utility
Definition: config-file.hpp:57
a validation policy that only permits Interest signed by a trust anchor
Represents an Interest packet.
Definition: interest.hpp:48
std::function< void(const std::string &requester)> AcceptContinuation
a function to be called if authorization is successful
Definition: dispatcher.hpp:45
void setConfigFile(ConfigFile &configFile)
#define NDN_THROW(e)
Definition: exception.hpp:61
Catch-all error for security policy errors that don&#39;t fit in other categories.
Definition: base.hpp:79
provides a tag type for simple types
Definition: tag.hpp:58
#define NFD_LOG_INFO
Definition: logger.hpp:39
static Name getKeyLocatorName(const SignatureInfo &si, ValidationState &state)
std::function< void(RejectReply reply)> RejectContinuation
a function to be called if authorization is rejected
Definition: dispatcher.hpp:60
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
void addSectionHandler(const std::string &sectionName, ConfigSectionHandler subscriber)
setup notification of configuration file sections
Definition: config-file.cpp:77
ndn::mgmt::Authorization makeAuthorization(const std::string &module, const std::string &verb)
static optional< std::string > getSignerFromTag(const Interest &interest)
obtain signer from SignerTag attached to Interest, if available
#define NFD_LOG_DEBUG
Definition: logger.hpp:38
const size_t MIN_SIZE
minimal number of components for Command Interest
boost::property_tree::ptree ConfigSection
a config file section
Represents an absolute name.
Definition: name.hpp:41
void checkPolicy(const Interest &interest, const shared_ptr< security::ValidationState > &state, const ValidationContinuation &continueValidation) final
base class for a struct that contains ControlCommand parameters
size_t size() const
Returns the number of components.
Definition: name.hpp:151
Provides ControlCommand authorization according to NFD configuration file.
#define NFD_LOG_WARN
Definition: logger.hpp:40
static shared_ptr< CommandAuthenticator > create()
const Name & getName() const noexcept
Definition: interest.hpp:172
void checkPolicy(const Data &, const shared_ptr< security::ValidationState > &, const ValidationContinuation &) final
Represents a Data packet.
Definition: data.hpp:37
std::function< void(const Name &prefix, const Interest &interest, const ControlParameters *params, const AcceptContinuation &accept, const RejectContinuation &reject)> Authorization
a function that performs authorization
Definition: dispatcher.hpp:77
const nullopt_t nullopt((nullopt_t::init()))