[PATCH 1/2] initramfs: Check negative timestamp to prevent broken cpio archive

From: Benjamin Gray
Date: Mon Mar 20 2023 - 00:09:18 EST


Similar to commit 4c9d410f32b3 ("initramfs: Check timestamp to prevent
broken cpio archive"), except asserts that the timestamp is
non-negative. This can happen when the KBUILD_BUILD_TIMESTAMP is a value
before UNIX epoch, which may be set when making reproducible builds that
don't want to look like they use a valid date.

While support for dates before 1970 might not be supported, this is more
about preventing undetected CPIO corruption. The printf's use a minimum
length format specifier, and will happily make the field longer than 8
characters if they need to.

Signed-off-by: Benjamin Gray <bgray@xxxxxxxxxxxxx>

---

Ran into this when setting KBUILD_BUILD_TIMESTAMP=0000-01-01. The kernel
builds and boots to an initramfs just fine, but inexplicably failed to
load any root disks. It was a pain to debug, because the first sign of
an issue was so deep into the boot sequence.
---
usr/gen_init_cpio.c | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/usr/gen_init_cpio.c b/usr/gen_init_cpio.c
index ee01e40e8bc6..61230532fef1 100644
--- a/usr/gen_init_cpio.c
+++ b/usr/gen_init_cpio.c
@@ -353,6 +353,12 @@ static int cpio_mkfile(const char *name, const char *location,
buf.st_mtime = 0xffffffff;
}

+ if (buf.st_mtime < 0) {
+ fprintf(stderr, "%s: Timestamp negative, clipping.\n",
+ location);
+ buf.st_mtime = 0;
+ }
+
if (buf.st_size > 0xffffffff) {
fprintf(stderr, "%s: Size exceeds maximum cpio file size\n",
location);
@@ -602,10 +608,10 @@ int main (int argc, char *argv[])
/*
* Timestamps after 2106-02-07 06:28:15 UTC have an ascii hex time_t
* representation that exceeds 8 chars and breaks the cpio header
- * specification.
+ * specification. Negative timestamps similarly exceed 8 chars.
*/
- if (default_mtime > 0xffffffff) {
- fprintf(stderr, "ERROR: Timestamp too large for cpio format\n");
+ if (default_mtime > 0xffffffff || default_mtime < 0) {
+ fprintf(stderr, "ERROR: Timestamp out of range for cpio format\n");
exit(1);
}


base-commit: 065ffaee73892e8a3629b4cfbe635697807a3c6f
--
2.39.2