NFD 24.07-35-g23c53535
Loading...
Searching...
No Matches
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-2026, 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/security/certificate-fetcher-offline.hpp>
30#include <ndn-cxx/security/certificate-request.hpp>
31#include <ndn-cxx/security/validation-policy.hpp>
32#include <ndn-cxx/security/validation-policy-accept-all.hpp>
33#include <ndn-cxx/security/validation-policy-command-interest.hpp>
34#include <ndn-cxx/tag.hpp>
35#include <ndn-cxx/util/io.hpp>
36
37#include <filesystem>
38#include <fstream>
39
40namespace security = ndn::security;
41
42namespace nfd {
43
44NFD_LOG_INIT(CommandAuthenticator);
45// INFO: configuration change, etc
46// DEBUG: per authentication request result
47
51using SignerTag = ndn::SimpleTag<Name, 20>;
52
56static std::optional<std::string>
57getSignerFromTag(const Interest& interest)
58{
59 auto signerTag = interest.getTag<SignerTag>();
60 if (signerTag == nullptr) {
61 return std::nullopt;
62 }
63 else {
64 return signerTag->get().toUri();
65 }
66}
67
71class CommandAuthenticatorValidationPolicy final : public security::ValidationPolicy
72{
73public:
74 void
75 checkPolicy(const Interest& interest, const shared_ptr<security::ValidationState>& state,
76 const ValidationContinuation& continueValidation) final
77 {
78 auto sigInfo = getSignatureInfo(interest, *state);
79 if (!state->getOutcome()) { // already failed
80 return;
81 }
82 Name klName = getKeyLocatorName(sigInfo, *state);
83 if (!state->getOutcome()) { // already failed
84 return;
85 }
86
87 // SignerTag must be placed on the 'original Interest' in ValidationState to be available for
88 // InterestValidationSuccessCallback. The 'interest' parameter refers to a different instance
89 // which is copied into 'original Interest'.
90 auto state1 = std::dynamic_pointer_cast<security::InterestValidationState>(state);
91 state1->getOriginalInterest().setTag(make_shared<SignerTag>(klName));
92
93 continueValidation(make_shared<security::CertificateRequest>(klName), state);
94 }
95
96 void
97 checkPolicy(const Data&, const shared_ptr<security::ValidationState>&,
98 const ValidationContinuation&) final
99 {
100 // Non-certificate Data are not handled by CommandAuthenticator.
101 // Non-anchor certificates cannot be retrieved by offline fetcher.
102 BOOST_ASSERT_MSG(false, "Data should not be passed to this policy");
103 }
104};
105
106shared_ptr<CommandAuthenticator>
108{
109 return shared_ptr<CommandAuthenticator>(new CommandAuthenticator);
110}
111
112CommandAuthenticator::CommandAuthenticator() = default;
113
114void
116{
117 configFile.addSectionHandler("authorizations", [this] (auto&&... args) {
118 processConfig(std::forward<decltype(args)>(args)...);
119 });
120}
121
122void
123CommandAuthenticator::processConfig(const ConfigSection& section, bool isDryRun, const std::string& filename)
124{
125 if (!isDryRun) {
126 NFD_LOG_DEBUG("resetting authorizations");
127 for (auto& kv : m_validators) {
128 kv.second = make_shared<security::Validator>(
129 make_unique<security::ValidationPolicyCommandInterest>(make_unique<CommandAuthenticatorValidationPolicy>()),
130 make_unique<security::CertificateFetcherOffline>());
131 }
132 }
133
134 if (section.empty()) {
135 NDN_THROW(ConfigFile::Error("'authorize' is missing under 'authorizations'"));
136 }
137
138 int authSectionIndex = 0;
139 for (const auto& [sectionName, authSection] : section) {
140 if (sectionName != "authorize") {
141 NDN_THROW(ConfigFile::Error("'" + sectionName + "' section is not permitted under 'authorizations'"));
142 }
143
144 std::string certfile;
145 try {
146 certfile = authSection.get<std::string>("certfile");
147 }
148 catch (const boost::property_tree::ptree_error&) {
149 NDN_THROW(ConfigFile::Error("'certfile' is missing under authorize[" +
150 std::to_string(authSectionIndex) + "]"));
151 }
152
153 bool isAny = false;
154 security::Certificate cert;
155 if (certfile == "any") {
156 isAny = true;
157 NFD_LOG_WARN("'certfile any' is intended for demo purposes only and "
158 "SHOULD NOT be used in production environments");
159 }
160 else {
161 auto certfilePath = std::filesystem::absolute(filename).parent_path() / certfile;
162 certfilePath = certfilePath.lexically_normal();
163 try {
164 std::ifstream ifs(certfilePath);
165 cert = ndn::io::loadTlv<security::Certificate>(ifs);
166 }
167 catch (const std::runtime_error&) {
168 NDN_THROW_NESTED(ConfigFile::Error("cannot load certfile '" + certfilePath.native() +
169 "' for authorize[" + std::to_string(authSectionIndex) + "]"));
170 }
171 }
172
173 const ConfigSection* privSection = nullptr;
174 try {
175 privSection = &authSection.get_child("privileges");
176 }
177 catch (const boost::property_tree::ptree_error&) {
178 NDN_THROW(ConfigFile::Error("'privileges' is missing under authorize[" +
179 std::to_string(authSectionIndex) + "]"));
180 }
181
182 if (privSection->empty()) {
183 NFD_LOG_WARN("No privileges granted to certificate " << certfile);
184 }
185 for (const auto& kv : *privSection) {
186 const std::string& module = kv.first;
187 auto found = m_validators.find(module);
188 if (found == m_validators.end()) {
189 NDN_THROW(ConfigFile::Error("unknown module '" + module +
190 "' under authorize[" + std::to_string(authSectionIndex) + "]"));
191 }
192
193 if (isDryRun) {
194 continue;
195 }
196
197 if (isAny) {
198 found->second = make_shared<security::Validator>(make_unique<security::ValidationPolicyAcceptAll>(),
199 make_unique<security::CertificateFetcherOffline>());
200 NFD_LOG_INFO("authorize module=" << module << " signer=any");
201 }
202 else {
203 found->second->loadAnchor(certfile, security::Certificate(cert));
204 NFD_LOG_INFO("authorize module=" << module << " signer=" << cert.getKeyName()
205 << " certfile=" << certfile);
206 }
207 }
208
209 ++authSectionIndex;
210 }
211}
212
213ndn::mgmt::Authorization
214CommandAuthenticator::makeAuthorization(const std::string& module, const std::string& verb)
215{
216 m_validators[module]; // declares module, so that privilege is recognized
217
218 return [module, self = shared_from_this()] (const Name&, const Interest& interest,
219 const ndn::mgmt::ControlParametersBase*,
220 const ndn::mgmt::AcceptContinuation& accept,
221 const ndn::mgmt::RejectContinuation& reject) {
222 auto validator = self->m_validators.at(module);
223
224 auto successCb = [accept, validator] (const Interest& interest1) {
225 auto signer1 = getSignerFromTag(interest1);
226 BOOST_ASSERT(signer1 || // signer must be available unless 'certfile any'
227 dynamic_cast<security::ValidationPolicyAcceptAll*>(&validator->getPolicy()) != nullptr);
228 std::string signer = signer1.value_or("*");
229 NFD_LOG_DEBUG("accept " << interest1.getName() << " signer=" << signer);
230 accept(signer);
231 };
232
233 using ndn::security::ValidationError;
234 auto failureCb = [reject] (const Interest& interest1, const ValidationError& err) {
235 auto reply = ndn::mgmt::RejectReply::STATUS403;
236 if (err.getCode() == ValidationError::MALFORMED_SIGNATURE ||
237 err.getCode() == ValidationError::INVALID_KEY_LOCATOR) {
238 // do not waste cycles signing and sending a reply if the command is clearly malformed
239 reply = ndn::mgmt::RejectReply::SILENT;
240 }
241 NFD_LOG_DEBUG("reject " << interest1.getName() << " signer=" <<
242 getSignerFromTag(interest1).value_or("?") << " reason=" << err);
243 reject(reply);
244 };
245
246 if (validator) {
247 validator->validate(interest, successCb, failureCb);
248 }
249 else {
250 NFD_LOG_DEBUG("reject " << interest.getName() << " signer=" <<
251 getSignerFromTag(interest).value_or("?") << " reason=Unauthorized");
252 reject(ndn::mgmt::RejectReply::STATUS403);
253 }
254 };
255}
256
257} // namespace nfd
Provides ControlCommand authorization according to NFD's configuration file.
ndn::mgmt::Authorization makeAuthorization(const std::string &module, const std::string &verb)
Returns an Authorization function for module/verb command.
void setConfigFile(ConfigFile &configFile)
static shared_ptr< CommandAuthenticator > create()
Configuration file parsing utility.
void addSectionHandler(const std::string &sectionName, ConfigSectionHandler subscriber)
Setup notification of configuration file sections.
#define NFD_LOG_INFO
Definition logger.hpp:39
#define NFD_LOG_INIT(name)
Definition logger.hpp:31
#define NFD_LOG_WARN
Definition logger.hpp:40
#define NFD_LOG_DEBUG
Definition logger.hpp:38
Definition common.hpp:71
ndn::SimpleTag< Name, 20 > SignerTag
An Interest tag to store the command signer.
boost::property_tree::ptree ConfigSection
A configuration file section.
static std::optional< std::string > getSignerFromTag(const Interest &interest)
Obtain signer from a SignerTag attached to interest, if available.