validation-policy-config.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2023 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  */
21 
24 #include "ndn-cxx/util/io.hpp"
25 
26 #include <boost/algorithm/string/predicate.hpp>
27 #include <boost/filesystem/operations.hpp>
28 #include <boost/filesystem/path.hpp>
29 #include <boost/lexical_cast.hpp>
30 #include <boost/property_tree/info_parser.hpp>
31 
32 #include <fstream>
33 
35 
36 void
37 ValidationPolicyConfig::load(const std::string& filename)
38 {
39  std::ifstream inputFile(filename);
40  if (!inputFile) {
41  NDN_THROW(Error("Failed to read configuration file: " + filename));
42  }
43  load(inputFile, filename);
44 }
45 
46 void
47 ValidationPolicyConfig::load(const std::string& input, const std::string& filename)
48 {
49  std::istringstream inputStream(input);
50  load(inputStream, filename);
51 }
52 
53 void
54 ValidationPolicyConfig::load(std::istream& input, const std::string& filename)
55 {
56  ConfigSection tree;
57  try {
58  boost::property_tree::read_info(input, tree);
59  }
60  catch (const boost::property_tree::info_parser_error& e) {
61  NDN_THROW(Error("Failed to parse configuration file " + filename +
62  " line " + to_string(e.line()) + ": " + e.message()));
63  }
64  load(tree, filename);
65 }
66 
67 void
68 ValidationPolicyConfig::load(const ConfigSection& configSection, const std::string& filename)
69 {
70  BOOST_ASSERT(!filename.empty());
71 
72  if (m_validator == nullptr) {
73  NDN_THROW(Error("Validator instance not assigned on the policy"));
74  }
75  if (m_isConfigured) {
76  m_shouldBypass = false;
77  m_dataRules.clear();
78  m_interestRules.clear();
81  }
82  m_isConfigured = true;
83 
84  for (const auto& subSection : configSection) {
85  const std::string& sectionName = subSection.first;
86  const ConfigSection& section = subSection.second;
87 
88  if (boost::iequals(sectionName, "rule")) {
89  auto rule = Rule::create(section, filename);
90  if (rule->getPktType() == tlv::Data) {
91  m_dataRules.push_back(std::move(rule));
92  }
93  else if (rule->getPktType() == tlv::Interest) {
94  m_interestRules.push_back(std::move(rule));
95  }
96  }
97  else if (boost::iequals(sectionName, "trust-anchor")) {
98  processConfigTrustAnchor(section, filename);
99  }
100  else {
101  NDN_THROW(Error("Error processing configuration file " + filename +
102  ": unrecognized section " + sectionName));
103  }
104  }
105 }
106 
107 void
108 ValidationPolicyConfig::processConfigTrustAnchor(const ConfigSection& configSection,
109  const std::string& filename)
110 {
111  using namespace boost::filesystem;
112 
113  auto propertyIt = configSection.begin();
114 
115  // Get trust-anchor.type
116  if (propertyIt == configSection.end() || !boost::iequals(propertyIt->first, "type")) {
117  NDN_THROW(Error("Expecting <trust-anchor.type>"));
118  }
119 
120  std::string type = propertyIt->second.data();
121  propertyIt++;
122 
123  if (boost::iequals(type, "file")) {
124  // Get trust-anchor.file
125  if (propertyIt == configSection.end() || !boost::iequals(propertyIt->first, "file-name")) {
126  NDN_THROW(Error("Expecting <trust-anchor.file-name>"));
127  }
128 
129  std::string file = propertyIt->second.data();
130  propertyIt++;
131 
132  time::nanoseconds refresh = getRefreshPeriod(propertyIt, configSection.end());
133  if (propertyIt != configSection.end())
134  NDN_THROW(Error("Expecting end of <trust-anchor>"));
135 
136  m_validator->loadAnchor(file, absolute(file, path(filename).parent_path()).string(),
137  refresh, false);
138  }
139  else if (boost::iequals(type, "base64")) {
140  // Get trust-anchor.base64-string
141  if (propertyIt == configSection.end() || !boost::iequals(propertyIt->first, "base64-string"))
142  NDN_THROW(Error("Expecting <trust-anchor.base64-string>"));
143 
144  std::stringstream ss(propertyIt->second.data());
145  propertyIt++;
146 
147  if (propertyIt != configSection.end())
148  NDN_THROW(Error("Expecting end of <trust-anchor>"));
149 
150  auto idCert = io::load<Certificate>(ss);
151  if (idCert != nullptr) {
152  m_validator->loadAnchor("", std::move(*idCert));
153  }
154  else {
155  NDN_THROW(Error("Cannot decode certificate from base64-string"));
156  }
157  }
158  else if (boost::iequals(type, "dir")) {
159  if (propertyIt == configSection.end() || !boost::iequals(propertyIt->first, "dir"))
160  NDN_THROW(Error("Expecting <trust-anchor.dir>"));
161 
162  std::string dirString(propertyIt->second.data());
163  propertyIt++;
164 
165  time::nanoseconds refresh = getRefreshPeriod(propertyIt, configSection.end());
166  if (propertyIt != configSection.end())
167  NDN_THROW(Error("Expecting end of <trust-anchor>"));
168 
169  path dirPath = absolute(dirString, path(filename).parent_path());
170  m_validator->loadAnchor(dirString, dirPath.string(), refresh, true);
171  }
172  else if (boost::iequals(type, "any")) {
173  m_shouldBypass = true;
174  }
175  else {
176  NDN_THROW(Error("Unrecognized <trust-anchor.type>: " + type));
177  }
178 }
179 
181 ValidationPolicyConfig::getRefreshPeriod(ConfigSection::const_iterator& it,
182  const ConfigSection::const_iterator& end)
183 {
184  auto refresh = time::nanoseconds::max();
185  if (it == end) {
186  return refresh;
187  }
188 
189  if (!boost::iequals(it->first, "refresh")) {
190  NDN_THROW(Error("Expecting <trust-anchor.refresh>"));
191  }
192 
193  std::string inputString = it->second.data();
194  ++it;
195  char unit = inputString[inputString.size() - 1];
196  std::string refreshString = inputString.substr(0, inputString.size() - 1);
197 
198  int32_t refreshPeriod = -1;
199  try {
200  refreshPeriod = boost::lexical_cast<int32_t>(refreshString);
201  }
202  catch (const boost::bad_lexical_cast&) {
203  // pass
204  }
205  if (refreshPeriod < 0) {
206  NDN_THROW(Error("Bad refresh value: " + refreshString));
207  }
208 
209  if (refreshPeriod == 0) {
210  return getDefaultRefreshPeriod();
211  }
212 
213  switch (unit) {
214  case 'h':
215  return time::hours(refreshPeriod);
216  case 'm':
217  return time::minutes(refreshPeriod);
218  case 's':
219  return time::seconds(refreshPeriod);
220  default:
221  NDN_THROW(Error("Bad refresh time unit: "s + unit));
222  }
223 }
224 
226 ValidationPolicyConfig::getDefaultRefreshPeriod()
227 {
228  return 1_h;
229 }
230 
231 void
232 ValidationPolicyConfig::checkPolicy(const Data& data, const shared_ptr<ValidationState>& state,
233  const ValidationContinuation& continueValidation)
234 {
235  BOOST_ASSERT_MSG(!hasInnerPolicy(), "ValidationPolicyConfig must be a terminal inner policy");
236 
237  if (m_shouldBypass) {
238  return continueValidation(nullptr, state);
239  }
240 
241  Name klName = getKeyLocatorName(data.getSignatureInfo(), *state);
242  if (!state->getOutcome()) { // already failed
243  return;
244  }
245 
246  auto sigType = tlv::SignatureTypeValue(data.getSignatureType());
247 
248  for (const auto& rule : m_dataRules) {
249  if (rule->match(tlv::Data, data.getName(), state)) {
250  if (rule->check(tlv::Data, sigType, data.getName(), klName, state)) {
251  return continueValidation(make_shared<CertificateRequest>(klName), state);
252  }
253  // rule->check calls state->fail(...) if the check fails
254  return;
255  }
256  }
257 
258  return state->fail({ValidationError::POLICY_ERROR,
259  "No rule matched for data `" + data.getName().toUri() + "`"});
260 }
261 
262 void
263 ValidationPolicyConfig::checkPolicy(const Interest& interest, const shared_ptr<ValidationState>& state,
264  const ValidationContinuation& continueValidation)
265 {
266  BOOST_ASSERT_MSG(!hasInnerPolicy(), "ValidationPolicyConfig must be a terminal inner policy");
267 
268  if (m_shouldBypass) {
269  return continueValidation(nullptr, state);
270  }
271 
272  auto sigInfo = getSignatureInfo(interest, *state);
273  if (!state->getOutcome()) { // already failed
274  return;
275  }
276 
277  Name klName = getKeyLocatorName(sigInfo, *state);
278  if (!state->getOutcome()) { // already failed
279  return;
280  }
281 
282  auto sigType = tlv::SignatureTypeValue(sigInfo.getSignatureType());
283 
284  for (const auto& rule : m_interestRules) {
285  if (rule->match(tlv::Interest, interest.getName(), state)) {
286  if (rule->check(tlv::Interest, sigType, interest.getName(), klName, state)) {
287  return continueValidation(make_shared<CertificateRequest>(klName), state);
288  }
289  // rule->check calls state->fail(...) if the check fails
290  return;
291  }
292  }
293 
294  return state->fail({ValidationError::POLICY_ERROR,
295  "No rule matched for interest `" + interest.getName().toUri() + "`"});
296 }
297 
298 } // namespace ndn::security::validator_config
Represents a Data packet.
Definition: data.hpp:39
int32_t getSignatureType() const noexcept
Get the SignatureType.
Definition: data.hpp:358
const SignatureInfo & getSignatureInfo() const noexcept
Get the SignatureInfo element.
Definition: data.hpp:243
const Name & getName() const noexcept
Get the Data name.
Definition: data.hpp:137
Represents an Interest packet.
Definition: interest.hpp:50
const Name & getName() const noexcept
Get the Interest name.
Definition: interest.hpp:179
Represents an absolute name.
Definition: name.hpp:45
@ POLICY_ERROR
The packet violates the validation rules enforced by the policy.
std::function< void(const shared_ptr< CertificateRequest > &certRequest, const shared_ptr< ValidationState > &state)> ValidationContinuation
bool hasInnerPolicy() const
Check if inner policy is set.
void loadAnchor(const std::string &groupId, Certificate &&cert)
Load static trust anchor.
Definition: validator.cpp:169
void resetVerifiedCertificates()
Remove any cached verified certificates.
Definition: validator.cpp:194
void resetAnchors()
Remove any previously loaded static or dynamic trust anchor.
Definition: validator.cpp:182
static unique_ptr< Rule > create(const ConfigSection &configSection, const std::string &configFilename)
Create a rule from configuration section.
Definition: rule.cpp:104
void load(const std::string &filename)
Load policy from file filename.
void checkPolicy(const Data &data, const shared_ptr< ValidationState > &state, const ValidationContinuation &continueValidation) override
Check data against the policy.
#define NDN_THROW(e)
Definition: exception.hpp:56
std::string to_string(const errinfo_stacktrace &x)
Definition: exception.cpp:30
boost::property_tree::ptree ConfigSection
Definition: common.hpp:33
SignatureInfo getSignatureInfo(const Interest &interest, ValidationState &state)
Extract SignatureInfo from a signed Interest.
Name getKeyLocatorName(const SignatureInfo &si, ValidationState &state)
Extract the KeyLocator name from a SignatureInfo element.
::boost::chrono::seconds seconds
Definition: time.hpp:51
::boost::chrono::minutes minutes
Definition: time.hpp:50
::boost::chrono::nanoseconds nanoseconds
Definition: time.hpp:54
::boost::chrono::hours hours
Definition: time.hpp:49
@ Data
Definition: tlv.hpp:69
@ Interest
Definition: tlv.hpp:68
SignatureTypeValue
SignatureType values.
Definition: tlv.hpp:127