1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <sched.h>
4 #include <sys/prctl.h>
5 #include <sys/stat.h>
6 #include <unistd.h>
7 
8 #include "alloc-util.h"
9 #include "btrfs-util.h"
10 #include "capability-util.h"
11 #include "chattr-util.h"
12 #include "dirent-util.h"
13 #include "fd-util.h"
14 #include "fileio.h"
15 #include "fs-util.h"
16 #include "hostname-util.h"
17 #include "import-common.h"
18 #include "os-util.h"
19 #include "process-util.h"
20 #include "selinux-util.h"
21 #include "signal-util.h"
22 #include "stat-util.h"
23 #include "tmpfile-util.h"
24 #include "util.h"
25 
import_fork_tar_x(const char * path,pid_t * ret)26 int import_fork_tar_x(const char *path, pid_t *ret) {
27         _cleanup_close_pair_ int pipefd[2] = { -1, -1 };
28         bool use_selinux;
29         pid_t pid;
30         int r;
31 
32         assert(path);
33         assert(ret);
34 
35         if (pipe2(pipefd, O_CLOEXEC) < 0)
36                 return log_error_errno(errno, "Failed to create pipe for tar: %m");
37 
38         use_selinux = mac_selinux_use();
39 
40         r = safe_fork("(tar)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
41         if (r < 0)
42                 return r;
43         if (r == 0) {
44                 const char *cmdline[] = {
45                        "tar",
46                        "--ignore-zeros",
47                        "--numeric-owner",
48                        "-C", path,
49                        "-px",
50                        "--xattrs",
51                        "--xattrs-include=*",
52                        use_selinux ? "--selinux" : "--no-selinux",
53                        NULL
54                 };
55 
56                 uint64_t retain =
57                         (1ULL << CAP_CHOWN) |
58                         (1ULL << CAP_FOWNER) |
59                         (1ULL << CAP_FSETID) |
60                         (1ULL << CAP_MKNOD) |
61                         (1ULL << CAP_SETFCAP) |
62                         (1ULL << CAP_DAC_OVERRIDE);
63 
64                 /* Child */
65 
66                 pipefd[1] = safe_close(pipefd[1]);
67 
68                 r = rearrange_stdio(TAKE_FD(pipefd[0]), -1, STDERR_FILENO);
69                 if (r < 0) {
70                         log_error_errno(r, "Failed to rearrange stdin/stdout: %m");
71                         _exit(EXIT_FAILURE);
72                 }
73 
74                 if (unshare(CLONE_NEWNET) < 0)
75                         log_warning_errno(errno, "Failed to lock tar into network namespace, ignoring: %m");
76 
77                 r = capability_bounding_set_drop(retain, true);
78                 if (r < 0)
79                         log_warning_errno(r, "Failed to drop capabilities, ignoring: %m");
80 
81                 /* Try "gtar" before "tar". We only test things upstream with GNU tar. Some distros appear to
82                  * install a different implementation as "tar" (in particular some that do not support the
83                  * same command line switches), but then provide "gtar" as alias for the real thing, hence
84                  * let's prefer that. (Yes, it's a bad idea they do that, given they don't provide equivalent
85                  * command line support, but we are not here to argue, let's just expose the same
86                  * behaviour/implementation everywhere.) */
87                 execvp("gtar", (char* const*) cmdline);
88                 execvp("tar", (char* const*) cmdline);
89 
90                 log_error_errno(errno, "Failed to execute tar: %m");
91                 _exit(EXIT_FAILURE);
92         }
93 
94         *ret = pid;
95 
96         return TAKE_FD(pipefd[1]);
97 }
98 
import_fork_tar_c(const char * path,pid_t * ret)99 int import_fork_tar_c(const char *path, pid_t *ret) {
100         _cleanup_close_pair_ int pipefd[2] = { -1, -1 };
101         bool use_selinux;
102         pid_t pid;
103         int r;
104 
105         assert(path);
106         assert(ret);
107 
108         if (pipe2(pipefd, O_CLOEXEC) < 0)
109                 return log_error_errno(errno, "Failed to create pipe for tar: %m");
110 
111         use_selinux = mac_selinux_use();
112 
113         r = safe_fork("(tar)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
114         if (r < 0)
115                 return r;
116         if (r == 0) {
117                 const char *cmdline[] = {
118                         "tar",
119                         "-C", path,
120                         "-c",
121                         "--xattrs",
122                         "--xattrs-include=*",
123                        use_selinux ? "--selinux" : "--no-selinux",
124                         ".",
125                         NULL
126                 };
127 
128                 uint64_t retain = (1ULL << CAP_DAC_OVERRIDE);
129 
130                 /* Child */
131 
132                 pipefd[0] = safe_close(pipefd[0]);
133 
134                 r = rearrange_stdio(-1, TAKE_FD(pipefd[1]), STDERR_FILENO);
135                 if (r < 0) {
136                         log_error_errno(r, "Failed to rearrange stdin/stdout: %m");
137                         _exit(EXIT_FAILURE);
138                 }
139 
140                 if (unshare(CLONE_NEWNET) < 0)
141                         log_error_errno(errno, "Failed to lock tar into network namespace, ignoring: %m");
142 
143                 r = capability_bounding_set_drop(retain, true);
144                 if (r < 0)
145                         log_error_errno(r, "Failed to drop capabilities, ignoring: %m");
146 
147                 execvp("gtar", (char* const*) cmdline);
148                 execvp("tar", (char* const*) cmdline);
149 
150                 log_error_errno(errno, "Failed to execute tar: %m");
151                 _exit(EXIT_FAILURE);
152         }
153 
154         *ret = pid;
155 
156         return TAKE_FD(pipefd[0]);
157 }
158 
import_mangle_os_tree(const char * path)159 int import_mangle_os_tree(const char *path) {
160         _cleanup_free_ char *child = NULL, *t = NULL, *joined = NULL;
161         _cleanup_closedir_ DIR *d = NULL, *cd = NULL;
162         struct dirent *dent;
163         struct stat st;
164         int r;
165 
166         assert(path);
167 
168         /* Some tarballs contain a single top-level directory that contains the actual OS directory tree. Try to
169          * recognize this, and move the tree one level up. */
170 
171         r = path_is_os_tree(path);
172         if (r < 0)
173                 return log_error_errno(r, "Failed to determine whether '%s' is an OS tree: %m", path);
174         if (r > 0) {
175                 log_debug("Directory tree '%s' is a valid OS tree.", path);
176                 return 0;
177         }
178 
179         log_debug("Directory tree '%s' is not recognizable as OS tree, checking whether to rearrange it.", path);
180 
181         d = opendir(path);
182         if (!d)
183                 return log_error_errno(r, "Failed to open directory '%s': %m", path);
184 
185         errno = 0;
186         dent = readdir_no_dot(d);
187         if (!dent) {
188                 if (errno != 0)
189                         return log_error_errno(errno, "Failed to iterate through directory '%s': %m", path);
190 
191                 log_debug("Directory '%s' is empty, leaving it as it is.", path);
192                 return 0;
193         }
194 
195         child = strdup(dent->d_name);
196         if (!child)
197                 return log_oom();
198 
199         errno = 0;
200         dent = readdir_no_dot(d);
201         if (dent) {
202                 if (errno != 0)
203                         return log_error_errno(errno, "Failed to iterate through directory '%s': %m", path);
204 
205                 log_debug("Directory '%s' does not look like an OS tree, and has multiple children, leaving as it is.", path);
206                 return 0;
207         }
208 
209         if (fstatat(dirfd(d), child, &st, AT_SYMLINK_NOFOLLOW) < 0)
210                 return log_debug_errno(errno, "Failed to stat file '%s/%s': %m", path, child);
211         r = stat_verify_directory(&st);
212         if (r < 0) {
213                 log_debug_errno(r, "Child '%s' of directory '%s' is not a directory, leaving things as they are.", child, path);
214                 return 0;
215         }
216 
217         joined = path_join(path, child);
218         if (!joined)
219                 return log_oom();
220         r = path_is_os_tree(joined);
221         if (r == -ENOTDIR) {
222                 log_debug("Directory '%s' does not look like an OS tree, and contains a single regular file only, leaving as it is.", path);
223                 return 0;
224         }
225         if (r < 0)
226                 return log_error_errno(r, "Failed to determine whether '%s' is an OS tree: %m", joined);
227         if (r == 0) {
228                 log_debug("Neither '%s' nor '%s' is a valid OS tree, leaving them as they are.", path, joined);
229                 return 0;
230         }
231 
232         /* Nice, we have checked now:
233          *
234          * 1. The top-level directory does not qualify as OS tree
235          * 1. The top-level directory only contains one item
236          * 2. That item is a directory
237          * 3. And that directory qualifies as OS tree
238          *
239          * Let's now rearrange things, moving everything in the inner directory one level up */
240 
241         cd = xopendirat(dirfd(d), child, O_NOFOLLOW);
242         if (!cd)
243                 return log_error_errno(errno, "Can't open directory '%s': %m", joined);
244 
245         log_info("Rearranging '%s', moving OS tree one directory up.", joined);
246 
247         /* Let's rename the child to an unguessable name so that we can be sure all files contained in it can be
248          * safely moved up and won't collide with the name. */
249         r = tempfn_random(child, NULL, &t);
250         if (r < 0)
251                 return log_oom();
252         r = rename_noreplace(dirfd(d), child, dirfd(d), t);
253         if (r < 0)
254                 return log_error_errno(r, "Unable to rename '%s' to '%s/%s': %m", joined, path, t);
255 
256         FOREACH_DIRENT_ALL(de, cd, return log_error_errno(errno, "Failed to iterate through directory '%s': %m", joined)) {
257                 if (dot_or_dot_dot(de->d_name))
258                         continue;
259 
260                 r = rename_noreplace(dirfd(cd), de->d_name, dirfd(d), de->d_name);
261                 if (r < 0)
262                         return log_error_errno(r, "Unable to move '%s/%s/%s' to '%s/%s': %m", path, t, de->d_name, path, de->d_name);
263         }
264 
265         if (unlinkat(dirfd(d), t, AT_REMOVEDIR) < 0)
266                 return log_error_errno(errno, "Failed to remove temporary directory '%s/%s': %m", path, t);
267 
268         r = futimens(dirfd(d), (struct timespec[2]) { st.st_atim, st.st_mtim });
269         if (r < 0)
270                 log_debug_errno(r, "Failed to adjust top-level timestamps '%s', ignoring: %m", path);
271 
272         r = fchmod_and_chown(dirfd(d), st.st_mode, st.st_uid, st.st_gid);
273         if (r < 0)
274                 return log_error_errno(r, "Failed to adjust top-level directory mode/ownership '%s': %m", path);
275 
276         log_info("Successfully rearranged OS tree.");
277 
278         return 0;
279 }
280 
import_validate_local(const char * name,ImportFlags flags)281 bool import_validate_local(const char *name, ImportFlags flags) {
282 
283         /* By default we insist on a valid hostname for naming images. But optionally we relax that, in which
284          * case it can be any path name */
285 
286         if (FLAGS_SET(flags, IMPORT_DIRECT))
287                 return path_is_valid(name);
288 
289         return hostname_is_valid(name, 0);
290 }
291 
interrupt_signal_handler(sd_event_source * s,const struct signalfd_siginfo * si,void * userdata)292 static int interrupt_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
293         log_notice("Transfer aborted.");
294         sd_event_exit(sd_event_source_get_event(s), EINTR);
295         return 0;
296 }
297 
import_allocate_event_with_signals(sd_event ** ret)298 int import_allocate_event_with_signals(sd_event **ret) {
299         _cleanup_(sd_event_unrefp) sd_event *event = NULL;
300         int r;
301 
302         assert(ret);
303 
304         r = sd_event_default(&event);
305         if (r < 0)
306                 return log_error_errno(r, "Failed to allocate event loop: %m");
307 
308         assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
309         (void) sd_event_add_signal(event, NULL, SIGTERM, interrupt_signal_handler,  NULL);
310         (void) sd_event_add_signal(event, NULL, SIGINT, interrupt_signal_handler, NULL);
311 
312         *ret = TAKE_PTR(event);
313         return 0;
314 }
315