Kea 3.3.4
filesystem.cc
Go to the documentation of this file.
1// Copyright (C) 2021-2026 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
10#include <util/filesystem.h>
11#include <util/str.h>
12
13#include <cstdio>
14#include <cstdlib>
15#include <fstream>
16#include <string>
17#include <iostream>
18
19#include <dirent.h>
20#include <fcntl.h>
21#include <unistd.h>
22
23using namespace isc;
24using namespace isc::util::str;
25using namespace std;
26
27namespace isc {
28namespace util {
29namespace file {
30
31
32string
33getContent(string const& file_name) {
34 if (!exists(file_name)) {
35 isc_throw(BadValue, "Expected a file at path '" << file_name << "'");
36 }
37 if (!isFile(file_name)) {
38 isc_throw(BadValue, "Expected '" << file_name << "' to be a regular file");
39 }
40 ifstream file(file_name, ios::in);
41 if (!file.is_open()) {
42 isc_throw(BadValue, "Cannot open '" << file_name);
43 }
44 string content;
45 getline(file, content);
46 return (content);
47}
48
49bool
50exists(string const& path) {
51 struct stat statbuf;
52 return (::stat(path.c_str(), &statbuf) == 0);
53}
54
55mode_t
56getPermissions(const std::string path) {
57 struct stat statbuf;
58 if (::stat(path.c_str(), &statbuf) < 0) {
59 return (0);
60 }
61
62 return (statbuf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO));
63}
64
65bool
66hasPermissions(const std::string path, const mode_t& permissions) {
67 return (getPermissions(path) == permissions);
68}
69
70bool
71isDir(string const& path) {
72 struct stat statbuf;
73 if (::stat(path.c_str(), &statbuf) < 0) {
74 return (false);
75 }
76 return ((statbuf.st_mode & S_IFMT) == S_IFDIR);
77}
78
79bool
80isFile(string const& path) {
81 struct stat statbuf;
82 if (::stat(path.c_str(), &statbuf) < 0) {
83 return (false);
84 }
85 return ((statbuf.st_mode & S_IFMT) == S_IFREG);
86}
87
88bool
89isSocket(string const& path) {
90 struct stat statbuf;
91 if (::stat(path.c_str(), &statbuf) < 0) {
92 return (false);
93 }
94 return ((statbuf.st_mode & S_IFMT) == S_IFSOCK);
95}
96
97bool
98remove(string const& path) {
99 return (::remove(path.c_str()) == 0);
100}
101
102void
104 // No group write and no other access.
105 mode_t mask(S_IWGRP | S_IRWXO);
106 mode_t orig = umask(mask);
107 // Handle the case where the original umask was already more restrictive.
108 if ((orig | mask) != mask) {
109 static_cast<void>(umask(orig | mask));
110 }
111}
112
113RelaxUmask::RelaxUmask() : orig_umask_(umask(S_IRWXO)) {
114}
115
117 static_cast<void>(umask(orig_umask_));
118}
119
121 return (getuid() == 0 || geteuid() == 0);
122}
123
124Path::Path(string const& full_name) {
125 dir_present_ = false;
126 if (!full_name.empty()) {
127 // Find the directory.
128 size_t last_slash = full_name.find_last_of('/');
129 if (last_slash != string::npos) {
130 // Found a directory so note the fact.
131 dir_present_ = true;
132
133 // Found the last slash, so extract directory component and
134 // set where the scan for the last_dot should terminate.
135 parent_path_ = full_name.substr(0, last_slash);
136 if (last_slash == full_name.size()) {
137 // The entire string was a directory, so exit and don't
138 // do any more searching.
139 return;
140 }
141 }
142
143 // Now search backwards for the last ".".
144 size_t last_dot = full_name.find_last_of('.');
145 if ((last_dot == string::npos) || (dir_present_ && (last_dot < last_slash))) {
146 // Last "." either not found or it occurs to the left of the last
147 // slash if a directory was present (so it is part of a directory
148 // name). In this case, the remainder of the string after the slash
149 // is the name part.
150 stem_ = full_name.substr(last_slash + 1);
151 return;
152 }
153
154 // Did find a valid dot, so it and everything to the right is the
155 // extension...
156 extension_ = full_name.substr(last_dot);
157
158 // ... and the name of the file is everything in between.
159 if ((last_dot - last_slash) > 1) {
160 stem_ = full_name.substr(last_slash + 1, last_dot - last_slash - 1);
161 }
162 }
163}
164
165string
166Path::str() const {
167 return (parent_path_ + (dir_present_ ? "/" : "") + stem_ + extension_);
168}
169
170string
172 return (parent_path_);
173}
174
175string
177 return (parent_path_ + (dir_present_ ? "/" : ""));
178}
179
180string
181Path::stem() const {
182 return (stem_);
183}
184
185string
187 return (extension_);
188}
189
190string
192 return (stem_ + extension_);
193}
194
195Path&
196Path::replaceExtension(string const& replacement) {
197 string const trimmed_replacement(trim(replacement));
198 if (trimmed_replacement.empty()) {
199 extension_ = string();
200 } else {
201 size_t const last_dot(trimmed_replacement.find_last_of('.'));
202 if (last_dot == string::npos) {
203 extension_ = "." + trimmed_replacement;
204 } else {
205 extension_ = trimmed_replacement.substr(last_dot);
206 }
207 }
208 return (*this);
209}
210
211Path&
212Path::replaceParentPath(string const& replacement) {
213 string const trimmed_replacement(trim(replacement));
214 dir_present_ = (trimmed_replacement.find_last_of('/') != string::npos);
215 if (trimmed_replacement.empty() || (trimmed_replacement == "/")) {
216 parent_path_ = string();
217 } else if (trimmed_replacement.at(trimmed_replacement.size() - 1) == '/') {
218 parent_path_ = trimmed_replacement.substr(0, trimmed_replacement.size() - 1);
219 } else {
220 parent_path_ = trimmed_replacement;
221 }
222 return (*this);
223}
224
226 char dir[]("/tmp/kea-tmpdir-XXXXXX");
227 char const* dir_name = mkdtemp(dir);
228 if (!dir_name) {
229 isc_throw(Unexpected, "mkdtemp failed " << dir << ": " << strerror(errno));
230 }
231 dir_name_ = string(dir_name);
232}
233
235 DIR *dir(opendir(dir_name_.c_str()));
236 if (!dir) {
237 return;
238 }
239
240 std::unique_ptr<DIR, void(*)(DIR*)> defer(dir, [](DIR* d) { closedir(d); });
241
242 struct dirent *i;
243 string filepath;
244 while ((i = readdir(dir))) {
245 if (strcmp(i->d_name, ".") == 0 || strcmp(i->d_name, "..") == 0) {
246 continue;
247 }
248
249 filepath = dir_name_ + '/' + i->d_name;
250 remove(filepath.c_str());
251 }
252
253 rmdir(dir_name_.c_str());
254}
255
257 return dir_name_;
258}
259
260PathChecker::PathChecker(const std::string default_path,
261 const std::string env_name /* = "" */)
262 : default_path_(default_path), env_name_(env_name),
263 default_overridden_(false) {
264 getPath(true);
265}
266
267std::string
268PathChecker::getPath(bool reset /* = false */,
269 const std::string explicit_path /* = "" */) {
270 if (reset) {
271 if (!explicit_path.empty()) {
272 path_ = explicit_path;
273 } else if (!env_name_.empty()) {
274 char* env_path = std::getenv(env_name_.c_str());
275 if (env_path) {
276 path_ = env_path;
277 } else {
278 path_ = default_path_;
279 }
280 } else {
281 path_ = default_path_;
282 }
283
284 // Remove the trailing "/" if it is present so comparison to
285 // other Path::parentPath() works.
286 while (!path_.empty() && path_.back() == '/') {
287 path_.pop_back();
288 }
289
290 default_overridden_ = (path_ != default_path_);
291 }
292
293 return (path_);
294}
295
296std::string
297PathChecker::validatePath(const std::string input_path_str,
298 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
299 Path input_path(trim(input_path_str));
300 auto filename = input_path.filename();
301 if (filename.empty() || (filename == ".") || (filename == "..")) {
302 isc_throw(BadValue, "path: '" << input_path.str() << "' has no filename");
303 }
304
305 auto parent_path = input_path.parentPath();
306 auto parent_dir = input_path.parentDirectory();
307 if (!parent_dir.empty()) {
308 // We only allow absolute path equal to default. Catch an invalid path.
309 if ((parent_path != path_) || (parent_dir == "/")) {
310 std::ostringstream oss;
311 oss << "invalid path specified: '"
312 << (parent_path.empty() ? "/" : parent_path)
313 << "', supported path is '"
314 << path_ << "'";
315
316 if (enforce_path) {
317 isc_throw(SecurityError, oss.str());
318 } else {
319 isc_throw(SecurityWarn, oss.str());
320 }
321 }
322 }
323
324 std::string valid_path(path_ + "/" + filename);
325 return (valid_path);
326}
327
328std::string
329PathChecker::validateDirectory(const std::string input_path_str,
330 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
331 // We only allow absolute path equal to default. Catch an invalid path.
332 if (!input_path_str.empty()) {
333 std::string input_copy = input_path_str;
334 while (!input_copy.empty() && input_copy.back() == '/') {
335 input_copy.pop_back();
336 }
337
338 if (input_copy != path_) {
339 std::ostringstream oss;
340 oss << "invalid path specified: '"
341 << input_path_str << "', supported path is '"
342 << path_ << "'";
343
344 if (enforce_path) {
345 isc_throw(SecurityError, oss.str());
346 } else {
347 isc_throw(SecurityWarn, oss.str());
348 }
349 }
350 }
351
352 return (path_);
353}
354
355bool
356PathChecker::pathHasPermissions(mode_t permissions, bool enforce_perms
357 /* = PathChecker::shouldEnforceSecurity() */) const {
358 return((!enforce_perms) || hasPermissions(path_, permissions));
359}
360
361bool
363 return (default_overridden_);
364}
365
367 return (enforce_security_);
368}
369
371 enforce_security_ = enable;
372}
373
374bool PathChecker::enforce_security_ = true;
375
376} // namespace file
377} // namespace util
378} // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
A generic exception that is thrown when an unexpected error condition occurs.
std::string getPath(bool reset=false, const std::string explicit_path="")
Fetches the supported path.
static bool shouldEnforceSecurity()
Indicates security checks should be enforced.
PathChecker(const std::string default_path, const std::string env_name="")
Constructor.
bool isDefaultOverridden()
Indicates if the default path has been overridden.
static void enableEnforcement(bool enable)
Enables or disables security enforcement checks.
std::string validateDirectory(const std::string input_path_str, bool enforce_path=shouldEnforceSecurity()) const
Validates a directory against a supported path.
bool pathHasPermissions(mode_t permissions, bool enforce_perms=shouldEnforceSecurity()) const
Check if the path has expected permissions.
std::string validatePath(const std::string input_path_str, bool enforce_path=shouldEnforceSecurity()) const
Validates a file path against a supported path.
A generic exception that is thrown if a parameter given violates security and enforcement is true.
Definition filesystem.h:30
A generic exception that is thrown if a parameter given violates security check but enforcement is la...
Definition filesystem.h:22
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
bool amRunningAsRoot()
Indicates if current user is root.
bool remove(string const &path)
Remove file at the given path.
Definition filesystem.cc:98
bool isSocket(string const &path)
Check if there is a socket at the given path.
Definition filesystem.cc:89
string getContent(string const &file_name)
Get the content of a regular file.
Definition filesystem.cc:33
bool isFile(string const &path)
Check if there is a file at the given path.
Definition filesystem.cc:80
bool exists(string const &path)
Check if there is a file or directory at the given path.
Definition filesystem.cc:50
bool isDir(string const &path)
Check if there is a directory at the given path.
Definition filesystem.cc:71
mode_t getPermissions(const std::string path)
Fetches the file permissions mask.
Definition filesystem.cc:56
bool hasPermissions(const std::string path, const mode_t &permissions)
Check if there if file or directory has the given permissions.
Definition filesystem.cc:66
void setUmask()
Set umask (at least 0027 i.e. no group write and no other access).
string trim(const string &input)
Trim leading and trailing spaces.
Definition str.cc:32
Defines the logger used by the top-level component of kea-lfc.
Paths on a filesystem.
Definition filesystem.h:134
Path(std::string const &path)
Constructor.
Path & replaceParentPath(std::string const &replacement=std::string())
Trims {replacement} and replaces this instance's parent path with it.
std::string parentDirectory() const
Get the parent directory.
std::string extension() const
Get the extension of the file.
Path & replaceExtension(std::string const &replacement=std::string())
Identifies the extension in {replacement}, trims it, and replaces this instance's extension with it.
std::string stem() const
Get the base name of the file without the extension.
std::string parentPath() const
Get the parent path.
std::string filename() const
Get the name of the file, extension included.
std::string str() const
Get the path in textual format.