elf: Relocate brk elsewhere for static-PIE ELFs.
diff mbox series

Message ID 20191030104927.6681-1-ruinland@andestech.com
State New
Headers show
  • elf: Relocate brk elsewhere for static-PIE ELFs.
Related show

Commit Message

Ruinland Chuan-Tzu Tsai Oct. 30, 2019, 10:49 a.m. UTC
Previous commits (bbdc607, 7be3cb0) move brk to ELF_ET_DYN_BASE to
mitigate collision between heap and stack during ASLR's randomization
procedure. We found the collision to be not limited to heap and stack
nor ASLR enablement.

During the mapping of static-PIE binaries (ET_DYN, no INTERP) e.g.
glibc's ld.so, elf_map() is used with load_bias being zero, which
makes get_unmapped_area() to return an arbitrary unamapped area.

After mapping the static-PIE binary, set_brk() is called to setup
program break.

Then, arch_setup_additional_pages() carries out its duty to initialize
vDSO pages and get_unmapped_area() is invoked with addr being zero
once again - - in some cases (*), this could make it land right next to
the previously mapped static-PIE program and occupy the space for heap.

If we want to avoid this issue, we need to relocate our heap somewhere
else. Regarding the principle of reusing the code, we simply make
brk's relocating happen no matter ASLR is enabled or not.

* This could be reproduced on qemu-system-riscv64 and I observed this
  issue on my riscv32 platform as well.

Signed-off-by: Ruinland Chuan-Tzu Tsai <ruinland@andestech.com>
 fs/binfmt_elf.c | 23 ++++++++++++-----------
 1 file changed, 12 insertions(+), 11 deletions(-)

diff mbox series

diff --git a/fs/binfmt_elf.c b/fs/binfmt_elf.c
index d4e11b2e04f6..a49eb1ea2c6b 100644
--- a/fs/binfmt_elf.c
+++ b/fs/binfmt_elf.c
@@ -1133,18 +1133,19 @@  static int load_elf_binary(struct linux_binprm *bprm)
 	current->mm->end_data = end_data;
 	current->mm->start_stack = bprm->p;
-	if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) {
-		/*
-		 * For architectures with ELF randomization, when executing
-		 * a loader directly (i.e. no interpreter listed in ELF
-		 * headers), move the brk area out of the mmap region
-		 * (since it grows up, and may collide early with the stack
-		 * growing down), and into the unused ELF_ET_DYN_BASE region.
-		 */
-			current->mm->brk = current->mm->start_brk =
+	/*
+	 * While treating static-PIE, force brk to move to ELF_ET_DYN_BASE
+	 * no matter ASLR is enabled or * not. vDSO may collide with
+	 * heap since both of them call get_unmapped_area() which doesn't
+	 * know about set_brk(), causing vDSO to overlap our heap.
+	 */
+	if (loc->elf_ex.e_type == ET_DYN && !interpreter) {
+		current->mm->brk = current->mm->start_brk =
+	}
+	if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) {
 		current->mm->brk = current->mm->start_brk =
 #ifdef compat_brk_randomized