eBPF-based security platform
upatch: read an artifact into memory rather than map it
Daniel Borkmann9006770d07fb
diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.cindex 2624ef4e..719b5dc0 100644--- a/tools/shirudo-build/package.c+++ b/tools/shirudo-build/package.c@@ -118,9 +118,9 @@ static void pack_header(struct upatch_header *h,}/*- * The inputs stay mapped while the output is written, so an output that- * is one of them, under whatever name, must be refused before it is- * truncated.+ * An output that is one of the inputs, under whatever name, is refused+ * before it is truncated, so that a write that fails cannot take the+ * input with it.*/static bool output_is_input(int fd, const char *original,const char *modified)diff --git a/util/upatch.c b/util/upatch.cindex 6029fd28..9245361d 100644--- a/util/upatch.c+++ b/util/upatch.c@@ -10,7 +10,6 @@#include <stddef.h>#include <stdint.h>#include <string.h>-#include <sys/mman.h>#include <sys/stat.h>#include <unistd.h>@@ -342,10 +341,16 @@ int upatch_open_memory(const void *data, size_t size,return upatch_parse(data, size, out);}+/*+ * A copy, not a mapping: a private mapping still shows what is written to+ * the file after mmap(), so the bytes parsed here, the ones handed to the+ * kernel and the ones acted on after its signature check could differ.+ */int upatch_open_fd(int fd, struct upatch *out){struct stat st;- void *m;+ size_t size, off;+ __u8 *buf;int ret;memset(out, 0, sizeof(*out));@@ -357,17 +362,29 @@ int upatch_open_fd(int fd, struct upatch *out)if ((uintmax_t)st.st_size > UPATCH_FILE_MAX)return -EFBIG;- m = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);- if (m == MAP_FAILED)- return -errno;+ size = (size_t)st.st_size;+ buf = xmalloc(size);+ if (!buf)+ return -ENOMEM;+ for (off = 0; off < size; ) {+ ssize_t n = pread(fd, buf + off, size - off, (off_t)off);- ret = upatch_parse(m, (size_t)st.st_size, out);- if (ret) {- munmap(m, (size_t)st.st_size);- return ret;+ if (n < 0 && errno == EINTR)+ continue;+ if (n <= 0) {+ ret = n < 0 ? -errno : -EIO;+ goto err;+ }+ off += (size_t)n;}- out->mapped = true;+ ret = upatch_parse(buf, size, out);+ if (ret)+ goto err;+ out->owned = true;return 0;+err:+ xfree(buf, size);+ return ret;}int upatch_open(const char *path, struct upatch *out)@@ -385,12 +402,12 @@ int upatch_open(const char *path, struct upatch *out)void upatch_close(struct upatch *u){- if (u->map && u->mapped)- munmap((void *)u->map, u->map_size);+ if (u->map && u->owned)+ xfree((void *)u->map, u->map_size);if (u->map) {u->map = NULL;u->map_size = 0;- u->mapped = false;+ u->owned = false;forget_signed_sections(u);}}diff --git a/util/upatch.h b/util/upatch.hindex 505bd9c9..23f51f4d 100644--- a/util/upatch.h+++ b/util/upatch.h@@ -45,7 +45,7 @@ struct upatch {struct upatch_host_header hdr;const __u8 *map;size_t map_size;- bool mapped;+ bool owned;bool rodata_offset_valid;const struct upatch_decoder_blob *decoder_blob;__u32 decoder_blob_len;