1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include "alloc-util.h"
6 #include "btrfs-util.h"
7 #include "capability-util.h"
9 #include "dirent-util.h"
12 #include "hostname-util.h"
14 #include "memory-util.h"
15 #include "path-util.h"
16 #include "process-util.h"
17 #include "pull-common.h"
19 #include "rlimit-util.h"
21 #include "signal-util.h"
22 #include "siphash24.h"
23 #include "string-util.h"
28 #define FILENAME_ESCAPE "/.#\"\'"
29 #define HASH_URL_THRESHOLD_LENGTH (_POSIX_PATH_MAX - 16)
31 int pull_find_old_etags(
33 const char *image_root
,
45 image_root
= "/var/lib/machines";
47 _cleanup_free_
char *escaped_url
= xescape(url
, FILENAME_ESCAPE
);
51 _cleanup_closedir_
DIR *d
= opendir(image_root
);
53 if (errno
== ENOENT
) {
61 _cleanup_strv_free_
char **ans
= NULL
;
63 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
64 _cleanup_free_
char *u
= NULL
;
67 if (de
->d_type
!= DT_UNKNOWN
&&
72 a
= startswith(de
->d_name
, prefix
);
78 a
= startswith(a
, escaped_url
);
82 a
= startswith(a
, ".");
87 b
= endswith(de
->d_name
, suffix
);
91 b
= strchr(de
->d_name
, 0);
96 ssize_t l
= cunescape_length(a
, b
- a
, 0, &u
);
98 assert(l
>= INT8_MIN
);
102 if (!http_etag_is_valid(u
))
105 r
= strv_consume(&ans
, TAKE_PTR(u
));
110 *etags
= TAKE_PTR(ans
);
115 static int hash_url(const char *url
, char **ret
) {
117 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
);
121 h
= siphash24(url
, strlen(url
), k
.bytes
);
122 if (asprintf(ret
, "%"PRIx64
, h
) < 0)
128 int pull_make_path(const char *url
, const char *etag
, const char *image_root
, const char *prefix
, const char *suffix
, char **ret
) {
129 _cleanup_free_
char *escaped_url
= NULL
, *escaped_etag
= NULL
;
136 image_root
= "/var/lib/machines";
138 escaped_url
= xescape(url
, FILENAME_ESCAPE
);
143 escaped_etag
= xescape(etag
, FILENAME_ESCAPE
);
148 path
= strjoin(image_root
, "/", strempty(prefix
), escaped_url
, escaped_etag
? "." : "",
149 strempty(escaped_etag
), strempty(suffix
));
153 /* URLs might make the path longer than the maximum allowed length for a file name.
154 * When that happens, a URL hash is used instead. Paths returned by this function
155 * can be later used with tempfn_random() which adds 16 bytes to the resulting name. */
156 if (strlen(path
) >= HASH_URL_THRESHOLD_LENGTH
) {
157 _cleanup_free_
char *hash
= NULL
;
162 r
= hash_url(url
, &hash
);
166 path
= strjoin(image_root
, "/", strempty(prefix
), hash
, escaped_etag
? "." : "",
167 strempty(escaped_etag
), strempty(suffix
));
176 int pull_make_auxiliary_job(
179 int (*strip_suffixes
)(const char *name
, char **ret
),
183 PullJobOpenDisk on_open_disk
,
184 PullJobFinished on_finished
,
187 _cleanup_free_
char *last_component
= NULL
, *ll
= NULL
, *auxiliary_url
= NULL
;
188 _cleanup_(pull_job_unrefp
) PullJob
*job
= NULL
;
194 assert(strip_suffixes
);
197 r
= import_url_last_component(url
, &last_component
);
201 r
= strip_suffixes(last_component
, &ll
);
205 q
= strjoina(ll
, suffix
);
207 r
= import_url_change_last_component(url
, q
, &auxiliary_url
);
211 r
= pull_job_new(&job
, auxiliary_url
, glue
, userdata
);
215 job
->on_open_disk
= on_open_disk
;
216 job
->on_finished
= on_finished
;
217 job
->compressed_max
= job
->uncompressed_max
= 1ULL * 1024ULL * 1024ULL;
218 job
->calc_checksum
= IN_SET(verify
, IMPORT_VERIFY_CHECKSUM
, IMPORT_VERIFY_SIGNATURE
);
220 *ret
= TAKE_PTR(job
);
224 static bool is_checksum_file(const char *fn
) {
225 /* Returns true if the specified filename refers to a checksum file we grok */
230 return streq(fn
, "SHA256SUMS") || endswith(fn
, ".sha256");
233 static bool is_signature_file(const char *fn
) {
234 /* Returns true if the specified filename refers to a signature file we grok (reminder:
235 * suse-style .sha256 files are inline signed) */
240 return streq(fn
, "SHA256SUMS.gpg") || endswith(fn
, ".sha256");
243 int pull_make_verification_jobs(
244 PullJob
**ret_checksum_job
,
245 PullJob
**ret_signature_job
,
247 const char *checksum
, /* set if literal checksum verification is requested, in which case 'verify' is set to _IMPORT_VERIFY_INVALID */
250 PullJobFinished on_finished
,
253 _cleanup_(pull_job_unrefp
) PullJob
*checksum_job
= NULL
, *signature_job
= NULL
;
254 _cleanup_free_
char *fn
= NULL
;
257 assert(ret_checksum_job
);
258 assert(ret_signature_job
);
259 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
< _IMPORT_VERIFY_MAX
);
260 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
>= 0);
261 assert((verify
< 0) || !checksum
);
265 /* If verification is turned off, or if the checksum to validate is already specified we don't need
266 * to download a checksum file or signature, hence shortcut things */
267 if (verify
== IMPORT_VERIFY_NO
|| checksum
) {
268 *ret_checksum_job
= *ret_signature_job
= NULL
;
272 r
= import_url_last_component(url
, &fn
);
273 if (r
< 0 && r
!= -EADDRNOTAVAIL
) /* EADDRNOTAVAIL means there was no last component, which is OK for
274 * us, we'll just assume it's not a checksum/signature file */
277 /* Acquire the checksum file if verification or signature verification is requested and the main file
278 * to acquire isn't a checksum or signature file anyway */
279 if (verify
!= IMPORT_VERIFY_NO
&& !is_checksum_file(fn
) && !is_signature_file(fn
)) {
280 _cleanup_free_
char *checksum_url
= NULL
;
281 const char *suffixed
= NULL
;
283 /* Queue jobs for the checksum file for the image. */
286 suffixed
= strjoina(fn
, ".sha256"); /* Start with the suse-style checksum (if there's a base filename) */
288 suffixed
= "SHA256SUMS";
290 r
= import_url_change_last_component(url
, suffixed
, &checksum_url
);
294 r
= pull_job_new(&checksum_job
, checksum_url
, glue
, userdata
);
298 checksum_job
->on_finished
= on_finished
;
299 checksum_job
->uncompressed_max
= checksum_job
->compressed_max
= 1ULL * 1024ULL * 1024ULL;
300 checksum_job
->on_not_found
= pull_job_restart_with_sha256sum
; /* if this fails, look for ubuntu-style checksum */
303 if (verify
== IMPORT_VERIFY_SIGNATURE
&& !is_signature_file(fn
)) {
304 _cleanup_free_
char *signature_url
= NULL
;
306 /* Queue job for the SHA256SUMS.gpg file for the image. */
307 r
= import_url_change_last_component(url
, "SHA256SUMS.gpg", &signature_url
);
311 r
= pull_job_new(&signature_job
, signature_url
, glue
, userdata
);
315 signature_job
->on_finished
= on_finished
;
316 signature_job
->uncompressed_max
= signature_job
->compressed_max
= 1ULL * 1024ULL * 1024ULL;
319 *ret_checksum_job
= TAKE_PTR(checksum_job
);
320 *ret_signature_job
= TAKE_PTR(signature_job
);
324 static int verify_one(PullJob
*checksum_job
, PullJob
*job
) {
325 _cleanup_free_
char *fn
= NULL
;
326 const char *line
, *p
;
329 assert(checksum_job
);
334 assert(IN_SET(job
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
));
336 /* Don't verify the checksum if we didn't actually successfully download something new */
337 if (job
->state
!= PULL_JOB_DONE
)
341 if (job
->etag_exists
)
344 assert(job
->calc_checksum
);
345 assert(job
->checksum
);
347 r
= import_url_last_component(job
->url
, &fn
);
349 return log_error_errno(r
, "Failed to extract filename from URL '%s': %m", job
->url
);
351 if (!filename_is_valid(fn
))
352 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
353 "Cannot verify checksum, could not determine server-side file name.");
355 if (is_checksum_file(fn
) || is_signature_file(fn
)) /* We cannot verify checksum files or signature files with a checksum file */
356 return log_error_errno(SYNTHETIC_ERRNO(ELOOP
),
357 "Cannot verify checksum/signature files via themselves.");
359 line
= strjoina(job
->checksum
, " *", fn
, "\n"); /* string for binary mode */
360 p
= memmem_safe(checksum_job
->payload
,
361 checksum_job
->payload_size
,
365 line
= strjoina(job
->checksum
, " ", fn
, "\n"); /* string for text mode */
366 p
= memmem_safe(checksum_job
->payload
,
367 checksum_job
->payload_size
,
372 /* Only counts if found at beginning of a line */
373 if (!p
|| (p
!= (char*) checksum_job
->payload
&& p
[-1] != '\n'))
374 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
375 "DOWNLOAD INVALID: Checksum of %s file did not check out, file has been tampered with.", fn
);
377 log_info("SHA256 checksum of %s is valid.", job
->url
);
381 static int verify_gpg(
382 const void *payload
, size_t payload_size
,
383 const void *signature
, size_t signature_size
) {
385 _cleanup_close_pair_
int gpg_pipe
[2] = { -1, -1 };
386 char sig_file_path
[] = "/tmp/sigXXXXXX", gpg_home
[] = "/tmp/gpghomeXXXXXX";
387 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
388 bool gpg_home_created
= false;
391 assert(payload
|| payload_size
== 0);
392 assert(signature
|| signature_size
== 0);
394 r
= pipe2(gpg_pipe
, O_CLOEXEC
);
396 return log_error_errno(errno
, "Failed to create pipe for gpg: %m");
398 if (signature_size
> 0) {
399 _cleanup_close_
int sig_file
= -1;
401 sig_file
= mkostemp(sig_file_path
, O_RDWR
);
403 return log_error_errno(errno
, "Failed to create temporary file: %m");
405 r
= loop_write(sig_file
, signature
, signature_size
, false);
407 log_error_errno(r
, "Failed to write to temporary file: %m");
412 if (!mkdtemp(gpg_home
)) {
413 r
= log_error_errno(errno
, "Failed to create temporary home for gpg: %m");
417 gpg_home_created
= true;
419 r
= safe_fork("(gpg)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &pid
);
423 const char *cmd
[] = {
426 "--no-default-keyring",
427 "--no-auto-key-locate",
428 "--no-auto-check-trustdb",
430 "--trust-model=always",
431 NULL
, /* --homedir= */
432 NULL
, /* --keyring= */
434 NULL
, /* signature file */
436 NULL
/* trailing NULL */
438 size_t k
= ELEMENTSOF(cmd
) - 6;
442 gpg_pipe
[1] = safe_close(gpg_pipe
[1]);
444 r
= rearrange_stdio(TAKE_FD(gpg_pipe
[0]), -1, STDERR_FILENO
);
446 log_error_errno(r
, "Failed to rearrange stdin/stdout: %m");
450 (void) rlimit_nofile_safe();
452 cmd
[k
++] = strjoina("--homedir=", gpg_home
);
454 /* We add the user keyring only to the command line arguments, if it's around since gpg fails
456 if (access(USER_KEYRING_PATH
, F_OK
) >= 0)
457 cmd
[k
++] = "--keyring=" USER_KEYRING_PATH
;
459 cmd
[k
++] = "--keyring=" VENDOR_KEYRING_PATH
;
461 cmd
[k
++] = "--verify";
463 cmd
[k
++] = sig_file_path
;
468 execvp("gpg2", (char * const *) cmd
);
469 execvp("gpg", (char * const *) cmd
);
470 log_error_errno(errno
, "Failed to execute gpg: %m");
474 gpg_pipe
[0] = safe_close(gpg_pipe
[0]);
476 r
= loop_write(gpg_pipe
[1], payload
, payload_size
, false);
478 log_error_errno(r
, "Failed to write to pipe: %m");
482 gpg_pipe
[1] = safe_close(gpg_pipe
[1]);
484 r
= wait_for_terminate_and_check("gpg", TAKE_PID(pid
), WAIT_LOG_ABNORMAL
);
487 if (r
!= EXIT_SUCCESS
)
488 r
= log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
489 "DOWNLOAD INVALID: Signature verification failed.");
491 log_info("Signature verification succeeded.");
496 if (signature_size
> 0)
497 (void) unlink(sig_file_path
);
499 if (gpg_home_created
)
500 (void) rm_rf(gpg_home
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
505 int pull_verify(ImportVerify verify
,
506 const char *checksum
, /* Verify with literal checksum */
508 PullJob
*checksum_job
,
509 PullJob
*signature_job
,
510 PullJob
*settings_job
,
511 PullJob
*roothash_job
,
512 PullJob
*roothash_signature_job
,
513 PullJob
*verity_job
) {
515 _cleanup_free_
char *fn
= NULL
;
516 VerificationStyle style
;
520 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
< _IMPORT_VERIFY_MAX
);
521 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
>= 0);
522 assert((verify
< 0) || !checksum
);
524 assert(main_job
->state
== PULL_JOB_DONE
);
526 if (verify
== IMPORT_VERIFY_NO
) /* verification turned off */
530 /* Verification by literal checksum */
531 assert(!checksum_job
);
532 assert(!signature_job
);
533 assert(!settings_job
);
534 assert(!roothash_job
);
535 assert(!roothash_signature_job
);
538 assert(main_job
->calc_checksum
);
539 assert(main_job
->checksum
);
541 if (!strcaseeq(checksum
, main_job
->checksum
))
542 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
543 "DOWNLOAD INVALID: Checksum of %s file did not check out, file has been tampered with.",
549 r
= import_url_last_component(main_job
->url
, &fn
);
551 return log_error_errno(r
, "Failed to extract filename from URL '%s': %m", main_job
->url
);
553 if (is_signature_file(fn
))
554 return log_error_errno(SYNTHETIC_ERRNO(ELOOP
),
555 "Main download is a signature file, can't verify it.");
557 if (is_checksum_file(fn
)) {
558 log_debug("Main download is a checksum file, can't validate its checksum with itself, skipping.");
559 verify_job
= main_job
;
562 assert(main_job
->calc_checksum
);
563 assert(main_job
->checksum
);
564 assert(checksum_job
);
565 assert(checksum_job
->state
== PULL_JOB_DONE
);
567 if (!checksum_job
->payload
|| checksum_job
->payload_size
<= 0)
568 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
569 "Checksum is empty, cannot verify.");
571 FOREACH_POINTER(j
, main_job
, settings_job
, roothash_job
, roothash_signature_job
, verity_job
) {
572 r
= verify_one(checksum_job
, j
);
577 verify_job
= checksum_job
;
580 if (verify
!= IMPORT_VERIFY_SIGNATURE
)
585 r
= verification_style_from_url(verify_job
->url
, &style
);
587 return log_error_errno(r
, "Failed to determine verification style from URL '%s': %m", verify_job
->url
);
589 if (style
== VERIFICATION_PER_DIRECTORY
) {
590 assert(signature_job
);
591 assert(signature_job
->state
== PULL_JOB_DONE
);
593 if (!signature_job
->payload
|| signature_job
->payload_size
<= 0)
594 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
595 "Signature is empty, cannot verify.");
597 return verify_gpg(verify_job
->payload
, verify_job
->payload_size
, signature_job
->payload
, signature_job
->payload_size
);
599 return verify_gpg(verify_job
->payload
, verify_job
->payload_size
, NULL
, 0);
602 int verification_style_from_url(const char *url
, VerificationStyle
*ret
) {
603 _cleanup_free_
char *last
= NULL
;
609 /* Determines which kind of verification style is appropriate for this url */
611 r
= import_url_last_component(url
, &last
);
615 if (streq(last
, "SHA256SUMS")) {
616 *ret
= VERIFICATION_PER_DIRECTORY
;
620 if (endswith(last
, ".sha256")) {
621 *ret
= VERIFICATION_PER_FILE
;
628 int pull_job_restart_with_sha256sum(PullJob
*j
, char **ret
) {
629 VerificationStyle style
;
634 /* Generic implementation of a PullJobNotFound handler, that restarts the job requesting SHA256SUMS */
636 r
= verification_style_from_url(j
->url
, &style
);
638 return log_error_errno(r
, "Failed to determine verification style of URL '%s': %m", j
->url
);
640 if (style
== VERIFICATION_PER_DIRECTORY
) /* Nothing to do anymore */
643 assert(style
== VERIFICATION_PER_FILE
); /* This must have been .sha256 style URL before */
645 log_debug("Got 404 for %s, now trying to get SHA256SUMS instead.", j
->url
);
647 r
= import_url_change_last_component(j
->url
, "SHA256SUMS", ret
);
649 return log_error_errno(r
, "Failed to replace SHA256SUMS suffix: %m");
654 bool pull_validate_local(const char *name
, PullFlags flags
) {
656 if (FLAGS_SET(flags
, PULL_DIRECT
))
657 return path_is_valid(name
);
659 return hostname_is_valid(name
, 0);
662 int pull_url_needs_checksum(const char *url
) {
663 _cleanup_free_
char *fn
= NULL
;
666 /* Returns true if we need to validate this resource via a hash value. This returns true for all
667 * files — except for gpg signature files and SHA256SUMS files and the like, which are validated with
668 * a validation tool like gpg. */
670 r
= import_url_last_component(url
, &fn
);
671 if (r
== -EADDRNOTAVAIL
) /* no last component? then let's assume it's not a signature/checksum file */
676 return !is_checksum_file(fn
) && !is_signature_file(fn
);