Kea 3.1.1
filesystem.cc
Go to the documentation of this file.
1// Copyright (C) 2021-2025 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 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
97void
99 // No group write and no other access.
100 mode_t mask(S_IWGRP | S_IRWXO);
101 mode_t orig = umask(mask);
102 // Handle the case where the original umask was already more restrictive.
103 if ((orig | mask) != mask) {
104 static_cast<void>(umask(orig | mask));
105 }
106}
107
109 return (getuid() == 0 || geteuid() == 0);
110}
111
112Path::Path(string const& full_name) {
113 dir_present_ = false;
114 if (!full_name.empty()) {
115 // Find the directory.
116 size_t last_slash = full_name.find_last_of('/');
117 if (last_slash != string::npos) {
118 // Found a directory so note the fact.
119 dir_present_ = true;
120
121 // Found the last slash, so extract directory component and
122 // set where the scan for the last_dot should terminate.
123 parent_path_ = full_name.substr(0, last_slash);
124 if (last_slash == full_name.size()) {
125 // The entire string was a directory, so exit and don't
126 // do any more searching.
127 return;
128 }
129 }
130
131 // Now search backwards for the last ".".
132 size_t last_dot = full_name.find_last_of('.');
133 if ((last_dot == string::npos) || (dir_present_ && (last_dot < last_slash))) {
134 // Last "." either not found or it occurs to the left of the last
135 // slash if a directory was present (so it is part of a directory
136 // name). In this case, the remainder of the string after the slash
137 // is the name part.
138 stem_ = full_name.substr(last_slash + 1);
139 return;
140 }
141
142 // Did find a valid dot, so it and everything to the right is the
143 // extension...
144 extension_ = full_name.substr(last_dot);
145
146 // ... and the name of the file is everything in between.
147 if ((last_dot - last_slash) > 1) {
148 stem_ = full_name.substr(last_slash + 1, last_dot - last_slash - 1);
149 }
150 }
151}
152
153string
154Path::str() const {
155 return (parent_path_ + (dir_present_ ? "/" : "") + stem_ + extension_);
156}
157
158string
160 return (parent_path_);
161}
162
163string
165 return (parent_path_ + (dir_present_ ? "/" : ""));
166}
167
168string
169Path::stem() const {
170 return (stem_);
171}
172
173string
175 return (extension_);
176}
177
178string
180 return (stem_ + extension_);
181}
182
183Path&
184Path::replaceExtension(string const& replacement) {
185 string const trimmed_replacement(trim(replacement));
186 if (trimmed_replacement.empty()) {
187 extension_ = string();
188 } else {
189 size_t const last_dot(trimmed_replacement.find_last_of('.'));
190 if (last_dot == string::npos) {
191 extension_ = "." + trimmed_replacement;
192 } else {
193 extension_ = trimmed_replacement.substr(last_dot);
194 }
195 }
196 return (*this);
197}
198
199Path&
200Path::replaceParentPath(string const& replacement) {
201 string const trimmed_replacement(trim(replacement));
202 dir_present_ = (trimmed_replacement.find_last_of('/') != string::npos);
203 if (trimmed_replacement.empty() || (trimmed_replacement == "/")) {
204 parent_path_ = string();
205 } else if (trimmed_replacement.at(trimmed_replacement.size() - 1) == '/') {
206 parent_path_ = trimmed_replacement.substr(0, trimmed_replacement.size() - 1);
207 } else {
208 parent_path_ = trimmed_replacement;
209 }
210 return (*this);
211}
212
214 char dir[]("/tmp/kea-tmpdir-XXXXXX");
215 char const* dir_name = mkdtemp(dir);
216 if (!dir_name) {
217 isc_throw(Unexpected, "mkdtemp failed " << dir << ": " << strerror(errno));
218 }
219 dir_name_ = string(dir_name);
220}
221
223 DIR *dir(opendir(dir_name_.c_str()));
224 if (!dir) {
225 return;
226 }
227
228 std::unique_ptr<DIR, void(*)(DIR*)> defer(dir, [](DIR* d) { closedir(d); });
229
230 struct dirent *i;
231 string filepath;
232 while ((i = readdir(dir))) {
233 if (strcmp(i->d_name, ".") == 0 || strcmp(i->d_name, "..") == 0) {
234 continue;
235 }
236
237 filepath = dir_name_ + '/' + i->d_name;
238 remove(filepath.c_str());
239 }
240
241 rmdir(dir_name_.c_str());
242}
243
245 return dir_name_;
246}
247
248PathChecker::PathChecker(const std::string default_path,
249 const std::string env_name /* = "" */)
250 : default_path_(default_path), env_name_(env_name),
251 default_overridden_(false) {
252 getPath(true);
253}
254
255std::string
256PathChecker::getPath(bool reset /* = false */,
257 const std::string explicit_path /* = "" */) {
258 if (reset) {
259 if (!explicit_path.empty()) {
260 path_ = explicit_path;
261 } else if (!env_name_.empty()) {
262 path_ = std::string(std::getenv(env_name_.c_str()) ?
263 std::getenv(env_name_.c_str()) : default_path_);
264 } else {
265 path_ = default_path_;
266 }
267
268 // Remove the trailing "/" if it is present so comparison to
269 // other Path::parentPath() works.
270 while (!path_.empty() && path_.back() == '/') {
271 path_.pop_back();
272 }
273
274 default_overridden_ = (path_ != default_path_);
275 }
276
277 return (path_);
278}
279
280std::string
281PathChecker::validatePath(const std::string input_path_str,
282 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
283 Path input_path(trim(input_path_str));
284 auto filename = input_path.filename();
285 if (filename.empty()) {
286 isc_throw(BadValue, "path: '" << input_path.str() << "' has no filename");
287 }
288
289 auto parent_path = input_path.parentPath();
290 auto parent_dir = input_path.parentDirectory();
291 if (!parent_dir.empty()) {
292 // We only allow absolute path equal to default. Catch an invalid path.
293 if ((parent_path != path_) || (parent_dir == "/")) {
294 std::ostringstream oss;
295 oss << "invalid path specified: '"
296 << (parent_path.empty() ? "/" : parent_path)
297 << "', supported path is '"
298 << path_ << "'";
299
300 if (enforce_path) {
301 isc_throw(SecurityError, oss.str());
302 } else {
303 isc_throw(SecurityWarn, oss.str());
304 }
305 }
306 }
307
308 std::string valid_path(path_ + "/" + filename);
309 return (valid_path);
310}
311
312std::string
313PathChecker::validateDirectory(const std::string input_path_str,
314 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
315 std::string input_copy = trim(input_path_str);
316 // We only allow absolute path equal to default. Catch an invalid path.
317 if (!input_path_str.empty()) {
318 std::string input_copy = input_path_str;
319 while (!input_copy.empty() && input_copy.back() == '/') {
320 input_copy.pop_back();
321 }
322
323 if (input_copy != path_) {
324 std::ostringstream oss;
325 oss << "invalid path specified: '"
326 << input_path_str << "', supported path is '"
327 << path_ << "'";
328
329 if (enforce_path) {
330 isc_throw(SecurityError, oss.str());
331 } else {
332 isc_throw(SecurityWarn, oss.str());
333 }
334 }
335 }
336
337 return (path_);
338}
339
340bool
341PathChecker::pathHasPermissions(mode_t permissions, bool enforce_perms
342 /* = PathChecker::shouldEnforceSecurity() */) const {
343 return((!enforce_perms) || hasPermissions(path_, permissions));
344}
345
346bool
348 return (default_overridden_);
349}
350
352 return (enforce_security_);
353}
354
356 enforce_security_ = enable;
357}
358
359bool PathChecker::enforce_security_ = true;
360
361} // namespace file
362} // namespace util
363} // 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 enforcment 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:29
A generic exception that is thrown if a parameter given violates security check but enforcement is la...
Definition filesystem.h:21
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
bool amRunningAsRoot()
Indicates if current user is root.
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).
Definition filesystem.cc:98
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:107
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.