]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/import/pull-common.c
tree-wide: drop license boilerplate
[thirdparty/systemd.git] / src / import / pull-common.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2015 Lennart Poettering
6 ***/
7
8 #include <sys/prctl.h>
9
10 #include "alloc-util.h"
11 #include "btrfs-util.h"
12 #include "capability-util.h"
13 #include "copy.h"
14 #include "dirent-util.h"
15 #include "escape.h"
16 #include "fd-util.h"
17 #include "io-util.h"
18 #include "path-util.h"
19 #include "process-util.h"
20 #include "pull-common.h"
21 #include "pull-job.h"
22 #include "rm-rf.h"
23 #include "signal-util.h"
24 #include "siphash24.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "util.h"
28 #include "web-util.h"
29
30 #define FILENAME_ESCAPE "/.#\"\'"
31 #define HASH_URL_THRESHOLD_LENGTH (_POSIX_PATH_MAX - 16)
32
33 int pull_find_old_etags(
34 const char *url,
35 const char *image_root,
36 int dt,
37 const char *prefix,
38 const char *suffix,
39 char ***etags) {
40
41 _cleanup_free_ char *escaped_url = NULL;
42 _cleanup_closedir_ DIR *d = NULL;
43 _cleanup_strv_free_ char **l = NULL;
44 struct dirent *de;
45 int r;
46
47 assert(url);
48 assert(etags);
49
50 if (!image_root)
51 image_root = "/var/lib/machines";
52
53 escaped_url = xescape(url, FILENAME_ESCAPE);
54 if (!escaped_url)
55 return -ENOMEM;
56
57 d = opendir(image_root);
58 if (!d) {
59 if (errno == ENOENT) {
60 *etags = NULL;
61 return 0;
62 }
63
64 return -errno;
65 }
66
67 FOREACH_DIRENT_ALL(de, d, return -errno) {
68 const char *a, *b;
69 char *u;
70
71 if (de->d_type != DT_UNKNOWN &&
72 de->d_type != dt)
73 continue;
74
75 if (prefix) {
76 a = startswith(de->d_name, prefix);
77 if (!a)
78 continue;
79 } else
80 a = de->d_name;
81
82 a = startswith(a, escaped_url);
83 if (!a)
84 continue;
85
86 a = startswith(a, ".");
87 if (!a)
88 continue;
89
90 if (suffix) {
91 b = endswith(de->d_name, suffix);
92 if (!b)
93 continue;
94 } else
95 b = strchr(de->d_name, 0);
96
97 if (a >= b)
98 continue;
99
100 r = cunescape_length(a, b - a, 0, &u);
101 if (r < 0)
102 return r;
103
104 if (!http_etag_is_valid(u)) {
105 free(u);
106 continue;
107 }
108
109 r = strv_consume(&l, u);
110 if (r < 0)
111 return r;
112 }
113
114 *etags = TAKE_PTR(l);
115
116 return 0;
117 }
118
119 int pull_make_local_copy(const char *final, const char *image_root, const char *local, bool force_local) {
120 const char *p;
121 int r;
122
123 assert(final);
124 assert(local);
125
126 if (!image_root)
127 image_root = "/var/lib/machines";
128
129 p = strjoina(image_root, "/", local);
130
131 if (force_local)
132 (void) rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
133
134 r = btrfs_subvol_snapshot(final, p,
135 BTRFS_SNAPSHOT_QUOTA|
136 BTRFS_SNAPSHOT_FALLBACK_COPY|
137 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY|
138 BTRFS_SNAPSHOT_RECURSIVE);
139 if (r < 0)
140 return log_error_errno(r, "Failed to create local image: %m");
141
142 log_info("Created new local image '%s'.", local);
143
144 return 0;
145 }
146
147 static int hash_url(const char *url, char **ret) {
148 uint64_t h;
149 static const sd_id128_t k = SD_ID128_ARRAY(df,89,16,87,01,cc,42,30,98,ab,4a,19,a6,a5,63,4f);
150
151 assert(url);
152
153 h = siphash24(url, strlen(url), k.bytes);
154 if (asprintf(ret, "%"PRIx64, h) < 0)
155 return -ENOMEM;
156
157 return 0;
158 }
159
160 int pull_make_path(const char *url, const char *etag, const char *image_root, const char *prefix, const char *suffix, char **ret) {
161 _cleanup_free_ char *escaped_url = NULL, *escaped_etag = NULL;
162 char *path;
163
164 assert(url);
165 assert(ret);
166
167 if (!image_root)
168 image_root = "/var/lib/machines";
169
170 escaped_url = xescape(url, FILENAME_ESCAPE);
171 if (!escaped_url)
172 return -ENOMEM;
173
174 if (etag) {
175 escaped_etag = xescape(etag, FILENAME_ESCAPE);
176 if (!escaped_etag)
177 return -ENOMEM;
178 }
179
180 path = strjoin(image_root, "/", strempty(prefix), escaped_url, escaped_etag ? "." : "",
181 strempty(escaped_etag), strempty(suffix));
182 if (!path)
183 return -ENOMEM;
184
185 /* URLs might make the path longer than the maximum allowed length for a file name.
186 * When that happens, a URL hash is used instead. Paths returned by this function
187 * can be later used with tempfn_random() which adds 16 bytes to the resulting name. */
188 if (strlen(path) >= HASH_URL_THRESHOLD_LENGTH) {
189 _cleanup_free_ char *hash = NULL;
190 int r;
191
192 free(path);
193
194 r = hash_url(url, &hash);
195 if (r < 0)
196 return r;
197
198 path = strjoin(image_root, "/", strempty(prefix), hash, escaped_etag ? "." : "",
199 strempty(escaped_etag), strempty(suffix));
200 if (!path)
201 return -ENOMEM;
202 }
203
204 *ret = path;
205 return 0;
206 }
207
208 int pull_make_auxiliary_job(
209 PullJob **ret,
210 const char *url,
211 int (*strip_suffixes)(const char *name, char **ret),
212 const char *suffix,
213 CurlGlue *glue,
214 PullJobFinished on_finished,
215 void *userdata) {
216
217 _cleanup_free_ char *last_component = NULL, *ll = NULL, *auxiliary_url = NULL;
218 _cleanup_(pull_job_unrefp) PullJob *job = NULL;
219 const char *q;
220 int r;
221
222 assert(ret);
223 assert(url);
224 assert(strip_suffixes);
225 assert(glue);
226
227 r = import_url_last_component(url, &last_component);
228 if (r < 0)
229 return r;
230
231 r = strip_suffixes(last_component, &ll);
232 if (r < 0)
233 return r;
234
235 q = strjoina(ll, suffix);
236
237 r = import_url_change_last_component(url, q, &auxiliary_url);
238 if (r < 0)
239 return r;
240
241 r = pull_job_new(&job, auxiliary_url, glue, userdata);
242 if (r < 0)
243 return r;
244
245 job->on_finished = on_finished;
246 job->compressed_max = job->uncompressed_max = 1ULL * 1024ULL * 1024ULL;
247
248 *ret = TAKE_PTR(job);
249
250 return 0;
251 }
252
253 int pull_make_verification_jobs(
254 PullJob **ret_checksum_job,
255 PullJob **ret_signature_job,
256 ImportVerify verify,
257 const char *url,
258 CurlGlue *glue,
259 PullJobFinished on_finished,
260 void *userdata) {
261
262 _cleanup_(pull_job_unrefp) PullJob *checksum_job = NULL, *signature_job = NULL;
263 int r;
264 const char *chksums = NULL;
265
266 assert(ret_checksum_job);
267 assert(ret_signature_job);
268 assert(verify >= 0);
269 assert(verify < _IMPORT_VERIFY_MAX);
270 assert(url);
271 assert(glue);
272
273 if (verify != IMPORT_VERIFY_NO) {
274 _cleanup_free_ char *checksum_url = NULL, *fn = NULL;
275
276 /* Queue jobs for the checksum file for the image. */
277 r = import_url_last_component(url, &fn);
278 if (r < 0)
279 return r;
280
281 chksums = strjoina(fn, ".sha256");
282
283 r = import_url_change_last_component(url, chksums, &checksum_url);
284 if (r < 0)
285 return r;
286
287 r = pull_job_new(&checksum_job, checksum_url, glue, userdata);
288 if (r < 0)
289 return r;
290
291 checksum_job->on_finished = on_finished;
292 checksum_job->uncompressed_max = checksum_job->compressed_max = 1ULL * 1024ULL * 1024ULL;
293 }
294
295 if (verify == IMPORT_VERIFY_SIGNATURE) {
296 _cleanup_free_ char *signature_url = NULL;
297
298 /* Queue job for the SHA256SUMS.gpg file for the image. */
299 r = import_url_change_last_component(url, "SHA256SUMS.gpg", &signature_url);
300 if (r < 0)
301 return r;
302
303 r = pull_job_new(&signature_job, signature_url, glue, userdata);
304 if (r < 0)
305 return r;
306
307 signature_job->on_finished = on_finished;
308 signature_job->uncompressed_max = signature_job->compressed_max = 1ULL * 1024ULL * 1024ULL;
309 }
310
311 *ret_checksum_job = checksum_job;
312 *ret_signature_job = signature_job;
313
314 checksum_job = signature_job = NULL;
315
316 return 0;
317 }
318
319 static int verify_one(PullJob *checksum_job, PullJob *job) {
320 _cleanup_free_ char *fn = NULL;
321 const char *line, *p;
322 int r;
323
324 assert(checksum_job);
325
326 if (!job)
327 return 0;
328
329 assert(IN_SET(job->state, PULL_JOB_DONE, PULL_JOB_FAILED));
330
331 /* Don't verify the checksum if we didn't actually successfully download something new */
332 if (job->state != PULL_JOB_DONE)
333 return 0;
334 if (job->error != 0)
335 return 0;
336 if (job->etag_exists)
337 return 0;
338
339 assert(job->calc_checksum);
340 assert(job->checksum);
341
342 r = import_url_last_component(job->url, &fn);
343 if (r < 0)
344 return log_oom();
345
346 if (!filename_is_valid(fn)) {
347 log_error("Cannot verify checksum, could not determine server-side file name.");
348 return -EBADMSG;
349 }
350
351 line = strjoina(job->checksum, " *", fn, "\n");
352
353 p = memmem(checksum_job->payload,
354 checksum_job->payload_size,
355 line,
356 strlen(line));
357
358 if (!p) {
359 line = strjoina(job->checksum, " ", fn, "\n");
360
361 p = memmem(checksum_job->payload,
362 checksum_job->payload_size,
363 line,
364 strlen(line));
365 }
366
367 if (!p || (p != (char*) checksum_job->payload && p[-1] != '\n')) {
368 log_error("DOWNLOAD INVALID: Checksum of %s file did not checkout, file has been tampered with.", fn);
369 return -EBADMSG;
370 }
371
372 log_info("SHA256 checksum of %s is valid.", job->url);
373 return 1;
374 }
375
376 int pull_verify(PullJob *main_job,
377 PullJob *roothash_job,
378 PullJob *settings_job,
379 PullJob *checksum_job,
380 PullJob *signature_job) {
381
382 _cleanup_close_pair_ int gpg_pipe[2] = { -1, -1 };
383 _cleanup_close_ int sig_file = -1;
384 char sig_file_path[] = "/tmp/sigXXXXXX", gpg_home[] = "/tmp/gpghomeXXXXXX";
385 _cleanup_(sigkill_waitp) pid_t pid = 0;
386 bool gpg_home_created = false;
387 int r;
388
389 assert(main_job);
390 assert(main_job->state == PULL_JOB_DONE);
391
392 if (!checksum_job)
393 return 0;
394
395 assert(main_job->calc_checksum);
396 assert(main_job->checksum);
397
398 assert(checksum_job->state == PULL_JOB_DONE);
399
400 if (!checksum_job->payload || checksum_job->payload_size <= 0) {
401 log_error("Checksum is empty, cannot verify.");
402 return -EBADMSG;
403 }
404
405 r = verify_one(checksum_job, main_job);
406 if (r < 0)
407 return r;
408
409 r = verify_one(checksum_job, roothash_job);
410 if (r < 0)
411 return r;
412
413 r = verify_one(checksum_job, settings_job);
414 if (r < 0)
415 return r;
416
417 if (!signature_job)
418 return 0;
419
420 if (checksum_job->style == VERIFICATION_PER_FILE)
421 signature_job = checksum_job;
422
423 assert(signature_job->state == PULL_JOB_DONE);
424
425 if (!signature_job->payload || signature_job->payload_size <= 0) {
426 log_error("Signature is empty, cannot verify.");
427 return -EBADMSG;
428 }
429
430 r = pipe2(gpg_pipe, O_CLOEXEC);
431 if (r < 0)
432 return log_error_errno(errno, "Failed to create pipe for gpg: %m");
433
434 sig_file = mkostemp(sig_file_path, O_RDWR);
435 if (sig_file < 0)
436 return log_error_errno(errno, "Failed to create temporary file: %m");
437
438 r = loop_write(sig_file, signature_job->payload, signature_job->payload_size, false);
439 if (r < 0) {
440 log_error_errno(r, "Failed to write to temporary file: %m");
441 goto finish;
442 }
443
444 if (!mkdtemp(gpg_home)) {
445 r = log_error_errno(errno, "Failed to create tempory home for gpg: %m");
446 goto finish;
447 }
448
449 gpg_home_created = true;
450
451 r = safe_fork("(gpg)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
452 if (r < 0)
453 return r;
454 if (r == 0) {
455 const char *cmd[] = {
456 "gpg",
457 "--no-options",
458 "--no-default-keyring",
459 "--no-auto-key-locate",
460 "--no-auto-check-trustdb",
461 "--batch",
462 "--trust-model=always",
463 NULL, /* --homedir= */
464 NULL, /* --keyring= */
465 NULL, /* --verify */
466 NULL, /* signature file */
467 NULL, /* dash */
468 NULL /* trailing NULL */
469 };
470 unsigned k = ELEMENTSOF(cmd) - 6;
471
472 /* Child */
473
474 gpg_pipe[1] = safe_close(gpg_pipe[1]);
475
476 r = rearrange_stdio(gpg_pipe[0], -1, STDERR_FILENO);
477 if (r < 0) {
478 log_error_errno(r, "Failed to rearrange stdin/stdout: %m");
479 _exit(EXIT_FAILURE);
480 }
481
482 cmd[k++] = strjoina("--homedir=", gpg_home);
483
484 /* We add the user keyring only to the command line
485 * arguments, if it's around since gpg fails
486 * otherwise. */
487 if (access(USER_KEYRING_PATH, F_OK) >= 0)
488 cmd[k++] = "--keyring=" USER_KEYRING_PATH;
489 else
490 cmd[k++] = "--keyring=" VENDOR_KEYRING_PATH;
491
492 cmd[k++] = "--verify";
493 if (checksum_job->style == VERIFICATION_PER_DIRECTORY) {
494 cmd[k++] = sig_file_path;
495 cmd[k++] = "-";
496 cmd[k++] = NULL;
497 }
498
499 execvp("gpg2", (char * const *) cmd);
500 execvp("gpg", (char * const *) cmd);
501 log_error_errno(errno, "Failed to execute gpg: %m");
502 _exit(EXIT_FAILURE);
503 }
504
505 gpg_pipe[0] = safe_close(gpg_pipe[0]);
506
507 r = loop_write(gpg_pipe[1], checksum_job->payload, checksum_job->payload_size, false);
508 if (r < 0) {
509 log_error_errno(r, "Failed to write to pipe: %m");
510 goto finish;
511 }
512
513 gpg_pipe[1] = safe_close(gpg_pipe[1]);
514
515 r = wait_for_terminate_and_check("gpg", pid, WAIT_LOG_ABNORMAL);
516 pid = 0;
517 if (r < 0)
518 goto finish;
519 if (r != EXIT_SUCCESS) {
520 log_error("DOWNLOAD INVALID: Signature verification failed.");
521 r = -EBADMSG;
522 } else {
523 log_info("Signature verification succeeded.");
524 r = 0;
525 }
526
527 finish:
528 if (sig_file >= 0)
529 (void) unlink(sig_file_path);
530
531 if (gpg_home_created)
532 (void) rm_rf(gpg_home, REMOVE_ROOT|REMOVE_PHYSICAL);
533
534 return r;
535 }