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"
27 #define FILENAME_ESCAPE "/.#\"\'"
28 #define HASH_URL_THRESHOLD_LENGTH (_POSIX_PATH_MAX - 16)
30 int pull_find_old_etags(
32 const char *image_root
,
44 image_root
= "/var/lib/machines";
46 _cleanup_free_
char *escaped_url
= xescape(url
, FILENAME_ESCAPE
);
50 _cleanup_closedir_
DIR *d
= opendir(image_root
);
52 if (errno
== ENOENT
) {
60 _cleanup_strv_free_
char **ans
= NULL
;
62 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
63 _cleanup_free_
char *u
= NULL
;
66 if (de
->d_type
!= DT_UNKNOWN
&&
71 a
= startswith(de
->d_name
, prefix
);
77 a
= startswith(a
, escaped_url
);
81 a
= startswith(a
, ".");
86 b
= endswith(de
->d_name
, suffix
);
90 b
= strchr(de
->d_name
, 0);
95 ssize_t l
= cunescape_length(a
, b
- a
, 0, &u
);
97 assert(l
>= INT8_MIN
);
101 if (!http_etag_is_valid(u
))
104 r
= strv_consume(&ans
, TAKE_PTR(u
));
109 *etags
= TAKE_PTR(ans
);
114 static int hash_url(const char *url
, char **ret
) {
116 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
);
120 h
= siphash24(url
, strlen(url
), k
.bytes
);
121 if (asprintf(ret
, "%"PRIx64
, h
) < 0)
127 int pull_make_path(const char *url
, const char *etag
, const char *image_root
, const char *prefix
, const char *suffix
, char **ret
) {
128 _cleanup_free_
char *escaped_url
= NULL
, *escaped_etag
= NULL
;
135 image_root
= "/var/lib/machines";
137 escaped_url
= xescape(url
, FILENAME_ESCAPE
);
142 escaped_etag
= xescape(etag
, FILENAME_ESCAPE
);
147 path
= strjoin(image_root
, "/", strempty(prefix
), escaped_url
, escaped_etag
? "." : "",
148 strempty(escaped_etag
), strempty(suffix
));
152 /* URLs might make the path longer than the maximum allowed length for a file name.
153 * When that happens, a URL hash is used instead. Paths returned by this function
154 * can be later used with tempfn_random() which adds 16 bytes to the resulting name. */
155 if (strlen(path
) >= HASH_URL_THRESHOLD_LENGTH
) {
156 _cleanup_free_
char *hash
= NULL
;
161 r
= hash_url(url
, &hash
);
165 path
= strjoin(image_root
, "/", strempty(prefix
), hash
, escaped_etag
? "." : "",
166 strempty(escaped_etag
), strempty(suffix
));
175 int pull_make_auxiliary_job(
178 int (*strip_suffixes
)(const char *name
, char **ret
),
182 PullJobOpenDisk on_open_disk
,
183 PullJobFinished on_finished
,
186 _cleanup_free_
char *last_component
= NULL
, *ll
= NULL
, *auxiliary_url
= NULL
;
187 _cleanup_(pull_job_unrefp
) PullJob
*job
= NULL
;
193 assert(strip_suffixes
);
196 r
= import_url_last_component(url
, &last_component
);
200 r
= strip_suffixes(last_component
, &ll
);
204 q
= strjoina(ll
, suffix
);
206 r
= import_url_change_last_component(url
, q
, &auxiliary_url
);
210 r
= pull_job_new(&job
, auxiliary_url
, glue
, userdata
);
214 job
->on_open_disk
= on_open_disk
;
215 job
->on_finished
= on_finished
;
216 job
->compressed_max
= job
->uncompressed_max
= 1ULL * 1024ULL * 1024ULL;
217 job
->calc_checksum
= IN_SET(verify
, IMPORT_VERIFY_CHECKSUM
, IMPORT_VERIFY_SIGNATURE
);
219 *ret
= TAKE_PTR(job
);
223 static bool is_checksum_file(const char *fn
) {
224 /* Returns true if the specified filename refers to a checksum file we grok */
229 return streq(fn
, "SHA256SUMS") || endswith(fn
, ".sha256");
232 static bool is_signature_file(const char *fn
) {
233 /* Returns true if the specified filename refers to a signature file we grok (reminder:
234 * suse-style .sha256 files are inline signed) */
239 return streq(fn
, "SHA256SUMS.gpg") || endswith(fn
, ".sha256");
242 int pull_make_verification_jobs(
243 PullJob
**ret_checksum_job
,
244 PullJob
**ret_signature_job
,
246 const char *checksum
, /* set if literal checksum verification is requested, in which case 'verify' is set to _IMPORT_VERIFY_INVALID */
249 PullJobFinished on_finished
,
252 _cleanup_(pull_job_unrefp
) PullJob
*checksum_job
= NULL
, *signature_job
= NULL
;
253 _cleanup_free_
char *fn
= NULL
;
256 assert(ret_checksum_job
);
257 assert(ret_signature_job
);
258 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
< _IMPORT_VERIFY_MAX
);
259 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
>= 0);
260 assert((verify
< 0) || !checksum
);
264 /* If verification is turned off, or if the checksum to validate is already specified we don't need
265 * to download a checksum file or signature, hence shortcut things */
266 if (verify
== IMPORT_VERIFY_NO
|| checksum
) {
267 *ret_checksum_job
= *ret_signature_job
= NULL
;
271 r
= import_url_last_component(url
, &fn
);
272 if (r
< 0 && r
!= -EADDRNOTAVAIL
) /* EADDRNOTAVAIL means there was no last component, which is OK for
273 * us, we'll just assume it's not a checksum/signature file */
276 /* Acquire the checksum file if verification or signature verification is requested and the main file
277 * to acquire isn't a checksum or signature file anyway */
278 if (verify
!= IMPORT_VERIFY_NO
&& !is_checksum_file(fn
) && !is_signature_file(fn
)) {
279 _cleanup_free_
char *checksum_url
= NULL
;
280 const char *suffixed
= NULL
;
282 /* Queue jobs for the checksum file for the image. */
285 suffixed
= strjoina(fn
, ".sha256"); /* Start with the suse-style checksum (if there's a base filename) */
287 suffixed
= "SHA256SUMS";
289 r
= import_url_change_last_component(url
, suffixed
, &checksum_url
);
293 r
= pull_job_new(&checksum_job
, checksum_url
, glue
, userdata
);
297 checksum_job
->on_finished
= on_finished
;
298 checksum_job
->uncompressed_max
= checksum_job
->compressed_max
= 1ULL * 1024ULL * 1024ULL;
299 checksum_job
->on_not_found
= pull_job_restart_with_sha256sum
; /* if this fails, look for ubuntu-style checksum */
302 if (verify
== IMPORT_VERIFY_SIGNATURE
&& !is_signature_file(fn
)) {
303 _cleanup_free_
char *signature_url
= NULL
;
305 /* Queue job for the SHA256SUMS.gpg file for the image. */
306 r
= import_url_change_last_component(url
, "SHA256SUMS.gpg", &signature_url
);
310 r
= pull_job_new(&signature_job
, signature_url
, glue
, userdata
);
314 signature_job
->on_finished
= on_finished
;
315 signature_job
->uncompressed_max
= signature_job
->compressed_max
= 1ULL * 1024ULL * 1024ULL;
318 *ret_checksum_job
= TAKE_PTR(checksum_job
);
319 *ret_signature_job
= TAKE_PTR(signature_job
);
323 static int verify_one(PullJob
*checksum_job
, PullJob
*job
) {
324 _cleanup_free_
char *fn
= NULL
;
325 const char *line
, *p
;
328 assert(checksum_job
);
333 assert(IN_SET(job
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
));
335 /* Don't verify the checksum if we didn't actually successfully download something new */
336 if (job
->state
!= PULL_JOB_DONE
)
340 if (job
->etag_exists
)
343 assert(job
->calc_checksum
);
344 assert(job
->checksum
);
346 r
= import_url_last_component(job
->url
, &fn
);
348 return log_error_errno(r
, "Failed to extract filename from URL '%s': %m", job
->url
);
350 if (!filename_is_valid(fn
))
351 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
352 "Cannot verify checksum, could not determine server-side file name.");
354 if (is_checksum_file(fn
) || is_signature_file(fn
)) /* We cannot verify checksum files or signature files with a checksum file */
355 return log_error_errno(SYNTHETIC_ERRNO(ELOOP
),
356 "Cannot verify checksum/signature files via themselves.");
358 line
= strjoina(job
->checksum
, " *", fn
, "\n"); /* string for binary mode */
359 p
= memmem_safe(checksum_job
->payload
,
360 checksum_job
->payload_size
,
364 line
= strjoina(job
->checksum
, " ", fn
, "\n"); /* string for text mode */
365 p
= memmem_safe(checksum_job
->payload
,
366 checksum_job
->payload_size
,
371 /* Only counts if found at beginning of a line */
372 if (!p
|| (p
!= (char*) checksum_job
->payload
&& p
[-1] != '\n'))
373 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
374 "DOWNLOAD INVALID: Checksum of %s file did not check out, file has been tampered with.", fn
);
376 log_info("SHA256 checksum of %s is valid.", job
->url
);
380 static int verify_gpg(
381 const void *payload
, size_t payload_size
,
382 const void *signature
, size_t signature_size
) {
384 _cleanup_close_pair_
int gpg_pipe
[2] = { -EBADF
, -EBADF
};
385 char sig_file_path
[] = "/tmp/sigXXXXXX", gpg_home
[] = "/tmp/gpghomeXXXXXX";
386 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
387 bool gpg_home_created
= false;
390 assert(payload
|| payload_size
== 0);
391 assert(signature
|| signature_size
== 0);
393 r
= pipe2(gpg_pipe
, O_CLOEXEC
);
395 return log_error_errno(errno
, "Failed to create pipe for gpg: %m");
397 if (signature_size
> 0) {
398 _cleanup_close_
int sig_file
= -1;
400 sig_file
= mkostemp(sig_file_path
, O_RDWR
);
402 return log_error_errno(errno
, "Failed to create temporary file: %m");
404 r
= loop_write(sig_file
, signature
, signature_size
, false);
406 log_error_errno(r
, "Failed to write to temporary file: %m");
411 if (!mkdtemp(gpg_home
)) {
412 r
= log_error_errno(errno
, "Failed to create temporary home for gpg: %m");
416 gpg_home_created
= true;
418 r
= safe_fork("(gpg)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &pid
);
422 const char *cmd
[] = {
425 "--no-default-keyring",
426 "--no-auto-key-locate",
427 "--no-auto-check-trustdb",
429 "--trust-model=always",
430 NULL
, /* --homedir= */
431 NULL
, /* --keyring= */
433 NULL
, /* signature file */
435 NULL
/* trailing NULL */
437 size_t k
= ELEMENTSOF(cmd
) - 6;
441 gpg_pipe
[1] = safe_close(gpg_pipe
[1]);
443 r
= rearrange_stdio(TAKE_FD(gpg_pipe
[0]), -1, STDERR_FILENO
);
445 log_error_errno(r
, "Failed to rearrange stdin/stdout: %m");
449 (void) rlimit_nofile_safe();
451 cmd
[k
++] = strjoina("--homedir=", gpg_home
);
453 /* We add the user keyring only to the command line arguments, if it's around since gpg fails
455 if (access(USER_KEYRING_PATH
, F_OK
) >= 0)
456 cmd
[k
++] = "--keyring=" USER_KEYRING_PATH
;
458 cmd
[k
++] = "--keyring=" VENDOR_KEYRING_PATH
;
460 cmd
[k
++] = "--verify";
462 cmd
[k
++] = sig_file_path
;
467 execvp("gpg2", (char * const *) cmd
);
468 execvp("gpg", (char * const *) cmd
);
469 log_error_errno(errno
, "Failed to execute gpg: %m");
473 gpg_pipe
[0] = safe_close(gpg_pipe
[0]);
475 r
= loop_write(gpg_pipe
[1], payload
, payload_size
, false);
477 log_error_errno(r
, "Failed to write to pipe: %m");
481 gpg_pipe
[1] = safe_close(gpg_pipe
[1]);
483 r
= wait_for_terminate_and_check("gpg", TAKE_PID(pid
), WAIT_LOG_ABNORMAL
);
486 if (r
!= EXIT_SUCCESS
)
487 r
= log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
488 "DOWNLOAD INVALID: Signature verification failed.");
490 log_info("Signature verification succeeded.");
495 if (signature_size
> 0)
496 (void) unlink(sig_file_path
);
498 if (gpg_home_created
)
499 (void) rm_rf(gpg_home
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
504 int pull_verify(ImportVerify verify
,
505 const char *checksum
, /* Verify with literal checksum */
507 PullJob
*checksum_job
,
508 PullJob
*signature_job
,
509 PullJob
*settings_job
,
510 PullJob
*roothash_job
,
511 PullJob
*roothash_signature_job
,
512 PullJob
*verity_job
) {
514 _cleanup_free_
char *fn
= NULL
;
515 VerificationStyle style
;
519 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
< _IMPORT_VERIFY_MAX
);
520 assert(verify
== _IMPORT_VERIFY_INVALID
|| verify
>= 0);
521 assert((verify
< 0) || !checksum
);
523 assert(main_job
->state
== PULL_JOB_DONE
);
525 if (verify
== IMPORT_VERIFY_NO
) /* verification turned off */
529 /* Verification by literal checksum */
530 assert(!checksum_job
);
531 assert(!signature_job
);
532 assert(!settings_job
);
533 assert(!roothash_job
);
534 assert(!roothash_signature_job
);
537 assert(main_job
->calc_checksum
);
538 assert(main_job
->checksum
);
540 if (!strcaseeq(checksum
, main_job
->checksum
))
541 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
542 "DOWNLOAD INVALID: Checksum of %s file did not check out, file has been tampered with.",
548 r
= import_url_last_component(main_job
->url
, &fn
);
550 return log_error_errno(r
, "Failed to extract filename from URL '%s': %m", main_job
->url
);
552 if (is_signature_file(fn
))
553 return log_error_errno(SYNTHETIC_ERRNO(ELOOP
),
554 "Main download is a signature file, can't verify it.");
556 if (is_checksum_file(fn
)) {
557 log_debug("Main download is a checksum file, can't validate its checksum with itself, skipping.");
558 verify_job
= main_job
;
561 assert(main_job
->calc_checksum
);
562 assert(main_job
->checksum
);
563 assert(checksum_job
);
564 assert(checksum_job
->state
== PULL_JOB_DONE
);
566 if (!checksum_job
->payload
|| checksum_job
->payload_size
<= 0)
567 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
568 "Checksum is empty, cannot verify.");
570 FOREACH_POINTER(j
, main_job
, settings_job
, roothash_job
, roothash_signature_job
, verity_job
) {
571 r
= verify_one(checksum_job
, j
);
576 verify_job
= checksum_job
;
579 if (verify
!= IMPORT_VERIFY_SIGNATURE
)
584 r
= verification_style_from_url(verify_job
->url
, &style
);
586 return log_error_errno(r
, "Failed to determine verification style from URL '%s': %m", verify_job
->url
);
588 if (style
== VERIFICATION_PER_DIRECTORY
) {
589 assert(signature_job
);
590 assert(signature_job
->state
== PULL_JOB_DONE
);
592 if (!signature_job
->payload
|| signature_job
->payload_size
<= 0)
593 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
594 "Signature is empty, cannot verify.");
596 return verify_gpg(verify_job
->payload
, verify_job
->payload_size
, signature_job
->payload
, signature_job
->payload_size
);
598 return verify_gpg(verify_job
->payload
, verify_job
->payload_size
, NULL
, 0);
601 int verification_style_from_url(const char *url
, VerificationStyle
*ret
) {
602 _cleanup_free_
char *last
= NULL
;
608 /* Determines which kind of verification style is appropriate for this url */
610 r
= import_url_last_component(url
, &last
);
614 if (streq(last
, "SHA256SUMS")) {
615 *ret
= VERIFICATION_PER_DIRECTORY
;
619 if (endswith(last
, ".sha256")) {
620 *ret
= VERIFICATION_PER_FILE
;
627 int pull_job_restart_with_sha256sum(PullJob
*j
, char **ret
) {
628 VerificationStyle style
;
633 /* Generic implementation of a PullJobNotFound handler, that restarts the job requesting SHA256SUMS */
635 r
= verification_style_from_url(j
->url
, &style
);
637 return log_error_errno(r
, "Failed to determine verification style of URL '%s': %m", j
->url
);
639 if (style
== VERIFICATION_PER_DIRECTORY
) /* Nothing to do anymore */
642 assert(style
== VERIFICATION_PER_FILE
); /* This must have been .sha256 style URL before */
644 log_debug("Got 404 for %s, now trying to get SHA256SUMS instead.", j
->url
);
646 r
= import_url_change_last_component(j
->url
, "SHA256SUMS", ret
);
648 return log_error_errno(r
, "Failed to replace SHA256SUMS suffix: %m");
653 bool pull_validate_local(const char *name
, PullFlags flags
) {
655 if (FLAGS_SET(flags
, PULL_DIRECT
))
656 return path_is_valid(name
);
658 return hostname_is_valid(name
, 0);
661 int pull_url_needs_checksum(const char *url
) {
662 _cleanup_free_
char *fn
= NULL
;
665 /* Returns true if we need to validate this resource via a hash value. This returns true for all
666 * files — except for gpg signature files and SHA256SUMS files and the like, which are validated with
667 * a validation tool like gpg. */
669 r
= import_url_last_component(url
, &fn
);
670 if (r
== -EADDRNOTAVAIL
) /* no last component? then let's assume it's not a signature/checksum file */
675 return !is_checksum_file(fn
) && !is_signature_file(fn
);