From patchwork Thu Dec 2 22:32:01 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653699 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id B8944C4321E for ; Thu, 2 Dec 2021 22:33:01 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S243772AbhLBWgX (ORCPT ); Thu, 2 Dec 2021 17:36:23 -0500 Received: from mga04.intel.com ([192.55.52.120]:50399 "EHLO mga04.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S238812AbhLBWgX (ORCPT ); Thu, 2 Dec 2021 17:36:23 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="235592792" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="235592792" Received: from fmsmga004.fm.intel.com ([10.253.24.48]) by fmsmga104.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:00 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="576948096" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga004.fm.intel.com with ESMTP; 02 Dec 2021 14:32:52 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYS028552; Thu, 2 Dec 2021 22:32:50 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 01/14] x86: Makefile: Add build and config option for CONFIG_FG_KASLR Date: Thu, 2 Dec 2021 23:32:01 +0100 Message-Id: <20211202223214.72888-2-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi Allow user to select CONFIG_FG_KASLR if dependencies are met. Change the make file to build with -ffunction-sections if CONFIG_FG_KASLR. While the only architecture that supports CONFIG_FG_KASLR does not currently enable HAVE_LD_DEAD_CODE_DATA_ELIMINATION, make sure these 2 features play nicely together for the future by ensuring that if CONFIG_LD_DEAD_CODE_DATA_ELIMINATION is selected when used with CONFIG_FG_KASLR the function sections will not be consolidated back into .text. Thanks to Kees Cook for the dead code elimination changes. Signed-off-by: Kristen Carlson Accardi Reviewed-by: Tony Luck Reviewed-by: Kees Cook Tested-by: Tony Luck [ alobakin: - improve cflags management in the top Makefile - move ARCH_HAS_FG_KASLR to the top arch/Kconfig - add symtab_shndx to the list of known sections ] Signed-off-by: Alexander Lobakin --- Makefile | 13 ++++++++++++- arch/Kconfig | 3 +++ include/asm-generic/vmlinux.lds.h | 20 ++++++++++++++++++-- init/Kconfig | 12 ++++++++++++ 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 0a6ecc8bb2d2..a4d2eac5f81f 100644 --- a/Makefile +++ b/Makefile @@ -882,8 +882,19 @@ ifdef CONFIG_DEBUG_SECTION_MISMATCH KBUILD_CFLAGS += -fno-inline-functions-called-once endif +# ClangLTO implies -ffunction-sections -fdata-sections, no need +# to specify them manually and trigger a pointless full rebuild +ifndef CONFIG_LTO_CLANG +ifneq ($(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION)$(CONFIG_FG_KASLR),) +KBUILD_CFLAGS_KERNEL += -ffunction-sections +endif + +ifdef CONFIG_LD_DEAD_CODE_DATA_ELIMINATION +KBUILD_CFLAGS_KERNEL += -fdata-sections +endif +endif # CONFIG_LTO_CLANG + ifdef CONFIG_LD_DEAD_CODE_DATA_ELIMINATION -KBUILD_CFLAGS_KERNEL += -ffunction-sections -fdata-sections LDFLAGS_vmlinux += --gc-sections endif diff --git a/arch/Kconfig b/arch/Kconfig index d3c4ab249e9c..602b67162e53 100644 --- a/arch/Kconfig +++ b/arch/Kconfig @@ -1312,6 +1312,9 @@ config ARCH_HAS_PARANOID_L1D_FLUSH config DYNAMIC_SIGFRAME bool +config ARCH_HAS_FG_KASLR + bool + source "kernel/gcov/Kconfig" source "scripts/gcc-plugins/Kconfig" diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h index 42f3866bca69..96fbedcbf7c8 100644 --- a/include/asm-generic/vmlinux.lds.h +++ b/include/asm-generic/vmlinux.lds.h @@ -97,14 +97,12 @@ * sections to be brought in with rodata. */ #if defined(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION) || defined(CONFIG_LTO_CLANG) -#define TEXT_MAIN .text .text.[0-9a-zA-Z_]* #define DATA_MAIN .data .data.[0-9a-zA-Z_]* .data..L* .data..compoundliteral* .data.$__unnamed_* .data.$L* #define SDATA_MAIN .sdata .sdata.[0-9a-zA-Z_]* #define RODATA_MAIN .rodata .rodata.[0-9a-zA-Z_]* .rodata..L* #define BSS_MAIN .bss .bss.[0-9a-zA-Z_]* .bss..compoundliteral* #define SBSS_MAIN .sbss .sbss.[0-9a-zA-Z_]* #else -#define TEXT_MAIN .text #define DATA_MAIN .data #define SDATA_MAIN .sdata #define RODATA_MAIN .rodata @@ -112,6 +110,23 @@ #define SBSS_MAIN .sbss #endif +/* + * LTO_CLANG, LD_DEAD_CODE_DATA_ELIMINATION and FG_KASLR options enable + * -ffunction-sections, which produces separately named .text sections. In + * the case of CONFIG_FG_KASLR, they need to stay distict so they can be + * separately randomized. Without CONFIG_FG_KASLR, the separate .text + * sections can be collected back into a common section, which makes the + * resulting image slightly smaller + */ +#if (defined(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION) || \ + defined(CONFIG_LTO_CLANG)) && !defined(CONFIG_FG_KASLR) +#define TEXT_MAIN .text .text.[0-9a-zA-Z_]* +#elif defined(CONFIG_FG_KASLR) +#define TEXT_MAIN .text.__unused__ +#else +#define TEXT_MAIN .text +#endif + /* * GCC 4.5 and later have a 32 bytes section alignment for structures. * Except GCC 4.9, that feels the need to align on 64 bytes. @@ -840,6 +855,7 @@ #define ELF_DETAILS \ .comment 0 : { *(.comment) } \ .symtab 0 : { *(.symtab) } \ + .symtab_shndx 0 : { *(.symtab_shndx) } \ .strtab 0 : { *(.strtab) } \ .shstrtab 0 : { *(.shstrtab) } diff --git a/init/Kconfig b/init/Kconfig index 4b7bac10c72d..5cb8f8230915 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -2051,6 +2051,18 @@ config PROFILING config TRACEPOINTS bool +config FG_KASLR + bool "Function Granular Kernel Address Space Layout Randomization" + depends on ARCH_HAS_FG_KASLR + help + This option improves the randomness of the kernel text + over basic Kernel Address Space Layout Randomization (KASLR) + by reordering the kernel text at boot time. This feature + uses information generated at compile time to re-layout the + kernel text section at boot time at function level granularity. + + If unsure, say N. + endmenu # General setup source "arch/Kconfig" From patchwork Thu Dec 2 22:32:02 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653703 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 53B42C433FE for ; Thu, 2 Dec 2021 22:33:16 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1349452AbhLBWgi (ORCPT ); Thu, 2 Dec 2021 17:36:38 -0500 Received: from mga05.intel.com ([192.55.52.43]:15443 "EHLO mga05.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S244201AbhLBWg1 (ORCPT ); Thu, 2 Dec 2021 17:36:27 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="323108310" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="323108310" Received: from orsmga007.jf.intel.com ([10.7.209.58]) by fmsmga105.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:02 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="500939454" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga007.jf.intel.com with ESMTP; 02 Dec 2021 14:32:54 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYT028552; Thu, 2 Dec 2021 22:32:52 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 02/14] x86/tools: Add relative relocs for randomized functions Date: Thu, 2 Dec 2021 23:32:02 +0100 Message-Id: <20211202223214.72888-3-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi When reordering functions, the relative offsets for relocs that are either in the randomized sections, or refer to the randomized sections will need to be adjusted. Add code to detect whether a reloc satisfies these cases, and if so, add them to the appropriate reloc list. Signed-off-by: Kristen Carlson Accardi Reviewed-by: Tony Luck Tested-by: Tony Luck Reviewed-by: Kees Cook [ alobakin: don't split relocs' usage string across lines ] Signed-off-by: Alexander Lobakin --- arch/x86/boot/compressed/Makefile | 7 ++++++- arch/x86/tools/relocs.c | 32 +++++++++++++++++++++++++++---- arch/x86/tools/relocs.h | 4 ++-- arch/x86/tools/relocs_common.c | 14 +++++++++----- 4 files changed, 45 insertions(+), 12 deletions(-) diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile index 431bf7f846c3..c31a24161fbf 100644 --- a/arch/x86/boot/compressed/Makefile +++ b/arch/x86/boot/compressed/Makefile @@ -106,6 +106,11 @@ $(obj)/vmlinux: $(vmlinux-objs-y) $(efi-obj-y) FORCE $(call if_changed,ld) OBJCOPYFLAGS_vmlinux.bin := -R .comment -S + +ifdef CONFIG_FG_KASLR +RELOCS_ARGS += --fg-kaslr +endif + $(obj)/vmlinux.bin: vmlinux FORCE $(call if_changed,objcopy) @@ -113,7 +118,7 @@ targets += $(patsubst $(obj)/%,%,$(vmlinux-objs-y)) vmlinux.bin.all vmlinux.relo CMD_RELOCS = arch/x86/tools/relocs quiet_cmd_relocs = RELOCS $@ - cmd_relocs = $(CMD_RELOCS) $< > $@;$(CMD_RELOCS) --abs-relocs $< + cmd_relocs = $(CMD_RELOCS) $(RELOCS_ARGS) $< > $@;$(CMD_RELOCS) $(RELOCS_ARGS) --abs-relocs $< $(obj)/vmlinux.relocs: vmlinux FORCE $(call if_changed,relocs) diff --git a/arch/x86/tools/relocs.c b/arch/x86/tools/relocs.c index c736cf2ac76b..8aa1f39be561 100644 --- a/arch/x86/tools/relocs.c +++ b/arch/x86/tools/relocs.c @@ -45,6 +45,8 @@ struct section { }; static struct section *secs; +static int fgkaslr_mode; + static const char * const sym_regex_kernel[S_NSYMTYPES] = { /* * Following symbols have been audited. There values are constant and do @@ -823,6 +825,24 @@ static int is_percpu_sym(ElfW(Sym) *sym, const char *symname) strncmp(symname, "init_per_cpu_", 13); } +static int is_function_section(struct section *sec) +{ + if (!fgkaslr_mode) + return 0; + + return !strncmp(sec_name(sec->shdr.sh_info), ".text.", 6); +} + +static int is_randomized_sym(ElfW(Sym) *sym) +{ + if (!fgkaslr_mode) + return 0; + + if (sym->st_shndx > shnum) + return 0; + + return !strncmp(sec_name(sym_index(sym)), ".text.", 6); +} static int do_reloc64(struct section *sec, Elf_Rel *rel, ElfW(Sym) *sym, const char *symname) @@ -848,12 +868,15 @@ static int do_reloc64(struct section *sec, Elf_Rel *rel, ElfW(Sym) *sym, case R_X86_64_PC32: case R_X86_64_PLT32: /* - * PC relative relocations don't need to be adjusted unless - * referencing a percpu symbol. + * we need to keep pc relative relocations for sections which + * might be randomized, and for the percpu section. + * We also need to keep relocations for any offset which might + * reference an address in a section which has been randomized. * * NB: R_X86_64_PLT32 can be treated as R_X86_64_PC32. */ - if (is_percpu_sym(sym, symname)) + if (is_function_section(sec) || is_randomized_sym(sym) || + is_percpu_sym(sym, symname)) add_reloc(&relocs32neg, offset); break; @@ -1168,8 +1191,9 @@ static void print_reloc_info(void) void process(FILE *fp, int use_real_mode, int as_text, int show_absolute_syms, int show_absolute_relocs, - int show_reloc_info) + int show_reloc_info, int fgkaslr) { + fgkaslr_mode = fgkaslr; regex_init(use_real_mode); read_ehdr(fp); read_shdrs(fp); diff --git a/arch/x86/tools/relocs.h b/arch/x86/tools/relocs.h index 4c49c82446eb..269db511b243 100644 --- a/arch/x86/tools/relocs.h +++ b/arch/x86/tools/relocs.h @@ -32,8 +32,8 @@ enum symtype { void process_32(FILE *fp, int use_real_mode, int as_text, int show_absolute_syms, int show_absolute_relocs, - int show_reloc_info); + int show_reloc_info, int fgkaslr); void process_64(FILE *fp, int use_real_mode, int as_text, int show_absolute_syms, int show_absolute_relocs, - int show_reloc_info); + int show_reloc_info, int fgkaslr); #endif /* RELOCS_H */ diff --git a/arch/x86/tools/relocs_common.c b/arch/x86/tools/relocs_common.c index 6634352a20bc..d6acda36575a 100644 --- a/arch/x86/tools/relocs_common.c +++ b/arch/x86/tools/relocs_common.c @@ -12,14 +12,13 @@ void die(char *fmt, ...) static void usage(void) { - die("relocs [--abs-syms|--abs-relocs|--reloc-info|--text|--realmode]" \ - " vmlinux\n"); + die("relocs [--abs-syms|--abs-relocs|--reloc-info|--text|--realmode|--fg-kaslr] vmlinux\n"); } int main(int argc, char **argv) { int show_absolute_syms, show_absolute_relocs, show_reloc_info; - int as_text, use_real_mode; + int as_text, use_real_mode, fgkaslr_opt; const char *fname; FILE *fp; int i; @@ -30,6 +29,7 @@ int main(int argc, char **argv) show_reloc_info = 0; as_text = 0; use_real_mode = 0; + fgkaslr_opt = 0; fname = NULL; for (i = 1; i < argc; i++) { char *arg = argv[i]; @@ -54,6 +54,10 @@ int main(int argc, char **argv) use_real_mode = 1; continue; } + if (strcmp(arg, "--fg-kaslr") == 0) { + fgkaslr_opt = 1; + continue; + } } else if (!fname) { fname = arg; @@ -75,11 +79,11 @@ int main(int argc, char **argv) if (e_ident[EI_CLASS] == ELFCLASS64) process_64(fp, use_real_mode, as_text, show_absolute_syms, show_absolute_relocs, - show_reloc_info); + show_reloc_info, fgkaslr_opt); else process_32(fp, use_real_mode, as_text, show_absolute_syms, show_absolute_relocs, - show_reloc_info); + show_reloc_info, fgkaslr_opt); fclose(fp); return 0; } From patchwork Thu Dec 2 22:32:03 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653705 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id F0CE2C43217 for ; Thu, 2 Dec 2021 22:33:17 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1349526AbhLBWgj (ORCPT ); Thu, 2 Dec 2021 17:36:39 -0500 Received: from mga12.intel.com ([192.55.52.136]:32073 "EHLO mga12.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S244743AbhLBWg3 (ORCPT ); Thu, 2 Dec 2021 17:36:29 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="216877401" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="216877401" Received: from orsmga001.jf.intel.com ([10.7.209.18]) by fmsmga106.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:05 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="541402355" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga001.jf.intel.com with ESMTP; 02 Dec 2021 14:32:56 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYU028552; Thu, 2 Dec 2021 22:32:54 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 03/14] x86: Add support for function granular KASLR Date: Thu, 2 Dec 2021 23:32:03 +0100 Message-Id: <20211202223214.72888-4-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi This commit contains the changes required to re-layout the kernel text sections generated by -ffunction-sections shortly after decompression. Documentation of the feature is also added. After decompression, the decompressed image's elf headers are parsed. In order to manually update certain data structures that are built with relative offsets during the kernel build process, certain symbols are not stripped by objdump and their location is retained in the elf symbol tables. These addresses are saved. If the image was built with -ffunction-sections, there will be ELF section headers present which contain information about the address range of each section. Anything that is not broken out into function sections (i.e. is consolidated into .text) is left in it's original location, but any other executable section which begins with ".text." is located and shuffled randomly within the remaining text segment address range. After the sections have been copied to their new locations, but before relocations have been applied, the kallsyms tables must be updated to reflect the new symbol locations. Because it is expected that these tables will be sorted by address, the kallsyms tables will need to be sorted after the update. When applying relocations, the address of the relocation needs to be adjusted by the offset from the original location of the section that was randomized to it's new location. In addition, if a value at that relocation was a location in the text segment that was randomized, it's value will be adjusted to a new location. After relocations have been applied, the exception table must be updated with new symbol locations, and then re-sorted by the new address. The orc table will have been updated as part of applying relocations, but since it is expected to be sorted by address, it will need to be resorted. Signed-off-by: Kristen Carlson Accardi Reviewed-by: Tony Luck Tested-by: Tony Luck Reviewed-by: Kees Cook Reported-by: kernel test robot # #if -> #ifdef [ alobakin: fix .altinstr_replacement relocations ] Signed-off-by: Alexander Lobakin --- arch/x86/boot/compressed/Makefile | 2 + arch/x86/boot/compressed/fgkaslr.c | 893 +++++++++++++++++++++++ arch/x86/boot/compressed/misc.c | 154 +++- arch/x86/boot/compressed/misc.h | 28 + arch/x86/boot/compressed/utils.c | 13 + arch/x86/boot/compressed/vmlinux.symbols | 19 + arch/x86/include/asm/boot.h | 13 +- arch/x86/kernel/vmlinux.lds.S | 2 + include/uapi/linux/elf.h | 1 + 9 files changed, 1098 insertions(+), 27 deletions(-) create mode 100644 arch/x86/boot/compressed/fgkaslr.c create mode 100644 arch/x86/boot/compressed/utils.c create mode 100644 arch/x86/boot/compressed/vmlinux.symbols diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile index c31a24161fbf..e12fb0c8f4fc 100644 --- a/arch/x86/boot/compressed/Makefile +++ b/arch/x86/boot/compressed/Makefile @@ -89,6 +89,7 @@ vmlinux-objs-y := $(obj)/vmlinux.lds $(obj)/kernel_info.o $(obj)/head_$(BITS).o vmlinux-objs-$(CONFIG_EARLY_PRINTK) += $(obj)/early_serial_console.o vmlinux-objs-$(CONFIG_RANDOMIZE_BASE) += $(obj)/kaslr.o +vmlinux-objs-$(CONFIG_FG_KASLR) += $(obj)/fgkaslr.o $(obj)/utils.o ifdef CONFIG_X86_64 vmlinux-objs-y += $(obj)/ident_map_64.o vmlinux-objs-y += $(obj)/idt_64.o $(obj)/idt_handlers_64.o @@ -108,6 +109,7 @@ $(obj)/vmlinux: $(vmlinux-objs-y) $(efi-obj-y) FORCE OBJCOPYFLAGS_vmlinux.bin := -R .comment -S ifdef CONFIG_FG_KASLR +OBJCOPYFLAGS += --keep-symbols=$(srctree)/$(src)/vmlinux.symbols RELOCS_ARGS += --fg-kaslr endif diff --git a/arch/x86/boot/compressed/fgkaslr.c b/arch/x86/boot/compressed/fgkaslr.c new file mode 100644 index 000000000000..265630266f46 --- /dev/null +++ b/arch/x86/boot/compressed/fgkaslr.c @@ -0,0 +1,893 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * This contains the routines needed to reorder the kernel text section + * at boot time. + * + * Copyright (C) 2020-2021, Intel Corporation. + * Author: Kristen Carlson Accardi + */ + +#include "misc.h" +#include "error.h" +#include "pgtable.h" +#include "../string.h" +#include "../voffset.h" +#include +#include +#include "../../include/asm/extable.h" +#include "../../include/asm/orc_types.h" + +/* + * Longest parameter of 'fgkaslr=' is 'off' right now, plus an extra '\0' + * for termination. + */ +#define MAX_FGKASLR_ARG_LENGTH 4 +static int nofgkaslr; + +/* + * Use normal definitions of mem*() from string.c. There are already + * included header files which expect a definition of memset() and by + * the time we define memset macro, it is too late. + */ +#undef memcpy +#undef memset +#define memzero(s, n) memset((s), 0, (n)) +#define memmove memmove + +void *memmove(void *dest, const void *src, size_t n); + +static unsigned long percpu_start; +static unsigned long percpu_end; + +static long addr_kallsyms_names; +static long addr_kallsyms_offsets; +static long addr_kallsyms_num_syms; +static long addr_kallsyms_relative_base; +static long addr_kallsyms_markers; +static long addr___start___ex_table; +static long addr___stop___ex_table; +static long addr___altinstr_replacement; +static long addr___altinstr_replacement_end; +static long addr__stext; +static long addr__etext; +static long addr__sinittext; +static long addr__einittext; +static long addr___start_orc_unwind_ip; +static long addr___stop_orc_unwind_ip; +static long addr___start_orc_unwind; + +/* addresses in mapped address space */ +static int *base; +static u8 *names; +static unsigned long relative_base; +static unsigned int *markers_addr; + +struct kallsyms_name { + u8 len; + u8 indecis[256]; +}; + +static struct kallsyms_name *names_table; + +static struct orc_entry *cur_orc_table; +static int *cur_orc_ip_table; + +/* Array of pointers to sections headers for randomized sections */ +Elf_Shdr **sections; + +/* Number of elements in the randomized section header array (sections) */ +static int sections_size; + +/* Array of all section headers, randomized or otherwise */ +static Elf_Shdr *sechdrs; + +static bool is_orc_unwind(long addr) +{ + if (addr >= addr___start_orc_unwind_ip && + addr < addr___stop_orc_unwind_ip) + return true; + return false; +} + +static bool is_text(long addr) +{ + if ((addr >= addr__stext && addr < addr__etext) || + (addr >= addr__sinittext && addr < addr__einittext) || + (addr >= addr___altinstr_replacement && + addr <= addr___altinstr_replacement_end)) + return true; + return false; +} + +bool is_percpu_addr(long pc, long offset) +{ + unsigned long ptr; + long address; + + address = pc + offset + 4; + + ptr = (unsigned long)address; + + if (ptr >= percpu_start && ptr < percpu_end) + return true; + + return false; +} + +static int cmp_section_addr(const void *a, const void *b) +{ + unsigned long ptr = (unsigned long)a; + Elf_Shdr *s = *(Elf_Shdr **)b; + unsigned long end = s->sh_addr + s->sh_size; + + if (ptr >= s->sh_addr && ptr < end) + return 0; + + if (ptr < s->sh_addr) + return -1; + + return 1; +} + +static int cmp_section_addr_orc(const void *a, const void *b) +{ + unsigned long ptr = (unsigned long)a; + Elf_Shdr *s = *(Elf_Shdr **)b; + unsigned long end = s->sh_addr + s->sh_size; + + /* orc relocations can be one past the end of the section */ + if (ptr >= s->sh_addr && ptr <= end) + return 0; + + if (ptr < s->sh_addr) + return -1; + + return 1; +} + +/* + * Discover if the orc_unwind address is in a randomized section and if so, + * adjust by the saved offset. + */ +Elf_Shdr *adjust_address_orc(long *address) +{ + Elf_Shdr **s; + Elf_Shdr *shdr; + + if (nofgkaslr) + return NULL; + + s = bsearch((const void *)*address, sections, sections_size, sizeof(*s), + cmp_section_addr_orc); + if (s) { + shdr = *s; + *address += shdr->sh_offset; + return shdr; + } + + return NULL; +} + +/* + * Discover if the address is in a randomized section and if so, adjust + * by the saved offset. + */ +Elf_Shdr *adjust_address(long *address) +{ + Elf_Shdr **s; + Elf_Shdr *shdr; + + if (nofgkaslr) + return NULL; + + s = bsearch((const void *)*address, sections, sections_size, sizeof(*s), + cmp_section_addr); + if (s) { + shdr = *s; + *address += shdr->sh_offset; + return shdr; + } + + return NULL; +} + +void adjust_relative_offset(long pc, long *value, Elf_Shdr *section) +{ + Elf_Shdr *s; + long address; + + if (nofgkaslr) + return; + + /* + * sometimes we are updating a relative offset that would + * normally be relative to the next instruction (such as a call). + * In this case to calculate the target, you need to add 32bits to + * the pc to get the next instruction value. However, sometimes + * targets are just data that was stored in a table such as ksymtab + * or cpu alternatives. In this case our target is not relative to + * the next instruction. + */ + + /* Calculate the address that this offset would call. */ + if (!is_text(pc)) + address = pc + *value; + else + address = pc + *value + 4; + + /* + * orc ip addresses are sorted at build time after relocs have + * been applied, making the relocs no longer valid. Skip any + * relocs for the orc_unwind_ip table. These will be updated + * separately. + */ + if (is_orc_unwind(pc)) + return; + + s = adjust_address(&address); + + /* + * if the address is in section that was randomized, + * we need to adjust the offset. + */ + if (s) + *value += s->sh_offset; + + /* + * If the PC that this offset was calculated for was in a section + * that has been randomized, the value needs to be adjusted by the + * same amount as the randomized section was adjusted from it's original + * location. + */ + if (section) + *value -= section->sh_offset; +} + +static void kallsyms_swp(void *a, void *b, int size) +{ + int idx1, idx2; + int temp; + struct kallsyms_name name_a; + + /* Determine our index into the array. */ + idx1 = (int *)a - base; + idx2 = (int *)b - base; + temp = base[idx1]; + base[idx1] = base[idx2]; + base[idx2] = temp; + + /* Swap the names table. */ + memcpy(&name_a, &names_table[idx1], sizeof(name_a)); + memcpy(&names_table[idx1], &names_table[idx2], + sizeof(struct kallsyms_name)); + memcpy(&names_table[idx2], &name_a, sizeof(struct kallsyms_name)); +} + +static int kallsyms_cmp(const void *a, const void *b) +{ + int addr_a, addr_b; + unsigned long uaddr_a, uaddr_b; + + addr_a = *(int *)a; + addr_b = *(int *)b; + + if (addr_a >= 0) + uaddr_a = addr_a; + if (addr_b >= 0) + uaddr_b = addr_b; + + if (addr_a < 0) + uaddr_a = relative_base - 1 - addr_a; + if (addr_b < 0) + uaddr_b = relative_base - 1 - addr_b; + + if (uaddr_b > uaddr_a) + return -1; + + return 0; +} + +static void deal_with_names(int num_syms) +{ + int num_bytes; + int i, j; + int offset; + + /* we should have num_syms kallsyms_name entries */ + num_bytes = num_syms * sizeof(*names_table); + names_table = malloc(num_syms * sizeof(*names_table)); + if (!names_table) { + debug_putstr("\nbytes requested: "); + debug_puthex(num_bytes); + error("\nunable to allocate space for names table\n"); + } + + /* read all the names entries */ + offset = 0; + for (i = 0; i < num_syms; i++) { + names_table[i].len = names[offset]; + offset++; + for (j = 0; j < names_table[i].len; j++) { + names_table[i].indecis[j] = names[offset]; + offset++; + } + } +} + +static void write_sorted_names(int num_syms) +{ + int i, j; + int offset = 0; + unsigned int *markers; + + /* + * we are going to need to regenerate the markers table, which is a + * table of offsets into the compressed stream every 256 symbols. + * this code copied almost directly from scripts/kallsyms.c + */ + markers = malloc(sizeof(unsigned int) * ((num_syms + 255) / 256)); + if (!markers) { + debug_putstr("\nfailed to allocate heap space of "); + debug_puthex(((num_syms + 255) / 256)); + debug_putstr(" bytes\n"); + error("Unable to allocate space for markers table"); + } + + for (i = 0; i < num_syms; i++) { + if ((i & 0xFF) == 0) + markers[i >> 8] = offset; + + names[offset] = (u8)names_table[i].len; + offset++; + for (j = 0; j < names_table[i].len; j++) { + names[offset] = (u8)names_table[i].indecis[j]; + offset++; + } + } + + /* write new markers table over old one */ + for (i = 0; i < ((num_syms + 255) >> 8); i++) + markers_addr[i] = markers[i]; + + free(markers); + free(names_table); +} + +static void sort_kallsyms(unsigned long map) +{ + int num_syms; + int i; + + debug_putstr("\nRe-sorting kallsyms...\n"); + + num_syms = *(int *)(addr_kallsyms_num_syms + map); + base = (int *)(addr_kallsyms_offsets + map); + relative_base = *(unsigned long *)(addr_kallsyms_relative_base + map); + markers_addr = (unsigned int *)(addr_kallsyms_markers + map); + names = (u8 *)(addr_kallsyms_names + map); + + /* + * the kallsyms table was generated prior to any randomization. + * it is a bunch of offsets from "relative base". In order for + * us to check if a symbol has an address that was in a randomized + * section, we need to reconstruct the address to it's original + * value prior to handle_relocations. + */ + for (i = 0; i < num_syms; i++) { + unsigned long addr; + int new_base; + + /* + * according to kernel/kallsyms.c, positive offsets are absolute + * values and negative offsets are relative to the base. + */ + if (base[i] >= 0) + addr = base[i]; + else + addr = relative_base - 1 - base[i]; + + if (adjust_address(&addr)) { + /* here we need to recalcuate the offset */ + new_base = relative_base - 1 - addr; + base[i] = new_base; + } + } + + /* + * here we need to read in all the kallsyms_names info + * so that we can regenerate it. + */ + deal_with_names(num_syms); + + sort(base, num_syms, sizeof(int), kallsyms_cmp, kallsyms_swp); + + /* write the newly sorted names table over the old one */ + write_sorted_names(num_syms); +} + +/* + * We need to include this file here rather than in utils.c because + * some of the helper functions in extable.c are used to update + * the extable below and are defined as "static" in extable.c + */ +#include "../../../../lib/extable.c" + +static inline unsigned long +ex_fixup_addr(const struct exception_table_entry *x) +{ + return ((unsigned long)&x->fixup + x->fixup); +} + +static void update_ex_table(unsigned long map) +{ + struct exception_table_entry *start_ex_table = + (struct exception_table_entry *)(addr___start___ex_table + map); + struct exception_table_entry *stop_ex_table = + (struct exception_table_entry *)(addr___stop___ex_table + map); + int num_entries = + (addr___stop___ex_table - addr___start___ex_table) / + sizeof(struct exception_table_entry); + int i; + + debug_putstr("\nUpdating exception table..."); + for (i = 0; i < num_entries; i++) { + unsigned long insn = ex_to_insn(&start_ex_table[i]); + unsigned long fixup = ex_fixup_addr(&start_ex_table[i]); + unsigned long addr; + Elf_Shdr *s; + + /* check each address to see if it needs adjusting */ + addr = insn - map; + s = adjust_address(&addr); + if (s) + start_ex_table[i].insn += s->sh_offset; + + addr = fixup - map; + s = adjust_address(&addr); + if (s) + start_ex_table[i].fixup += s->sh_offset; + } +} + +static void sort_ex_table(unsigned long map) +{ + struct exception_table_entry *start_ex_table = + (struct exception_table_entry *)(addr___start___ex_table + map); + struct exception_table_entry *stop_ex_table = + (struct exception_table_entry *)(addr___stop___ex_table + map); + + debug_putstr("\nRe-sorting exception table..."); + + sort_extable(start_ex_table, stop_ex_table); +} + +static inline unsigned long orc_ip(const int *ip) +{ + return (unsigned long)ip + *ip; +} + +static void orc_sort_swap(void *_a, void *_b, int size) +{ + struct orc_entry *orc_a, *orc_b; + struct orc_entry orc_tmp; + int *a = _a, *b = _b, tmp; + int delta = _b - _a; + + /* Swap the .orc_unwind_ip entries: */ + tmp = *a; + *a = *b + delta; + *b = tmp - delta; + + /* Swap the corresponding .orc_unwind entries: */ + orc_a = cur_orc_table + (a - cur_orc_ip_table); + orc_b = cur_orc_table + (b - cur_orc_ip_table); + orc_tmp = *orc_a; + *orc_a = *orc_b; + *orc_b = orc_tmp; +} + +static int orc_sort_cmp(const void *_a, const void *_b) +{ + struct orc_entry *orc_a; + const int *a = _a, *b = _b; + unsigned long a_val = orc_ip(a); + unsigned long b_val = orc_ip(b); + + if (a_val > b_val) + return 1; + if (a_val < b_val) + return -1; + + /* + * The "weak" section terminator entries need to always be on the left + * to ensure the lookup code skips them in favor of real entries. + * These terminator entries exist to handle any gaps created by + * whitelisted .o files which didn't get objtool generation. + */ + orc_a = cur_orc_table + (a - cur_orc_ip_table); + return orc_a->sp_reg == ORC_REG_UNDEFINED && !orc_a->end ? -1 : 1; +} + +static void update_orc_table(unsigned long map) +{ + int i; + int num_entries = + (addr___stop_orc_unwind_ip - addr___start_orc_unwind_ip) / sizeof(int); + + cur_orc_ip_table = (int *)(addr___start_orc_unwind_ip + map); + cur_orc_table = (struct orc_entry *)(addr___start_orc_unwind + map); + + debug_putstr("\nUpdating orc tables...\n"); + for (i = 0; i < num_entries; i++) { + unsigned long ip = orc_ip(&cur_orc_ip_table[i]); + Elf_Shdr *s; + + /* check each address to see if it needs adjusting */ + ip = ip - map; + + /* + * objtool places terminator entries just outside the end of + * the section. To identify an orc_unwind_ip address that might + * need adjusting, the address should be compared differently + * than a normal address. + */ + s = adjust_address_orc(&ip); + if (s) + cur_orc_ip_table[i] += s->sh_offset; + } +} + +static void sort_orc_table(unsigned long map) +{ + int num_entries = + (addr___stop_orc_unwind_ip - addr___start_orc_unwind_ip) / sizeof(int); + + cur_orc_ip_table = (int *)(addr___start_orc_unwind_ip + map); + cur_orc_table = (struct orc_entry *)(addr___start_orc_unwind + map); + + debug_putstr("\nRe-sorting orc tables...\n"); + sort(cur_orc_ip_table, num_entries, sizeof(int), orc_sort_cmp, + orc_sort_swap); +} + +void post_relocations_cleanup(unsigned long map) +{ + if (!nofgkaslr) { + update_ex_table(map); + sort_ex_table(map); + update_orc_table(map); + sort_orc_table(map); + } + + /* + * maybe one day free will do something. So, we "free" this memory + * in either case + */ + free(sections); + free(sechdrs); +} + +void pre_relocations_cleanup(unsigned long map) +{ + if (nofgkaslr) + return; + + sort_kallsyms(map); +} + +static void shuffle_sections(int *list, int size) +{ + int i; + unsigned long j; + int temp; + + for (i = size - 1; i > 0; i--) { + j = kaslr_get_random_long(NULL) % (i + 1); + + temp = list[i]; + list[i] = list[j]; + list[j] = temp; + } +} + +static void move_text(int num_sections, char *secstrings, Elf_Shdr *text, + void *source, void *dest, Elf64_Phdr *phdr) +{ + unsigned long adjusted_addr; + int copy_bytes; + void *stash; + Elf_Shdr **sorted_sections; + int *index_list; + int i, j; + + memmove(dest, source + text->sh_offset, text->sh_size); + copy_bytes = text->sh_size; + dest += text->sh_size; + adjusted_addr = text->sh_addr + text->sh_size; + + /* + * we leave the sections sorted in their original order + * by s->sh_addr, but shuffle the indexes in a random + * order for copying. + */ + index_list = malloc(sizeof(int) * num_sections); + if (!index_list) + error("Failed to allocate space for index list"); + + for (i = 0; i < num_sections; i++) + index_list[i] = i; + + shuffle_sections(index_list, num_sections); + + /* + * to avoid overwriting earlier sections before they can get + * copied to dest, stash everything into a buffer first. + * this will cause our source address to be off by + * phdr->p_offset though, so we'll adjust s->sh_offset below. + * + * TBD: ideally we'd simply decompress higher up so that our + * copy wasn't in danger of overwriting anything important. + */ + stash = malloc(phdr->p_filesz); + if (!stash) + error("Failed to allocate space for text stash"); + + memcpy(stash, source + phdr->p_offset, phdr->p_filesz); + + /* now we'd walk through the sections. */ + for (j = 0; j < num_sections; j++) { + unsigned long aligned_addr; + Elf_Shdr *s; + const char *sname; + void *src; + int pad_bytes; + + s = sections[index_list[j]]; + + sname = secstrings + s->sh_name; + + /* align addr for this section */ + aligned_addr = ALIGN(adjusted_addr, s->sh_addralign); + + /* + * copy out of stash, so adjust offset + */ + src = stash + s->sh_offset - phdr->p_offset; + + /* + * Fill any space between sections with int3 + */ + pad_bytes = aligned_addr - adjusted_addr; + memset(dest, 0xcc, pad_bytes); + + dest = (void *)ALIGN((unsigned long)dest, s->sh_addralign); + + memmove(dest, src, s->sh_size); + + dest += s->sh_size; + copy_bytes += s->sh_size + pad_bytes; + adjusted_addr = aligned_addr + s->sh_size; + + /* we can blow away sh_offset for our own uses */ + s->sh_offset = aligned_addr - s->sh_addr; + } + + free(index_list); + + /* + * move remainder of text segment. Ok to just use original source + * here since this area is untouched. + */ + memmove(dest, source + text->sh_offset + copy_bytes, + phdr->p_filesz - copy_bytes); + free(stash); +} + +#define GET_SYM(name) \ + do { \ + if (!addr_ ## name) { \ + if (strcmp(#name, strtab + sym->st_name) == 0) {\ + addr_ ## name = sym->st_value; \ + continue; \ + } \ + } \ + } while (0) + +static void parse_symtab(Elf64_Sym *symtab, char *strtab, long num_syms) +{ + Elf64_Sym *sym; + + if (!symtab || !strtab) + return; + + debug_putstr("\nLooking for symbols... "); + + /* + * walk through the symbol table looking for the symbols + * that we care about. + */ + for (sym = symtab; --num_syms >= 0; sym++) { + if (!sym->st_name) + continue; + + GET_SYM(kallsyms_num_syms); + GET_SYM(kallsyms_offsets); + GET_SYM(kallsyms_relative_base); + GET_SYM(kallsyms_names); + GET_SYM(kallsyms_markers); + GET_SYM(__altinstr_replacement); + GET_SYM(__altinstr_replacement_end); + GET_SYM(_stext); + GET_SYM(_etext); + GET_SYM(_sinittext); + GET_SYM(_einittext); + GET_SYM(__start_orc_unwind_ip); + GET_SYM(__stop_orc_unwind_ip); + GET_SYM(__start_orc_unwind); + GET_SYM(__start___ex_table); + GET_SYM(__stop___ex_table); + } +} + +void layout_randomized_image(void *output, Elf64_Ehdr *ehdr, Elf64_Phdr *phdrs) +{ + Elf64_Phdr *phdr; + Elf_Shdr *s; + Elf_Shdr *text = NULL; + Elf_Shdr *percpu = NULL; + char *secstrings; + const char *sname; + int num_sections = 0; + Elf64_Sym *symtab = NULL; + char *strtab = NULL; + long num_syms = 0; + void *dest; + int i; + char arg[MAX_FGKASLR_ARG_LENGTH]; + Elf_Shdr shdr; + unsigned long shnum; + unsigned int shstrndx; + + debug_putstr("\nParsing ELF section headers... "); + + /* + * Even though fgkaslr may have been disabled, we still + * need to parse through the section headers to get the + * start and end of the percpu section. This is because + * if we were built with CONFIG_FG_KASLR, there are more + * relative relocations present in vmlinux.relocs than + * just the percpu, and only the percpu relocs need to be + * adjusted when using just normal base address kaslr. + */ + if (cmdline_find_option_bool("nofgkaslr")) { + warn("FG_KASLR disabled on cmdline."); + nofgkaslr = 1; + } + + /* read the first section header */ + shnum = ehdr->e_shnum; + shstrndx = ehdr->e_shstrndx; + if (shnum == SHN_UNDEF || shstrndx == SHN_XINDEX) { + memcpy(&shdr, output + ehdr->e_shoff, sizeof(shdr)); + if (shnum == SHN_UNDEF) + shnum = shdr.sh_size; + if (shstrndx == SHN_XINDEX) + shstrndx = shdr.sh_link; + } + + /* we are going to need to allocate space for the section headers */ + sechdrs = malloc(sizeof(*sechdrs) * shnum); + if (!sechdrs) + error("Failed to allocate space for shdrs"); + + sections = malloc(sizeof(*sections) * shnum); + if (!sections) + error("Failed to allocate space for section pointers"); + + memcpy(sechdrs, output + ehdr->e_shoff, + sizeof(*sechdrs) * shnum); + + /* we need to allocate space for the section string table */ + s = &sechdrs[shstrndx]; + + secstrings = malloc(s->sh_size); + if (!secstrings) + error("Failed to allocate space for shstr"); + + memcpy(secstrings, output + s->sh_offset, s->sh_size); + + /* + * now we need to walk through the section headers and collect the + * sizes of the .text sections to be randomized. + */ + for (i = 0; i < shnum; i++) { + s = &sechdrs[i]; + sname = secstrings + s->sh_name; + + if (s->sh_type == SHT_SYMTAB) { + /* only one symtab per image */ + if (symtab) + error("Unexpected duplicate symtab"); + + symtab = malloc(s->sh_size); + if (!symtab) + error("Failed to allocate space for symtab"); + + memcpy(symtab, output + s->sh_offset, s->sh_size); + num_syms = s->sh_size / sizeof(*symtab); + continue; + } + + if (s->sh_type == SHT_STRTAB && i != ehdr->e_shstrndx) { + if (strtab) + error("Unexpected duplicate strtab"); + + strtab = malloc(s->sh_size); + if (!strtab) + error("Failed to allocate space for strtab"); + + memcpy(strtab, output + s->sh_offset, s->sh_size); + } + + if (!strcmp(sname, ".text")) { + if (text) + error("Unexpected duplicate .text section"); + + text = s; + continue; + } + + if (!strcmp(sname, ".data..percpu")) { + /* get start addr for later */ + percpu = s; + continue; + } + + if (!(s->sh_flags & SHF_ALLOC) || + !(s->sh_flags & SHF_EXECINSTR) || + !(strstarts(sname, ".text"))) + continue; + + sections[num_sections] = s; + + num_sections++; + } + sections[num_sections] = NULL; + sections_size = num_sections; + + parse_symtab(symtab, strtab, num_syms); + + for (i = 0; i < ehdr->e_phnum; i++) { + phdr = &phdrs[i]; + + switch (phdr->p_type) { + case PT_LOAD: + if ((phdr->p_align % 0x200000) != 0) + error("Alignment of LOAD segment isn't multiple of 2MB"); + dest = output; + dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR); + if (!nofgkaslr && + (text && phdr->p_offset == text->sh_offset)) { + move_text(num_sections, secstrings, text, + output, dest, phdr); + } else { + if (percpu && + phdr->p_offset == percpu->sh_offset) { + percpu_start = percpu->sh_addr; + percpu_end = percpu_start + + phdr->p_filesz; + } + memmove(dest, output + phdr->p_offset, + phdr->p_filesz); + } + break; + default: /* Ignore other PT_* */ + break; + } + } + + /* we need to keep the section info to redo relocs */ + free(secstrings); + + free(phdrs); +} diff --git a/arch/x86/boot/compressed/misc.c b/arch/x86/boot/compressed/misc.c index a4339cb2d247..34b2b3174727 100644 --- a/arch/x86/boot/compressed/misc.c +++ b/arch/x86/boot/compressed/misc.c @@ -207,10 +207,21 @@ static void handle_relocations(void *output, unsigned long output_len, if (IS_ENABLED(CONFIG_X86_64)) delta = virt_addr - LOAD_PHYSICAL_ADDR; - if (!delta) { - debug_putstr("No relocation needed... "); - return; + /* + * it is possible to have delta be zero and still have enabled + * fg kaslr. We need to perform relocations for fgkaslr regardless + * of whether the base address has moved. + */ + if (!IS_ENABLED(CONFIG_FG_KASLR) || + cmdline_find_option_bool("nokaslr")) { + if (!delta) { + debug_putstr("No relocation needed... "); + return; + } } + + pre_relocations_cleanup(map); + debug_putstr("Performing relocations... "); /* @@ -234,35 +245,106 @@ static void handle_relocations(void *output, unsigned long output_len, */ for (reloc = output + output_len - sizeof(*reloc); *reloc; reloc--) { long extended = *reloc; + long value; + + /* + * if using fgkaslr, we might have moved the address + * of the relocation. Check it to see if it needs adjusting + * from the original address. + */ + adjust_address(&extended); + extended += map; ptr = (unsigned long)extended; if (ptr < min_addr || ptr > max_addr) error("32-bit relocation outside of kernel!\n"); - *(uint32_t *)ptr += delta; + value = *(int32_t *)ptr; + + /* + * If using fgkaslr, the value of the relocation + * might need to be changed because it referred + * to an address that has moved. + */ + adjust_address(&value); + + value += delta; + + *(uint32_t *)ptr = value; } #ifdef CONFIG_X86_64 while (*--reloc) { long extended = *reloc; + long value; + long oldvalue; + Elf64_Shdr *s; + + /* + * if using fgkaslr, we might have moved the address + * of the relocation. Check it to see if it needs adjusting + * from the original address. + */ + s = adjust_address(&extended); + extended += map; ptr = (unsigned long)extended; if (ptr < min_addr || ptr > max_addr) error("inverse 32-bit relocation outside of kernel!\n"); - *(int32_t *)ptr -= delta; + value = *(int32_t *)ptr; + oldvalue = value; + + /* + * If using fgkaslr, these relocs will contain + * relative offsets which might need to be + * changed because it referred + * to an address that has moved. + */ + adjust_relative_offset(*reloc, &value, s); + + /* + * only percpu symbols need to have their values adjusted for + * base address kaslr since relative offsets within the .text + * and .text.* sections are ok wrt each other. + */ + if (is_percpu_addr(*reloc, oldvalue)) + value -= delta; + + *(int32_t *)ptr = value; } for (reloc--; *reloc; reloc--) { long extended = *reloc; + long value; + + /* + * if using fgkaslr, we might have moved the address + * of the relocation. Check it to see if it needs adjusting + * from the original address. + */ + adjust_address(&extended); + extended += map; ptr = (unsigned long)extended; if (ptr < min_addr || ptr > max_addr) error("64-bit relocation outside of kernel!\n"); - *(uint64_t *)ptr += delta; + value = *(int64_t *)ptr; + + /* + * If using fgkaslr, the value of the relocation + * might need to be changed because it referred + * to an address that has moved. + */ + adjust_address(&value); + + value += delta; + + *(uint64_t *)ptr = value; } + post_relocations_cleanup(map); #endif } #else @@ -271,6 +353,35 @@ static inline void handle_relocations(void *output, unsigned long output_len, { } #endif +static void layout_image(void *output, Elf_Ehdr *ehdr, Elf_Phdr *phdrs) +{ + int i; + void *dest; + Elf_Phdr *phdr; + + for (i = 0; i < ehdr->e_phnum; i++) { + phdr = &phdrs[i]; + + switch (phdr->p_type) { + case PT_LOAD: +#ifdef CONFIG_X86_64 + if ((phdr->p_align % 0x200000) != 0) + error("Alignment of LOAD segment isn't multiple of 2MB"); +#endif +#ifdef CONFIG_RELOCATABLE + dest = output; + dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR); +#else + dest = (void *)(phdr->p_paddr); +#endif + memmove(dest, output + phdr->p_offset, phdr->p_filesz); + break; + default: /* Ignore other PT_* */ + break; + } + } +} + static void parse_elf(void *output) { #ifdef CONFIG_X86_64 @@ -282,6 +393,7 @@ static void parse_elf(void *output) #endif void *dest; int i; + int nokaslr; memcpy(&ehdr, output, sizeof(ehdr)); if (ehdr.e_ident[EI_MAG0] != ELFMAG0 || @@ -292,6 +404,12 @@ static void parse_elf(void *output) return; } + if (IS_ENABLED(CONFIG_FG_KASLR)) { + nokaslr = cmdline_find_option_bool("nokaslr"); + if (nokaslr) + warn("FG_KASLR disabled: 'nokaslr' on cmdline."); + } + debug_putstr("Parsing ELF... "); phdrs = malloc(sizeof(*phdrs) * ehdr.e_phnum); @@ -300,26 +418,10 @@ static void parse_elf(void *output) memcpy(phdrs, output + ehdr.e_phoff, sizeof(*phdrs) * ehdr.e_phnum); - for (i = 0; i < ehdr.e_phnum; i++) { - phdr = &phdrs[i]; - - switch (phdr->p_type) { - case PT_LOAD: -#ifdef CONFIG_X86_64 - if ((phdr->p_align % 0x200000) != 0) - error("Alignment of LOAD segment isn't multiple of 2MB"); -#endif -#ifdef CONFIG_RELOCATABLE - dest = output; - dest += (phdr->p_paddr - LOAD_PHYSICAL_ADDR); -#else - dest = (void *)(phdr->p_paddr); -#endif - memmove(dest, output + phdr->p_offset, phdr->p_filesz); - break; - default: /* Ignore other PT_* */ break; - } - } + if (IS_ENABLED(CONFIG_FG_KASLR) && !nokaslr) + layout_randomized_image(output, &ehdr, phdrs); + else + layout_image(output, &ehdr, phdrs); free(phdrs); } diff --git a/arch/x86/boot/compressed/misc.h b/arch/x86/boot/compressed/misc.h index 16ed360b6692..1315a101c1c9 100644 --- a/arch/x86/boot/compressed/misc.h +++ b/arch/x86/boot/compressed/misc.h @@ -83,6 +83,34 @@ struct mem_vector { u64 size; }; +#ifdef CONFIG_X86_64 +#define Elf_Ehdr Elf64_Ehdr +#define Elf_Phdr Elf64_Phdr +#define Elf_Shdr Elf64_Shdr +#else +#define Elf_Ehdr Elf32_Ehdr +#define Elf_Phdr Elf32_Phdr +#define Elf_Shdr Elf32_Shdr +#endif + +#ifdef CONFIG_FG_KASLR +void layout_randomized_image(void *output, Elf_Ehdr *ehdr, Elf_Phdr *phdrs); +void pre_relocations_cleanup(unsigned long map); +void post_relocations_cleanup(unsigned long map); +Elf_Shdr *adjust_address(long *address); +void adjust_relative_offset(long pc, long *value, Elf_Shdr *section); +bool is_percpu_addr(long pc, long offset); +#else +static inline void layout_randomized_image(void *output, Elf_Ehdr *ehdr, + Elf_Phdr *phdrs) { } +static inline void pre_relocations_cleanup(unsigned long map) { } +static inline void post_relocations_cleanup(unsigned long map) { } +static inline Elf_Shdr *adjust_address(long *address) { return NULL; } +static inline void adjust_relative_offset(long pc, long *value, + Elf_Shdr *section) { } +static inline bool is_percpu_addr(long pc, long offset) { return true; } +#endif + #ifdef CONFIG_RANDOMIZE_BASE /* kaslr.c */ void choose_random_location(unsigned long input, diff --git a/arch/x86/boot/compressed/utils.c b/arch/x86/boot/compressed/utils.c new file mode 100644 index 000000000000..7c3c745f6251 --- /dev/null +++ b/arch/x86/boot/compressed/utils.c @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * This contains various libraries that are needed for FG-KASLR. + * + * Copyright (C) 2020-2021, Intel Corporation. + * Author: Kristen Carlson Accardi + */ + +#define _LINUX_KPROBES_H +#define NOKPROBE_SYMBOL(fname) + +#include "../../../../lib/sort.c" +#include "../../../../lib/bsearch.c" diff --git a/arch/x86/boot/compressed/vmlinux.symbols b/arch/x86/boot/compressed/vmlinux.symbols new file mode 100644 index 000000000000..da41f3ee153c --- /dev/null +++ b/arch/x86/boot/compressed/vmlinux.symbols @@ -0,0 +1,19 @@ +kallsyms_offsets +kallsyms_addresses +kallsyms_num_syms +kallsyms_relative_base +kallsyms_names +kallsyms_token_table +kallsyms_token_index +kallsyms_markers +__start___ex_table +__stop___ex_table +__altinstr_replacement +__altinstr_replacement_end +_sinittext +_einittext +_stext +_etext +__start_orc_unwind_ip +__stop_orc_unwind_ip +__start_orc_unwind diff --git a/arch/x86/include/asm/boot.h b/arch/x86/include/asm/boot.h index 9191280d9ea3..ce5fdee49046 100644 --- a/arch/x86/include/asm/boot.h +++ b/arch/x86/include/asm/boot.h @@ -24,7 +24,18 @@ # error "Invalid value for CONFIG_PHYSICAL_ALIGN" #endif -#if defined(CONFIG_KERNEL_BZIP2) +#ifdef CONFIG_FG_KASLR +/* + * We need extra boot heap when using fgkaslr because we make a copy + * of the original decompressed kernel to avoid issues with writing + * over ourselves when shuffling the sections. We also need extra + * space for resorting kallsyms after shuffling. This value could + * be decreased if free() would release memory properly, or if we + * could avoid the kernel copy. It would need to be increased if we + * find additional tables that need to be resorted. + */ +# define BOOT_HEAP_SIZE 0x4800000 +#elif defined(CONFIG_KERNEL_BZIP2) # define BOOT_HEAP_SIZE 0x400000 #elif defined(CONFIG_KERNEL_ZSTD) /* diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S index 3d6dc12d198f..e1db74452485 100644 --- a/arch/x86/kernel/vmlinux.lds.S +++ b/arch/x86/kernel/vmlinux.lds.S @@ -304,7 +304,9 @@ SECTIONS * get the address and the length of them to patch the kernel safely. */ .altinstr_replacement : AT(ADDR(.altinstr_replacement) - LOAD_OFFSET) { + __altinstr_replacement = .; *(.altinstr_replacement) + __altinstr_replacement_end = .; } /* diff --git a/include/uapi/linux/elf.h b/include/uapi/linux/elf.h index 61bf4774b8f2..1c74d9594919 100644 --- a/include/uapi/linux/elf.h +++ b/include/uapi/linux/elf.h @@ -299,6 +299,7 @@ typedef struct elf64_phdr { #define SHN_LIVEPATCH 0xff20 #define SHN_ABS 0xfff1 #define SHN_COMMON 0xfff2 +#define SHN_XINDEX 0xffff #define SHN_HIRESERVE 0xffff typedef struct elf32_shdr { From patchwork Thu Dec 2 22:32:04 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653707 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 9BC66C4332F for ; Thu, 2 Dec 2021 22:33:21 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1349636AbhLBWgl (ORCPT ); Thu, 2 Dec 2021 17:36:41 -0500 Received: from mga18.intel.com ([134.134.136.126]:48230 "EHLO mga18.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S245048AbhLBWga (ORCPT ); Thu, 2 Dec 2021 17:36:30 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="223730390" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="223730390" Received: from orsmga005.jf.intel.com ([10.7.209.41]) by orsmga106.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:06 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="677854451" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga005.jf.intel.com with ESMTP; 02 Dec 2021 14:32:58 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYV028552; Thu, 2 Dec 2021 22:32:55 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 04/14] linkage: add macros for putting ASM functions into own sections Date: Thu, 2 Dec 2021 23:32:04 +0100 Message-Id: <20211202223214.72888-5-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org With ClangLTO or -ffunction-sections (DCE, FG-KASLR), compiler places C functions into separate sections by default. However, this doesn't happen with ASM functions which are still being placed into .text. Introduce a pack of macros which generate a new unique section for the describing function named in the same fashion (.text.). This will be needed to make input .text section empty to harden the kernel even more. Signed-off-by: Alexander Lobakin --- include/linux/linkage.h | 82 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/include/linux/linkage.h b/include/linux/linkage.h index dbf8506decca..baaab7dece08 100644 --- a/include/linux/linkage.h +++ b/include/linux/linkage.h @@ -355,4 +355,86 @@ #endif /* __ASSEMBLY__ */ +/* + * Allow ASM symbols to have their own unique sections if they are being + * generated by the compiler for C functions (DCE, FG-KASLR, LTO). + */ +#if (defined(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION) && !defined(MODULE)) || \ + (defined(CONFIG_FG_KASLR) && !defined(MODULE)) || \ + (defined(CONFIG_MODULE_FG_KASLR) && defined(MODULE)) || \ + (defined(CONFIG_LTO_CLANG)) + +#define SYM_TEXT_SECTION(name) \ + .pushsection .text.##name, "ax" + +#define ASM_TEXT_SECTION(name) \ + ".text." #name + +#define ASM_PUSH_SECTION(name) \ + ".pushsection .text." #name ", \"ax\"" + +#else /* just .text */ + +#define SYM_TEXT_SECTION(name) \ + .pushsection .text, "ax" + +#define ASM_TEXT_SECTION(name) \ + ".text" + +#define ASM_PUSH_SECTION(name) \ + ".pushsection .text, \"ax\"" + +#endif /* just .text */ + +#ifdef __ASSEMBLY__ + +#define SYM_TEXT_END_SECTION \ + .popsection + +#define SYM_FUNC_START_LOCAL_ALIAS_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_FUNC_START_LOCAL_ALIAS(name) + +#define SYM_FUNC_START_LOCAL_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_FUNC_START_LOCAL(name) + +#define SYM_FUNC_START_NOALIGN_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_FUNC_START_NOALIGN(name) + +#define SYM_FUNC_START_WEAK_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_FUNC_START_WEAK(name) + +#define SYM_FUNC_START_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_FUNC_START(name) + +#define SYM_CODE_START_LOCAL_NOALIGN_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_CODE_START_LOCAL_NOALIGN(name) + +#define SYM_CODE_START_NOALIGN_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_CODE_START_NOALIGN(name) + +#define SYM_CODE_START_SECTION(name) \ + SYM_TEXT_SECTION(name) ASM_NL \ + SYM_CODE_START(name) + +#define SYM_FUNC_END_ALIAS_SECTION(name) \ + SYM_FUNC_END_ALIAS(name) ASM_NL \ + SYM_TEXT_END_SECTION + +#define SYM_FUNC_END_SECTION(name) \ + SYM_FUNC_END(name) ASM_NL \ + SYM_TEXT_END_SECTION + +#define SYM_CODE_END_SECTION(name) \ + SYM_CODE_END(name) ASM_NL \ + SYM_TEXT_END_SECTION + +#endif /* __ASSEMBLY__ */ + #endif /* _LINUX_LINKAGE_H */ From patchwork Thu Dec 2 22:32:06 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653713 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 00205C433FE for ; Thu, 2 Dec 2021 22:33:27 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377265AbhLBWgt (ORCPT ); Thu, 2 Dec 2021 17:36:49 -0500 Received: from mga06.intel.com ([134.134.136.31]:28330 "EHLO mga06.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S245226AbhLBWgg (ORCPT ); Thu, 2 Dec 2021 17:36:36 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="297653169" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="297653169" Received: from fmsmga008.fm.intel.com ([10.253.24.58]) by orsmga104.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:09 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="561380019" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga008.fm.intel.com with ESMTP; 02 Dec 2021 14:33:02 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYX028552; Thu, 2 Dec 2021 22:32:59 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 06/14] FG-KASLR: use a scripted approach to handle .text.* sections Date: Thu, 2 Dec 2021 23:32:06 +0100 Message-Id: <20211202223214.72888-7-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org Instead of relying on the linker and his heuristics about where to place (orphan) .text.* section, use a script to read vmlinux.o and generate a new .tmp_vmlinux.lds which will contain an entry for each of them. It relies on a magic marker inside the preprocessed vmlinux.lds (which is harmless in case FG-KASLR is disabled) and injects a list of input text sections there. As a bonus, this approach allows us to configure FG-KASLR in terms of number of functions per each section. The zero value means one section per each functions, it is the strongest choice, but the resulting vmlinux also has the biggest size here, as well as the total number of sections and the boottime delay (which is still barely noticeable). The values of 4-8 are still strong enough and allows to save some space, and so on. We also keep tracking the maximal alignment we found while traversing through the readelf output and the number of times we spotted it. It's actual only for values >= 64 and is required to reserve some space between the last .text.* section and the _etext marker. The reason is that e.g. x86 has at least 3 ASM sections (4 with ClangCFI) aligned to 4096, and when mixing them with the small sections, we could go past the _etext and render the kernel unbootable. This reserved space ensures this won't happen. Signed-off-by: Alexander Lobakin --- arch/x86/kernel/vmlinux.lds.S | 4 +- include/asm-generic/vmlinux.lds.h | 6 ++ init/Kconfig | 14 +++ scripts/generate_text_sections.pl | 156 ++++++++++++++++++++++++++++++ scripts/link-vmlinux.sh | 25 ++++- 5 files changed, 203 insertions(+), 2 deletions(-) create mode 100755 scripts/generate_text_sections.pl diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S index e1db74452485..532daa7fc888 100644 --- a/arch/x86/kernel/vmlinux.lds.S +++ b/arch/x86/kernel/vmlinux.lds.S @@ -147,9 +147,11 @@ SECTIONS #endif } :text =0xcccc + TEXT_FG_KASLR + /* End of text section, which should occupy whole number of pages */ - _etext = .; . = ALIGN(PAGE_SIZE); + _etext = .; X86_ALIGN_RODATA_BEGIN RO_DATA(PAGE_SIZE) diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h index 96fbedcbf7c8..8ddc08baf50c 100644 --- a/include/asm-generic/vmlinux.lds.h +++ b/include/asm-generic/vmlinux.lds.h @@ -127,6 +127,12 @@ #define TEXT_MAIN .text #endif +/* + * Used by scripts/generate_text_sections.pl to inject text sections, + * harmless if FG-KASLR is disabled. + */ +#define TEXT_FG_KASLR __fg_kaslr_magic = .; + /* * GCC 4.5 and later have a 32 bytes section alignment for structures. * Except GCC 4.9, that feels the need to align on 64 bytes. diff --git a/init/Kconfig b/init/Kconfig index 5cb8f8230915..8baeaef382c9 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -2063,6 +2063,20 @@ config FG_KASLR If unsure, say N. +config FG_KASLR_SHIFT + int "FG-KASLR granularity (number of functions per section shift)" + depends on FG_KASLR + range 0 16 + default 0 + help + This sets the number of functions that will be put in each section + as a power of two. + Decreasing the value increases the randomization, but also increases + the size of the final kernel/vmlinux due to the amount of sections. + 0 means that a separate section will be created for each function. + 16 almost disables the randomization, leaving only the manual + separation. + endmenu # General setup source "arch/Kconfig" diff --git a/scripts/generate_text_sections.pl b/scripts/generate_text_sections.pl new file mode 100755 index 000000000000..6871045fb7a6 --- /dev/null +++ b/scripts/generate_text_sections.pl @@ -0,0 +1,156 @@ +#!/usr/bin/env perl +# SPDX-License-Identifier: GPL-2.0-only +# +# Generates a new LD script with every .text.* section described for FG-KASLR +# to avoid orphan/heuristic section placement and double-checks we don't have +# any symbols in plain .text section. +# +# Copyright (C) 2021, Intel Corporation. +# Author: Alexander Lobakin +# + +use strict; +use warnings; + +## parameters +my $expecting = 0; +my $shift = 0; +my $file; + +foreach (@ARGV) { + if ($_ eq '-s') { + $expecting = 1; + } elsif ($expecting) { + $shift = $_ + 0; + if ($shift < 0) { + $shift = 0; + } elsif ($shift > 16) { + $shift = 16; + } + $expecting = 0; + } elsif (!defined($file)) { + $file = $_; + } else { + die "$0: usage: $0 [-s shift] binary < linker script"; + } +} + +if (!defined($file)) { + die "$0: usage: $0 [-s shift] binary < linker script"; +} + +## environment +my $readelf = $ENV{'READELF'} || die "$0: ERROR: READELF not set?"; + +## text sections array +my @sections = (); +my $has_ccf = 0; + +## max alignment found to reserve some space +my $max_align = 64; +my $count = 0; + +sub read_sections { + open(my $fh, "\"$readelf\" -SW \"$file\" 2>/dev/null |") + or die "$0: ERROR: failed to execute \"$readelf\": $!"; + + while (<$fh>) { + my $name; + my $align; + chomp; + + ($name, $align) = $_ =~ /^\s*\[[\s0-9]*\]\s*(\.\S*)\s*[A-Z]*\s*[0-9a-f]{16}\s*[0-9a-f]*\s*[0-9a-f]*\s*[0-9a-f]*\s*[0-9a-f]{2}\s*[A-Z]{2}\s*[0-9]\s*[0-9]\s*([0-9]*)$/; + + if (!defined($name)) { + next; + } + + ## Clang 13 onwards emits __cfi_check_fail only on final + ## linking, so it won't appear in .o files and will be + ## missing in @sections. Add it manually to prevent + ## spawning orphans. + if ($name eq ".text.__cfi_check_fail") { + $has_ccf = 1; + } + + if (!($name =~ /^\.text\.[0-9a-zA-Z_]*((\.constprop|\.isra|\.part)\.[0-9])*(|\.[0-9cfi]*)$/)) { + next; + } + + if ($align > $max_align) { + $max_align = $align; + $count = 1; + } elsif ($align == $max_align) { + $count++; + } + + push(@sections, $name); + } + + close($fh); + + if (!$has_ccf) { + push(@sections, ".text.__cfi_check_fail"); + } + + @sections = sort @sections; +} + +sub print_sections { + my $fps = 1 << $shift; + my $counter = 1; + + print "\t.text.0 : ALIGN(16) {\n"; + print "\t\t*(.text)\n"; + print "\t}\n"; + + print "\tASSERT(SIZEOF(.text.0) == 0, \"Plain .text is not empty!\")\n\n"; + + if (!@sections) { + return; + } + + while () { + print "\t.text.$counter : ALIGN(16) {\n"; + + my @a = (($counter - 1) * $fps .. ($counter * $fps) - 1); + for (@a) { + print "\t\t*($sections[$_])\n"; + + if ($sections[$_] eq $sections[-1]) { + print "\t}\n"; + return; + } + } + + print "\t}\n"; + $counter++; + } +} + +sub print_reserve { + ## If we have text sections aligned with 64 bytes or more, make + ## sure we reserve some space for them to not overlap _etext + ## while shuffling sections. + if (!$count) { + return; + } + + print "\n\t. += $max_align * $count;\n"; +} + +sub print_lds { + while () { + if ($_ =~ /^\s*__fg_kaslr_magic = \.;$/) { + print_sections(); + print_reserve(); + } else { + print $_; + } + } +} + +## main + +read_sections(); +print_lds(); diff --git a/scripts/link-vmlinux.sh b/scripts/link-vmlinux.sh index 5cdd9bc5c385..9245351a38d9 100755 --- a/scripts/link-vmlinux.sh +++ b/scripts/link-vmlinux.sh @@ -66,6 +66,18 @@ gen_symversions() done } +# If CONFIG_FG_KASLR is selected, generate a linker script which will +# declare all custom text sections for future boottime shuffling +gen_text_sections() +{ + info GEN .tmp_vmlinux.lds + + ${PERL} ${srctree}/scripts/generate_text_sections.pl \ + -s "${CONFIG_FG_KASLR_SHIFT}" vmlinux.o \ + < "${objtree}/${KBUILD_LDS}" \ + > .tmp_vmlinux.lds +} + # Link of vmlinux.o used for section mismatch analysis # ${1} output file modpost_link() @@ -155,12 +167,19 @@ vmlinux_link() local ld local ldflags local ldlibs + local lds info LD ${output} # skip output file argument shift + if [ -n "${CONFIG_FG_KASLR}" ]; then + lds=".tmp_vmlinux.lds" + else + lds="${objtree}/${KBUILD_LDS}" + fi + if [ -n "${CONFIG_LTO_CLANG}" ]; then # Use vmlinux.o instead of performing the slow LTO link again. objs=vmlinux.o @@ -182,7 +201,7 @@ vmlinux_link() ldlibs= fi - ldflags="${ldflags} ${wl}--script=${objtree}/${KBUILD_LDS}" + ldflags="${ldflags} ${wl}--script=${lds}" # The kallsyms linking does not need debug symbols included. if [ "$output" != "${output#.tmp_vmlinux.kallsyms}" ] ; then @@ -342,6 +361,10 @@ info GEN modules.builtin tr '\0' '\n' < modules.builtin.modinfo | sed -n 's/^[[:alnum:]:_]*\.file=//p' | tr ' ' '\n' | uniq | sed -e 's:^:kernel/:' -e 's/$/.ko/' > modules.builtin +if [ -n "${CONFIG_FG_KASLR}" ]; then + gen_text_sections +fi + btf_vmlinux_bin_o="" if [ -n "${CONFIG_DEBUG_INFO_BTF}" ]; then btf_vmlinux_bin_o=.btf.vmlinux.bin.o From patchwork Thu Dec 2 22:32:07 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653709 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 61ACEC4321E for ; Thu, 2 Dec 2021 22:33:26 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1349775AbhLBWgr (ORCPT ); Thu, 2 Dec 2021 17:36:47 -0500 Received: from mga03.intel.com ([134.134.136.65]:52308 "EHLO mga03.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S245276AbhLBWgg (ORCPT ); Thu, 2 Dec 2021 17:36:36 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="236795822" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="236795822" Received: from orsmga003.jf.intel.com ([10.7.209.27]) by orsmga103.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:12 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="459836417" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga003.jf.intel.com with ESMTP; 02 Dec 2021 14:33:04 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYY028552; Thu, 2 Dec 2021 22:33:01 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 07/14] kallsyms: Hide layout Date: Thu, 2 Dec 2021 23:32:07 +0100 Message-Id: <20211202223214.72888-8-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi This patch makes /proc/kallsyms display in a random order, rather than sorted by address in order to hide the newly randomized address layout. Signed-off-by: Kristen Carlson Accardi Reviewed-by: Tony Luck Tested-by: Tony Luck Reported-by: kernel test robot # swap.cocci Signed-off-by: Alexander Lobakin --- kernel/kallsyms.c | 158 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 157 insertions(+), 1 deletion(-) diff --git a/kernel/kallsyms.c b/kernel/kallsyms.c index 3011bc33a5ba..ff9d8b651966 100644 --- a/kernel/kallsyms.c +++ b/kernel/kallsyms.c @@ -583,6 +583,12 @@ struct kallsym_iter { int show_value; }; +struct kallsyms_shuffled_iter { + struct kallsym_iter iter; + loff_t total_syms; + loff_t shuffled_index[]; +}; + int __weak arch_get_kallsym(unsigned int symnum, unsigned long *value, char *type, char *name) { @@ -830,7 +836,7 @@ bool kallsyms_show_value(const struct cred *cred) } } -static int kallsyms_open(struct inode *inode, struct file *file) +static int __kallsyms_open(struct inode *inode, struct file *file) { /* * We keep iterator in m->private, since normal case is to @@ -851,6 +857,156 @@ static int kallsyms_open(struct inode *inode, struct file *file) return 0; } +/* + * When function granular kaslr is enabled, we need to print out the symbols + * at random so we don't reveal the new layout. + */ +#ifdef CONFIG_FG_KASLR +static int update_random_pos(struct kallsyms_shuffled_iter *s_iter, + loff_t pos, loff_t *new_pos) +{ + loff_t new; + + if (pos >= s_iter->total_syms) + return 0; + + new = s_iter->shuffled_index[pos]; + + /* + * normally this would be done as part of update_iter, however, + * we want to avoid triggering this in the event that new is + * zero since we don't want to blow away our pos end indicators. + */ + if (new == 0) { + s_iter->iter.name[0] = '\0'; + s_iter->iter.nameoff = get_symbol_offset(new); + s_iter->iter.pos = new; + } + + *new_pos = new; + return 1; +} + +static void *shuffled_start(struct seq_file *m, loff_t *pos) +{ + struct kallsyms_shuffled_iter *s_iter = m->private; + loff_t new_pos; + + if (!update_random_pos(s_iter, *pos, &new_pos)) + return NULL; + + return s_start(m, &new_pos); +} + +static void *shuffled_next(struct seq_file *m, void *p, loff_t *pos) +{ + struct kallsyms_shuffled_iter *s_iter = m->private; + loff_t new_pos; + + (*pos)++; + + if (!update_random_pos(s_iter, *pos, &new_pos)) + return NULL; + + if (!update_iter(m->private, new_pos)) + return NULL; + + return p; +} + +/* + * shuffle_index_list() + * Use a Fisher Yates algorithm to shuffle a list of text sections. + */ +static void shuffle_index_list(loff_t *indexes, loff_t size) +{ + u32 i, j; + + for (i = size - 1; i > 0; i--) { + /* pick a random index from 0 to i */ + j = get_random_u32() % (i + 1); + + swap(indexes[i], indexes[j]); + } +} + +static const struct seq_operations kallsyms_shuffled_op = { + .start = shuffled_start, + .next = shuffled_next, + .stop = s_stop, + .show = s_show +}; + +static int kallsyms_random_open(struct inode *inode, struct file *file) +{ + loff_t pos; + struct kallsyms_shuffled_iter *shuffled_iter; + struct kallsym_iter iter; + bool show_value; + + /* + * If privileged, go ahead and use the normal algorithm for + * displaying symbols + */ + show_value = kallsyms_show_value(file->f_cred); + if (show_value) + return __kallsyms_open(inode, file); + + /* + * we need to figure out how many extra symbols there are + * to print out past kallsyms_num_syms + */ + pos = kallsyms_num_syms; + reset_iter(&iter, 0); + do { + if (!update_iter(&iter, pos)) + break; + pos++; + } while (1); + + /* + * add storage space for an array of loff_t equal to the size + * of the total number of symbols we need to print + */ + shuffled_iter = __seq_open_private(file, &kallsyms_shuffled_op, + sizeof(*shuffled_iter) + + (sizeof(pos) * pos)); + if (!shuffled_iter) + return -ENOMEM; + + reset_iter(&shuffled_iter->iter, 0); + shuffled_iter->iter.show_value = show_value; + shuffled_iter->total_syms = pos; + + /* + * the existing update_iter algorithm requires that we + * are either moving along increasing pos sequentially, + * or that these values are correct. Since these values + * were discovered above, initialize our new iter so we + * can use update_iter non-sequentially. + */ + shuffled_iter->iter.pos_arch_end = iter.pos_arch_end; + shuffled_iter->iter.pos_mod_end = iter.pos_mod_end; + shuffled_iter->iter.pos_ftrace_mod_end = iter.pos_ftrace_mod_end; + + /* + * initialize the array with all possible pos values, then + * shuffle the array so that the values will display in a random + * order. + */ + for (pos = 0; pos < shuffled_iter->total_syms; pos++) + shuffled_iter->shuffled_index[pos] = pos; + + shuffle_index_list(shuffled_iter->shuffled_index, shuffled_iter->total_syms); + + return 0; +} + +#define kallsyms_open kallsyms_random_open +#else +#define kallsyms_open __kallsyms_open +#endif /* !CONFIG_FG_KASLR */ + #ifdef CONFIG_KGDB_KDB const char *kdb_walk_kallsyms(loff_t *pos) { From patchwork Thu Dec 2 22:32:08 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653711 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 1AE82C4332F for ; Thu, 2 Dec 2021 22:33:27 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377230AbhLBWgs (ORCPT ); Thu, 2 Dec 2021 17:36:48 -0500 Received: from mga12.intel.com ([192.55.52.136]:32132 "EHLO mga12.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1349448AbhLBWgg (ORCPT ); Thu, 2 Dec 2021 17:36:36 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="216877428" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="216877428" Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by fmsmga106.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:13 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="655540569" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga001.fm.intel.com with ESMTP; 02 Dec 2021 14:33:05 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYZ028552; Thu, 2 Dec 2021 22:33:03 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 08/14] livepatch: only match unique symbols when using FG-KASLR Date: Thu, 2 Dec 2021 23:32:08 +0100 Message-Id: <20211202223214.72888-9-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org If any type of function granular randomization is enabled, the sympos algorithm will fail, as it will be impossible to resolve symbols when there are duplicates using the previous symbol position. We could override sympos to 0, but make it more clear to the user and bail out if the symbol is not unique. Suggested-by: Miroslav Benes Signed-off-by: Alexander Lobakin --- kernel/livepatch/core.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/kernel/livepatch/core.c b/kernel/livepatch/core.c index 335d988bd811..10ea75111057 100644 --- a/kernel/livepatch/core.c +++ b/kernel/livepatch/core.c @@ -169,6 +169,17 @@ static int klp_find_object_symbol(const char *objname, const char *name, else kallsyms_on_each_symbol(klp_find_callback, &args); + /* + * If function granular randomization is enabled, it is impossible + * to resolve symbols when there are duplicates using the previous + * symbol position (i.e. sympos != 0). + */ + if (IS_ENABLED(CONFIG_FG_KASLR) && sympos) { + pr_err("FG-KASLR is enabled, specifying symbol position %lu for symbol '%s' in object '%s' does not work\n", + sympos, name, objname ? objname : "vmlinux"); + goto out_err; + } + /* * Ensure an address was found. If sympos is 0, ensure symbol is unique; * otherwise ensure the symbol position count matches sympos. @@ -186,6 +197,7 @@ static int klp_find_object_symbol(const char *objname, const char *name, return 0; } +out_err: *addr = 0; return -EINVAL; } From patchwork Thu Dec 2 22:32:09 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653715 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 0CA2AC4321E for ; Thu, 2 Dec 2021 22:33:30 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1349879AbhLBWgv (ORCPT ); Thu, 2 Dec 2021 17:36:51 -0500 Received: from mga12.intel.com ([192.55.52.136]:32073 "EHLO mga12.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1349494AbhLBWgi (ORCPT ); Thu, 2 Dec 2021 17:36:38 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="216877439" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="216877439" Received: from orsmga001.jf.intel.com ([10.7.209.18]) by fmsmga106.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:15 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="541402390" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga001.jf.intel.com with ESMTP; 02 Dec 2021 14:33:07 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYa028552; Thu, 2 Dec 2021 22:33:05 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 09/14] x86/boot: allow FG-KASLR to be selected Date: Thu, 2 Dec 2021 23:32:09 +0100 Message-Id: <20211202223214.72888-10-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org Now that we have full support of FG-KASLR from both kernel core and x86 code, allow FG-KASLR to be enabled for x86_64 if the "regular" KASLR is also turned on. Signed-off-by: Alexander Lobakin --- arch/x86/Kconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig index 7399327d1eff..970a03c7588d 100644 --- a/arch/x86/Kconfig +++ b/arch/x86/Kconfig @@ -75,6 +75,7 @@ config X86 select ARCH_HAS_EARLY_DEBUG if KGDB select ARCH_HAS_ELF_RANDOMIZE select ARCH_HAS_FAST_MULTIPLIER + select ARCH_HAS_FG_KASLR if X86_64 && RANDOMIZE_BASE select ARCH_HAS_FILTER_PGPROT select ARCH_HAS_FORTIFY_SOURCE select ARCH_HAS_GCOV_PROFILE_ALL From patchwork Thu Dec 2 22:32:10 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653717 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 8654DC4167D for ; Thu, 2 Dec 2021 22:33:30 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377301AbhLBWgw (ORCPT ); Thu, 2 Dec 2021 17:36:52 -0500 Received: from mga11.intel.com ([192.55.52.93]:40642 "EHLO mga11.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1349599AbhLBWgl (ORCPT ); Thu, 2 Dec 2021 17:36:41 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="234366350" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="234366350" Received: from orsmga003.jf.intel.com ([10.7.209.27]) by fmsmga102.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:17 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="459836433" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by orsmga003.jf.intel.com with ESMTP; 02 Dec 2021 14:33:09 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYb028552; Thu, 2 Dec 2021 22:33:07 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 10/14] arm64/crypto: conditionally place ASM functions into separate sections Date: Thu, 2 Dec 2021 23:32:10 +0100 Message-Id: <20211202223214.72888-11-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org The resulting LD script generated by FG-KASLR script contains a size assertion for the input .text function. In case if it's not empty, the build will stop plug a potentional layout leakage. As FG-KASLR for modules tends to be arch-independent, we should take care of the modular ASM code of every architecture to not break the build. This is the ARM64 part. Signed-off-by: Alexander Lobakin --- arch/arm64/crypto/aes-ce-ccm-core.S | 16 +++++------ arch/arm64/crypto/aes-ce-core.S | 16 +++++------ arch/arm64/crypto/aes-ce.S | 4 +-- arch/arm64/crypto/aes-cipher-core.S | 8 +++--- arch/arm64/crypto/aes-modes.S | 16 +++++------ arch/arm64/crypto/aes-neon.S | 4 +-- arch/arm64/crypto/aes-neonbs-core.S | 38 +++++++++++++-------------- arch/arm64/crypto/chacha-neon-core.S | 18 ++++++------- arch/arm64/crypto/crct10dif-ce-core.S | 14 +++++----- arch/arm64/crypto/ghash-ce-core.S | 24 ++++++++--------- arch/arm64/crypto/nh-neon-core.S | 4 +-- arch/arm64/crypto/poly1305-armv8.pl | 17 ++++++++++++ arch/arm64/crypto/sha1-ce-core.S | 4 +-- arch/arm64/crypto/sha2-ce-core.S | 4 +-- arch/arm64/crypto/sha3-ce-core.S | 4 +-- arch/arm64/crypto/sha512-armv8.pl | 11 ++++++++ arch/arm64/crypto/sha512-ce-core.S | 4 +-- arch/arm64/crypto/sm3-ce-core.S | 4 +-- arch/arm64/crypto/sm4-ce-core.S | 4 +-- 19 files changed, 121 insertions(+), 93 deletions(-) diff --git a/arch/arm64/crypto/aes-ce-ccm-core.S b/arch/arm64/crypto/aes-ce-ccm-core.S index b03f7f71f893..03c8606f45b4 100644 --- a/arch/arm64/crypto/aes-ce-ccm-core.S +++ b/arch/arm64/crypto/aes-ce-ccm-core.S @@ -15,7 +15,7 @@ * u32 ce_aes_ccm_auth_data(u8 mac[], u8 const in[], u32 abytes, * u32 macp, u8 const rk[], u32 rounds); */ -SYM_FUNC_START(ce_aes_ccm_auth_data) +SYM_FUNC_START_SECTION(ce_aes_ccm_auth_data) ld1 {v0.16b}, [x0] /* load mac */ cbz w3, 1f sub w3, w3, #16 @@ -80,13 +80,13 @@ SYM_FUNC_START(ce_aes_ccm_auth_data) st1 {v0.16b}, [x0] 10: mov w0, w3 ret -SYM_FUNC_END(ce_aes_ccm_auth_data) +SYM_FUNC_END_SECTION(ce_aes_ccm_auth_data) /* * void ce_aes_ccm_final(u8 mac[], u8 const ctr[], u8 const rk[], * u32 rounds); */ -SYM_FUNC_START(ce_aes_ccm_final) +SYM_FUNC_START_SECTION(ce_aes_ccm_final) ld1 {v3.4s}, [x2], #16 /* load first round key */ ld1 {v0.16b}, [x0] /* load mac */ cmp w3, #12 /* which key size? */ @@ -120,7 +120,7 @@ SYM_FUNC_START(ce_aes_ccm_final) eor v0.16b, v0.16b, v1.16b /* en-/decrypt the mac */ st1 {v0.16b}, [x0] /* store result */ ret -SYM_FUNC_END(ce_aes_ccm_final) +SYM_FUNC_END_SECTION(ce_aes_ccm_final) .macro aes_ccm_do_crypt,enc cbz x2, 5f @@ -212,10 +212,10 @@ CPU_LE( rev x8, x8 ) * u8 const rk[], u32 rounds, u8 mac[], * u8 ctr[]); */ -SYM_FUNC_START(ce_aes_ccm_encrypt) +SYM_FUNC_START_SECTION(ce_aes_ccm_encrypt) aes_ccm_do_crypt 1 -SYM_FUNC_END(ce_aes_ccm_encrypt) +SYM_FUNC_END_SECTION(ce_aes_ccm_encrypt) -SYM_FUNC_START(ce_aes_ccm_decrypt) +SYM_FUNC_START_SECTION(ce_aes_ccm_decrypt) aes_ccm_do_crypt 0 -SYM_FUNC_END(ce_aes_ccm_decrypt) +SYM_FUNC_END_SECTION(ce_aes_ccm_decrypt) diff --git a/arch/arm64/crypto/aes-ce-core.S b/arch/arm64/crypto/aes-ce-core.S index e52e13eb8fdb..abe6ee0501bf 100644 --- a/arch/arm64/crypto/aes-ce-core.S +++ b/arch/arm64/crypto/aes-ce-core.S @@ -8,7 +8,7 @@ .arch armv8-a+crypto -SYM_FUNC_START(__aes_ce_encrypt) +SYM_FUNC_START_SECTION(__aes_ce_encrypt) sub w3, w3, #2 ld1 {v0.16b}, [x2] ld1 {v1.4s}, [x0], #16 @@ -34,9 +34,9 @@ SYM_FUNC_START(__aes_ce_encrypt) eor v0.16b, v0.16b, v3.16b st1 {v0.16b}, [x1] ret -SYM_FUNC_END(__aes_ce_encrypt) +SYM_FUNC_END_SECTION(__aes_ce_encrypt) -SYM_FUNC_START(__aes_ce_decrypt) +SYM_FUNC_START_SECTION(__aes_ce_decrypt) sub w3, w3, #2 ld1 {v0.16b}, [x2] ld1 {v1.4s}, [x0], #16 @@ -62,23 +62,23 @@ SYM_FUNC_START(__aes_ce_decrypt) eor v0.16b, v0.16b, v3.16b st1 {v0.16b}, [x1] ret -SYM_FUNC_END(__aes_ce_decrypt) +SYM_FUNC_END_SECTION(__aes_ce_decrypt) /* * __aes_ce_sub() - use the aese instruction to perform the AES sbox * substitution on each byte in 'input' */ -SYM_FUNC_START(__aes_ce_sub) +SYM_FUNC_START_SECTION(__aes_ce_sub) dup v1.4s, w0 movi v0.16b, #0 aese v0.16b, v1.16b umov w0, v0.s[0] ret -SYM_FUNC_END(__aes_ce_sub) +SYM_FUNC_END_SECTION(__aes_ce_sub) -SYM_FUNC_START(__aes_ce_invert) +SYM_FUNC_START_SECTION(__aes_ce_invert) ld1 {v0.4s}, [x1] aesimc v1.16b, v0.16b st1 {v1.4s}, [x0] ret -SYM_FUNC_END(__aes_ce_invert) +SYM_FUNC_END_SECTION(__aes_ce_invert) diff --git a/arch/arm64/crypto/aes-ce.S b/arch/arm64/crypto/aes-ce.S index 1dc5bbbfeed2..909d2dcf0907 100644 --- a/arch/arm64/crypto/aes-ce.S +++ b/arch/arm64/crypto/aes-ce.S @@ -9,8 +9,8 @@ #include #include -#define AES_FUNC_START(func) SYM_FUNC_START(ce_ ## func) -#define AES_FUNC_END(func) SYM_FUNC_END(ce_ ## func) +#define AES_FUNC_START(func) SYM_FUNC_START_SECTION(ce_ ## func) +#define AES_FUNC_END(func) SYM_FUNC_END_SECTION(ce_ ## func) .arch armv8-a+crypto diff --git a/arch/arm64/crypto/aes-cipher-core.S b/arch/arm64/crypto/aes-cipher-core.S index c9d6955f8404..e47c0aef7a7d 100644 --- a/arch/arm64/crypto/aes-cipher-core.S +++ b/arch/arm64/crypto/aes-cipher-core.S @@ -122,11 +122,11 @@ CPU_BE( rev w7, w7 ) ret .endm -SYM_FUNC_START(__aes_arm64_encrypt) +SYM_FUNC_START_SECTION(__aes_arm64_encrypt) do_crypt fround, crypto_ft_tab, crypto_ft_tab + 1, 2 -SYM_FUNC_END(__aes_arm64_encrypt) +SYM_FUNC_END_SECTION(__aes_arm64_encrypt) +SYM_FUNC_START_SECTION(__aes_arm64_decrypt) .align 5 -SYM_FUNC_START(__aes_arm64_decrypt) do_crypt iround, crypto_it_tab, crypto_aes_inv_sbox, 0 -SYM_FUNC_END(__aes_arm64_decrypt) +SYM_FUNC_END_SECTION(__aes_arm64_decrypt) diff --git a/arch/arm64/crypto/aes-modes.S b/arch/arm64/crypto/aes-modes.S index b495de22bb38..5f7a43fa8438 100644 --- a/arch/arm64/crypto/aes-modes.S +++ b/arch/arm64/crypto/aes-modes.S @@ -22,26 +22,26 @@ #define ST5(x...) x #endif -SYM_FUNC_START_LOCAL(aes_encrypt_block4x) +SYM_FUNC_START_LOCAL_SECTION(aes_encrypt_block4x) encrypt_block4x v0, v1, v2, v3, w3, x2, x8, w7 ret -SYM_FUNC_END(aes_encrypt_block4x) +SYM_FUNC_END_SECTION(aes_encrypt_block4x) -SYM_FUNC_START_LOCAL(aes_decrypt_block4x) +SYM_FUNC_START_LOCAL_SECTION(aes_decrypt_block4x) decrypt_block4x v0, v1, v2, v3, w3, x2, x8, w7 ret -SYM_FUNC_END(aes_decrypt_block4x) +SYM_FUNC_END_SECTION(aes_decrypt_block4x) #if MAX_STRIDE == 5 -SYM_FUNC_START_LOCAL(aes_encrypt_block5x) +SYM_FUNC_START_LOCAL_SECTION(aes_encrypt_block5x) encrypt_block5x v0, v1, v2, v3, v4, w3, x2, x8, w7 ret -SYM_FUNC_END(aes_encrypt_block5x) +SYM_FUNC_END_SECTION(aes_encrypt_block5x) -SYM_FUNC_START_LOCAL(aes_decrypt_block5x) +SYM_FUNC_START_LOCAL_SECTION(aes_decrypt_block5x) decrypt_block5x v0, v1, v2, v3, v4, w3, x2, x8, w7 ret -SYM_FUNC_END(aes_decrypt_block5x) +SYM_FUNC_END_SECTION(aes_decrypt_block5x) #endif /* diff --git a/arch/arm64/crypto/aes-neon.S b/arch/arm64/crypto/aes-neon.S index e47d3ec2cfb4..9c8d6cccd2cd 100644 --- a/arch/arm64/crypto/aes-neon.S +++ b/arch/arm64/crypto/aes-neon.S @@ -8,8 +8,8 @@ #include #include -#define AES_FUNC_START(func) SYM_FUNC_START(neon_ ## func) -#define AES_FUNC_END(func) SYM_FUNC_END(neon_ ## func) +#define AES_FUNC_START(func) SYM_FUNC_START_SECTION(neon_ ## func) +#define AES_FUNC_END(func) SYM_FUNC_END_SECTION(neon_ ## func) xtsmask .req v7 cbciv .req v7 diff --git a/arch/arm64/crypto/aes-neonbs-core.S b/arch/arm64/crypto/aes-neonbs-core.S index a3405b8c344b..582343f18ad0 100644 --- a/arch/arm64/crypto/aes-neonbs-core.S +++ b/arch/arm64/crypto/aes-neonbs-core.S @@ -380,7 +380,7 @@ ISRM0: .octa 0x0306090c00070a0d01040b0e0205080f /* * void aesbs_convert_key(u8 out[], u32 const rk[], int rounds) */ -SYM_FUNC_START(aesbs_convert_key) +SYM_FUNC_START_SECTION(aesbs_convert_key) ld1 {v7.4s}, [x1], #16 // load round 0 key ld1 {v17.4s}, [x1], #16 // load round 1 key @@ -425,10 +425,10 @@ SYM_FUNC_START(aesbs_convert_key) eor v17.16b, v17.16b, v7.16b str q17, [x0] ret -SYM_FUNC_END(aesbs_convert_key) +SYM_FUNC_END_SECTION(aesbs_convert_key) +SYM_FUNC_START_LOCAL_SECTION(aesbs_encrypt8) .align 4 -SYM_FUNC_START_LOCAL(aesbs_encrypt8) ldr q9, [bskey], #16 // round 0 key ldr q8, M0SR ldr q24, SR @@ -488,10 +488,10 @@ SYM_FUNC_START_LOCAL(aesbs_encrypt8) eor v2.16b, v2.16b, v12.16b eor v5.16b, v5.16b, v12.16b ret -SYM_FUNC_END(aesbs_encrypt8) +SYM_FUNC_END_SECTION(aesbs_encrypt8) +SYM_FUNC_START_LOCAL_SECTION(aesbs_decrypt8) .align 4 -SYM_FUNC_START_LOCAL(aesbs_decrypt8) lsl x9, rounds, #7 add bskey, bskey, x9 @@ -553,7 +553,7 @@ SYM_FUNC_START_LOCAL(aesbs_decrypt8) eor v3.16b, v3.16b, v12.16b eor v5.16b, v5.16b, v12.16b ret -SYM_FUNC_END(aesbs_decrypt8) +SYM_FUNC_END_SECTION(aesbs_decrypt8) /* * aesbs_ecb_encrypt(u8 out[], u8 const in[], u8 const rk[], int rounds, @@ -619,13 +619,13 @@ SYM_FUNC_END(aesbs_decrypt8) ret .endm +SYM_FUNC_START_SECTION(aesbs_ecb_encrypt) .align 4 -SYM_FUNC_START(aesbs_ecb_encrypt) __ecb_crypt aesbs_encrypt8, v0, v1, v4, v6, v3, v7, v2, v5 -SYM_FUNC_END(aesbs_ecb_encrypt) +SYM_FUNC_END_SECTION(aesbs_ecb_encrypt) +SYM_FUNC_START_SECTION(aesbs_ecb_decrypt) .align 4 -SYM_FUNC_START(aesbs_ecb_decrypt) __ecb_crypt aesbs_decrypt8, v0, v1, v6, v4, v2, v7, v3, v5 SYM_FUNC_END(aesbs_ecb_decrypt) @@ -633,8 +633,8 @@ SYM_FUNC_END(aesbs_ecb_decrypt) * aesbs_cbc_decrypt(u8 out[], u8 const in[], u8 const rk[], int rounds, * int blocks, u8 iv[]) */ +SYM_FUNC_START_SECTION(aesbs_cbc_decrypt) .align 4 -SYM_FUNC_START(aesbs_cbc_decrypt) frame_push 6 mov x19, x0 @@ -718,7 +718,7 @@ SYM_FUNC_START(aesbs_cbc_decrypt) 2: frame_pop ret -SYM_FUNC_END(aesbs_cbc_decrypt) +SYM_FUNC_END_SECTION(aesbs_cbc_decrypt) .macro next_tweak, out, in, const, tmp sshr \tmp\().2d, \in\().2d, #63 @@ -734,7 +734,7 @@ SYM_FUNC_END(aesbs_cbc_decrypt) * aesbs_xts_decrypt(u8 out[], u8 const in[], u8 const rk[], int rounds, * int blocks, u8 iv[]) */ -SYM_FUNC_START_LOCAL(__xts_crypt8) +SYM_FUNC_START_LOCAL_SECTION(__xts_crypt8) mov x6, #1 lsl x6, x6, x23 subs w23, w23, #8 @@ -787,7 +787,7 @@ SYM_FUNC_START_LOCAL(__xts_crypt8) 0: mov bskey, x21 mov rounds, x22 br x16 -SYM_FUNC_END(__xts_crypt8) +SYM_FUNC_END_SECTION(__xts_crypt8) .macro __xts_crypt, do8, o0, o1, o2, o3, o4, o5, o6, o7 frame_push 6, 64 @@ -851,13 +851,13 @@ SYM_FUNC_END(__xts_crypt8) ret .endm -SYM_FUNC_START(aesbs_xts_encrypt) +SYM_FUNC_START_SECTION(aesbs_xts_encrypt) __xts_crypt aesbs_encrypt8, v0, v1, v4, v6, v3, v7, v2, v5 -SYM_FUNC_END(aesbs_xts_encrypt) +SYM_FUNC_END_SECTION(aesbs_xts_encrypt) -SYM_FUNC_START(aesbs_xts_decrypt) +SYM_FUNC_START_SECTION(aesbs_xts_decrypt) __xts_crypt aesbs_decrypt8, v0, v1, v6, v4, v2, v7, v3, v5 -SYM_FUNC_END(aesbs_xts_decrypt) +SYM_FUNC_END_SECTION(aesbs_xts_decrypt) .macro next_ctr, v mov \v\().d[1], x8 @@ -871,7 +871,7 @@ SYM_FUNC_END(aesbs_xts_decrypt) * aesbs_ctr_encrypt(u8 out[], u8 const in[], u8 const rk[], * int rounds, int blocks, u8 iv[], u8 final[]) */ -SYM_FUNC_START(aesbs_ctr_encrypt) +SYM_FUNC_START_SECTION(aesbs_ctr_encrypt) frame_push 8 mov x19, x0 @@ -998,4 +998,4 @@ CPU_LE( rev x8, x8 ) 7: cbz x25, 8b st1 {v5.16b}, [x25] b 8b -SYM_FUNC_END(aesbs_ctr_encrypt) +SYM_FUNC_END_SECTION(aesbs_ctr_encrypt) diff --git a/arch/arm64/crypto/chacha-neon-core.S b/arch/arm64/crypto/chacha-neon-core.S index b70ac76f2610..34a3087055f8 100644 --- a/arch/arm64/crypto/chacha-neon-core.S +++ b/arch/arm64/crypto/chacha-neon-core.S @@ -23,7 +23,6 @@ #include .text - .align 6 /* * chacha_permute - permute one block @@ -36,7 +35,8 @@ * * Clobbers: w3, x10, v4, v12 */ -SYM_FUNC_START_LOCAL(chacha_permute) +SYM_FUNC_START_LOCAL_SECTION(chacha_permute) + .align 6 adr_l x10, ROT8 ld1 {v12.4s}, [x10] @@ -104,9 +104,9 @@ SYM_FUNC_START_LOCAL(chacha_permute) b.ne .Ldoubleround ret -SYM_FUNC_END(chacha_permute) +SYM_FUNC_END_SECTION(chacha_permute) -SYM_FUNC_START(chacha_block_xor_neon) +SYM_FUNC_START_SECTION(chacha_block_xor_neon) // x0: Input state matrix, s // x1: 1 data block output, o // x2: 1 data block input, i @@ -143,9 +143,9 @@ SYM_FUNC_START(chacha_block_xor_neon) ldp x29, x30, [sp], #16 ret -SYM_FUNC_END(chacha_block_xor_neon) +SYM_FUNC_END_SECTION(chacha_block_xor_neon) -SYM_FUNC_START(hchacha_block_neon) +SYM_FUNC_START_SECTION(hchacha_block_neon) // x0: Input state matrix, s // x1: output (8 32-bit words) // w2: nrounds @@ -163,7 +163,7 @@ SYM_FUNC_START(hchacha_block_neon) ldp x29, x30, [sp], #16 ret -SYM_FUNC_END(hchacha_block_neon) +SYM_FUNC_END_SECTION(hchacha_block_neon) a0 .req w12 a1 .req w13 @@ -182,8 +182,8 @@ SYM_FUNC_END(hchacha_block_neon) a14 .req w27 a15 .req w28 +SYM_FUNC_START_SECTION(chacha_4block_xor_neon) .align 6 -SYM_FUNC_START(chacha_4block_xor_neon) frame_push 10 // x0: Input state matrix, s @@ -790,7 +790,7 @@ CPU_BE( rev a15, a15 ) st1 {v28.16b-v31.16b}, [x7] // overlapping stores 3: st1 {v24.16b-v27.16b}, [x1] b .Lout -SYM_FUNC_END(chacha_4block_xor_neon) +SYM_FUNC_END_SECTION(chacha_4block_xor_neon) .section ".rodata", "a", %progbits .align L1_CACHE_SHIFT diff --git a/arch/arm64/crypto/crct10dif-ce-core.S b/arch/arm64/crypto/crct10dif-ce-core.S index dce6dcebfca1..54e121a56895 100644 --- a/arch/arm64/crypto/crct10dif-ce-core.S +++ b/arch/arm64/crypto/crct10dif-ce-core.S @@ -131,7 +131,7 @@ tbl bd4.16b, {\bd\().16b}, perm4.16b .endm -SYM_FUNC_START_LOCAL(__pmull_p8_core) +SYM_FUNC_START_LOCAL_SECTION(__pmull_p8_core) .L__pmull_p8_core: ext t4.8b, ad.8b, ad.8b, #1 // A1 ext t5.8b, ad.8b, ad.8b, #2 // A2 @@ -194,7 +194,7 @@ SYM_FUNC_START_LOCAL(__pmull_p8_core) eor t4.16b, t4.16b, t5.16b eor t6.16b, t6.16b, t3.16b ret -SYM_FUNC_END(__pmull_p8_core) +SYM_FUNC_END_SECTION(__pmull_p8_core) .macro __pmull_p8, rq, ad, bd, i .ifnc \bd, fold_consts @@ -465,21 +465,21 @@ CPU_LE( ext v7.16b, v7.16b, v7.16b, #8 ) // // Assumes len >= 16. // -SYM_FUNC_START(crc_t10dif_pmull_p8) +SYM_FUNC_START_SECTION(crc_t10dif_pmull_p8) stp x29, x30, [sp, #-16]! mov x29, sp crc_t10dif_pmull p8 -SYM_FUNC_END(crc_t10dif_pmull_p8) +SYM_FUNC_END_SECTION(crc_t10dif_pmull_p8) - .align 5 // // u16 crc_t10dif_pmull_p64(u16 init_crc, const u8 *buf, size_t len); // // Assumes len >= 16. // -SYM_FUNC_START(crc_t10dif_pmull_p64) +SYM_FUNC_START_SECTION(crc_t10dif_pmull_p64) + .align 5 crc_t10dif_pmull p64 -SYM_FUNC_END(crc_t10dif_pmull_p64) +SYM_FUNC_END_SECTION(crc_t10dif_pmull_p64) .section ".rodata", "a" .align 4 diff --git a/arch/arm64/crypto/ghash-ce-core.S b/arch/arm64/crypto/ghash-ce-core.S index 7868330dd54e..a69c1d4479db 100644 --- a/arch/arm64/crypto/ghash-ce-core.S +++ b/arch/arm64/crypto/ghash-ce-core.S @@ -350,13 +350,13 @@ CPU_LE( rev64 T1.16b, T1.16b ) * void pmull_ghash_update(int blocks, u64 dg[], const char *src, * struct ghash_key const *k, const char *head) */ -SYM_FUNC_START(pmull_ghash_update_p64) +SYM_FUNC_START_SECTION(pmull_ghash_update_p64) __pmull_ghash p64 -SYM_FUNC_END(pmull_ghash_update_p64) +SYM_FUNC_END_SECTION(pmull_ghash_update_p64) -SYM_FUNC_START(pmull_ghash_update_p8) +SYM_FUNC_START_SECTION(pmull_ghash_update_p8) __pmull_ghash p8 -SYM_FUNC_END(pmull_ghash_update_p8) +SYM_FUNC_END_SECTION(pmull_ghash_update_p8) KS0 .req v8 KS1 .req v9 @@ -602,20 +602,20 @@ CPU_LE( rev w8, w8 ) * struct ghash_key const *k, u64 dg[], u8 ctr[], * int rounds, u8 tag) */ -SYM_FUNC_START(pmull_gcm_encrypt) +SYM_FUNC_START_SECTION(pmull_gcm_encrypt) pmull_gcm_do_crypt 1 -SYM_FUNC_END(pmull_gcm_encrypt) +SYM_FUNC_END_SECTION(pmull_gcm_encrypt) /* * void pmull_gcm_decrypt(int blocks, u8 dst[], const u8 src[], * struct ghash_key const *k, u64 dg[], u8 ctr[], * int rounds, u8 tag) */ -SYM_FUNC_START(pmull_gcm_decrypt) +SYM_FUNC_START_SECTION(pmull_gcm_decrypt) pmull_gcm_do_crypt 0 -SYM_FUNC_END(pmull_gcm_decrypt) +SYM_FUNC_END_SECTION(pmull_gcm_decrypt) -SYM_FUNC_START_LOCAL(pmull_gcm_ghash_4x) +SYM_FUNC_START_LOCAL_SECTION(pmull_gcm_ghash_4x) movi MASK.16b, #0xe1 shl MASK.2d, MASK.2d, #57 @@ -696,9 +696,9 @@ SYM_FUNC_START_LOCAL(pmull_gcm_ghash_4x) eor XL.16b, XL.16b, T2.16b ret -SYM_FUNC_END(pmull_gcm_ghash_4x) +SYM_FUNC_END_SECTION(pmull_gcm_ghash_4x) -SYM_FUNC_START_LOCAL(pmull_gcm_enc_4x) +SYM_FUNC_START_LOCAL_SECTION(pmull_gcm_enc_4x) ld1 {KS0.16b}, [x5] // load upper counter sub w10, w8, #4 sub w11, w8, #3 @@ -761,7 +761,7 @@ SYM_FUNC_START_LOCAL(pmull_gcm_enc_4x) eor INP3.16b, INP3.16b, KS3.16b ret -SYM_FUNC_END(pmull_gcm_enc_4x) +SYM_FUNC_END_SECTION(pmull_gcm_enc_4x) .section ".rodata", "a" .align 6 diff --git a/arch/arm64/crypto/nh-neon-core.S b/arch/arm64/crypto/nh-neon-core.S index 51c0a534ef87..cb354d3f7e7b 100644 --- a/arch/arm64/crypto/nh-neon-core.S +++ b/arch/arm64/crypto/nh-neon-core.S @@ -62,7 +62,7 @@ * * It's guaranteed that message_len % 16 == 0. */ -SYM_FUNC_START(nh_neon) +SYM_FUNC_START_SECTION(nh_neon) ld1 {K0.4s,K1.4s}, [KEY], #32 movi PASS0_SUMS.2d, #0 @@ -100,4 +100,4 @@ SYM_FUNC_START(nh_neon) addp T1.2d, PASS2_SUMS.2d, PASS3_SUMS.2d st1 {T0.16b,T1.16b}, [HASH] ret -SYM_FUNC_END(nh_neon) +SYM_FUNC_END_SECTION(nh_neon) diff --git a/arch/arm64/crypto/poly1305-armv8.pl b/arch/arm64/crypto/poly1305-armv8.pl index cbc980fb02e3..039e6a9ce68c 100644 --- a/arch/arm64/crypto/poly1305-armv8.pl +++ b/arch/arm64/crypto/poly1305-armv8.pl @@ -48,8 +48,12 @@ my ($h0,$h1,$h2,$r0,$r1,$s1,$t0,$t1,$d0,$d1,$d2) = map("x$_",(4..14)); $code.=<<___; #ifndef __KERNEL__ +# define SYM_TEXT_SECTION() +# define SYM_TEXT_END_SECTION # include "arm_arch.h" .extern OPENSSL_armcap_P +#else +# include #endif .text @@ -58,6 +62,7 @@ $code.=<<___; .globl poly1305_blocks .globl poly1305_emit +SYM_TEXT_SECTION(poly1305_init) .globl poly1305_init .type poly1305_init,%function .align 5 @@ -107,7 +112,9 @@ poly1305_init: .Lno_key: ret .size poly1305_init,.-poly1305_init +SYM_TEXT_END_SECTION +SYM_TEXT_SECTION(poly1305_blocks) .type poly1305_blocks,%function .align 5 poly1305_blocks: @@ -198,7 +205,9 @@ poly1305_blocks: .Lno_data: ret .size poly1305_blocks,.-poly1305_blocks +SYM_TEXT_END_SECTION +SYM_TEXT_SECTION(poly1305_emit) .type poly1305_emit,%function .align 5 poly1305_emit: @@ -258,6 +267,7 @@ poly1305_emit: ret .size poly1305_emit,.-poly1305_emit +SYM_TEXT_END_SECTION ___ my ($R0,$R1,$S1,$R2,$S2,$R3,$S3,$R4,$S4) = map("v$_.4s",(0..8)); my ($IN01_0,$IN01_1,$IN01_2,$IN01_3,$IN01_4) = map("v$_.2s",(9..13)); @@ -270,6 +280,7 @@ my ($in2,$zeros)=("x16","x17"); my $is_base2_26 = $zeros; # borrow $code.=<<___; +SYM_TEXT_SECTION(poly1305_mult) .type poly1305_mult,%function .align 5 poly1305_mult: @@ -306,7 +317,9 @@ poly1305_mult: ret .size poly1305_mult,.-poly1305_mult +SYM_TEXT_END_SECTION +SYM_TEXT_SECTION(poly1305_splat) .type poly1305_splat,%function .align 4 poly1305_splat: @@ -333,7 +346,9 @@ poly1305_splat: ret .size poly1305_splat,.-poly1305_splat +SYM_TEXT_END_SECTION +SYM_TEXT_SECTION(poly1305_blocks_neon) #ifdef __KERNEL__ .globl poly1305_blocks_neon #endif @@ -888,6 +903,8 @@ poly1305_blocks_neon: .align 5 .Lzeros: .long 0,0,0,0,0,0,0,0 +SYM_TEXT_END_SECTION + .asciz "Poly1305 for ARMv8, CRYPTOGAMS by \@dot-asm" .align 2 #if !defined(__KERNEL__) && !defined(_WIN64) diff --git a/arch/arm64/crypto/sha1-ce-core.S b/arch/arm64/crypto/sha1-ce-core.S index 889ca0f8972b..2ba5f8ea39fc 100644 --- a/arch/arm64/crypto/sha1-ce-core.S +++ b/arch/arm64/crypto/sha1-ce-core.S @@ -65,7 +65,7 @@ * int sha1_ce_transform(struct sha1_ce_state *sst, u8 const *src, * int blocks) */ -SYM_FUNC_START(sha1_ce_transform) +SYM_FUNC_START_SECTION(sha1_ce_transform) /* load round constants */ loadrc k0.4s, 0x5a827999, w6 loadrc k1.4s, 0x6ed9eba1, w6 @@ -147,4 +147,4 @@ CPU_LE( rev32 v11.16b, v11.16b ) str dgb, [x0, #16] mov w0, w2 ret -SYM_FUNC_END(sha1_ce_transform) +SYM_FUNC_END_SECTION(sha1_ce_transform) diff --git a/arch/arm64/crypto/sha2-ce-core.S b/arch/arm64/crypto/sha2-ce-core.S index 491179922f49..6c1a4a128355 100644 --- a/arch/arm64/crypto/sha2-ce-core.S +++ b/arch/arm64/crypto/sha2-ce-core.S @@ -75,7 +75,7 @@ * int blocks) */ .text -SYM_FUNC_START(sha2_ce_transform) +SYM_FUNC_START_SECTION(sha2_ce_transform) /* load round constants */ adr_l x8, .Lsha2_rcon ld1 { v0.4s- v3.4s}, [x8], #64 @@ -154,4 +154,4 @@ CPU_LE( rev32 v19.16b, v19.16b ) 3: st1 {dgav.4s, dgbv.4s}, [x0] mov w0, w2 ret -SYM_FUNC_END(sha2_ce_transform) +SYM_FUNC_END_SECTION(sha2_ce_transform) diff --git a/arch/arm64/crypto/sha3-ce-core.S b/arch/arm64/crypto/sha3-ce-core.S index 9c77313f5a60..6105cc815c9a 100644 --- a/arch/arm64/crypto/sha3-ce-core.S +++ b/arch/arm64/crypto/sha3-ce-core.S @@ -40,7 +40,7 @@ * int sha3_ce_transform(u64 *st, const u8 *data, int blocks, int dg_size) */ .text -SYM_FUNC_START(sha3_ce_transform) +SYM_FUNC_START_SECTION(sha3_ce_transform) /* load state */ add x8, x0, #32 ld1 { v0.1d- v3.1d}, [x0] @@ -197,7 +197,7 @@ SYM_FUNC_START(sha3_ce_transform) st1 {v24.1d}, [x0] mov w0, w2 ret -SYM_FUNC_END(sha3_ce_transform) +SYM_FUNC_END_SECTION(sha3_ce_transform) .section ".rodata", "a" .align 8 diff --git a/arch/arm64/crypto/sha512-armv8.pl b/arch/arm64/crypto/sha512-armv8.pl index 2d8655d5b1af..7952696d3c88 100644 --- a/arch/arm64/crypto/sha512-armv8.pl +++ b/arch/arm64/crypto/sha512-armv8.pl @@ -195,11 +195,16 @@ ___ $code.=<<___; #ifndef __KERNEL__ # include "arm_arch.h" +# define SYM_TEXT_SECTION() +# define SYM_TEXT_END_SECTION +#else +# include #endif .text .extern OPENSSL_armcap_P +SYM_TEXT_SECTION($func) .globl $func .type $func,%function .align 6 @@ -285,7 +290,9 @@ $code.=<<___; ldp x29,x30,[sp],#128 ret .size $func,.-$func +SYM_TEXT_END_SECTION +SYM_TEXT_SECTION(K$BITS) .align 6 .type .LK$BITS,%object .LK$BITS: @@ -354,6 +361,8 @@ $code.=<<___ if ($SZ==4); ___ $code.=<<___; .size .LK$BITS,.-.LK$BITS +SYM_TEXT_END_SECTION + #ifndef __KERNEL__ .align 3 .LOPENSSL_armcap_P: @@ -637,6 +646,7 @@ sub body_00_15 () { } $code.=<<___; +SYM_TEXT_SECTION(sha256_block_neon) #ifdef __KERNEL__ .globl sha256_block_neon #endif @@ -736,6 +746,7 @@ $code.=<<___; add sp,sp,#16*4+16 ret .size sha256_block_neon,.-sha256_block_neon +SYM_TEXT_END_SECTION ___ } diff --git a/arch/arm64/crypto/sha512-ce-core.S b/arch/arm64/crypto/sha512-ce-core.S index b6a3a36e15f5..7d34aabb3daa 100644 --- a/arch/arm64/crypto/sha512-ce-core.S +++ b/arch/arm64/crypto/sha512-ce-core.S @@ -106,7 +106,7 @@ * int blocks) */ .text -SYM_FUNC_START(sha512_ce_transform) +SYM_FUNC_START_SECTION(sha512_ce_transform) /* load state */ ld1 {v8.2d-v11.2d}, [x0] @@ -203,4 +203,4 @@ CPU_LE( rev64 v19.16b, v19.16b ) 3: st1 {v8.2d-v11.2d}, [x0] mov w0, w2 ret -SYM_FUNC_END(sha512_ce_transform) +SYM_FUNC_END_SECTION(sha512_ce_transform) diff --git a/arch/arm64/crypto/sm3-ce-core.S b/arch/arm64/crypto/sm3-ce-core.S index ef97d3187cb7..7be60c41e36d 100644 --- a/arch/arm64/crypto/sm3-ce-core.S +++ b/arch/arm64/crypto/sm3-ce-core.S @@ -73,7 +73,7 @@ * int blocks) */ .text -SYM_FUNC_START(sm3_ce_transform) +SYM_FUNC_START_SECTION(sm3_ce_transform) /* load state */ ld1 {v8.4s-v9.4s}, [x0] rev64 v8.4s, v8.4s @@ -131,7 +131,7 @@ CPU_LE( rev32 v3.16b, v3.16b ) ext v9.16b, v9.16b, v9.16b, #8 st1 {v8.4s-v9.4s}, [x0] ret -SYM_FUNC_END(sm3_ce_transform) +SYM_FUNC_END_SECTION(sm3_ce_transform) .section ".rodata", "a" .align 3 diff --git a/arch/arm64/crypto/sm4-ce-core.S b/arch/arm64/crypto/sm4-ce-core.S index 4ac6cfbc5797..5f64ed209a26 100644 --- a/arch/arm64/crypto/sm4-ce-core.S +++ b/arch/arm64/crypto/sm4-ce-core.S @@ -15,7 +15,7 @@ * void sm4_ce_do_crypt(const u32 *rk, u32 *out, const u32 *in); */ .text -SYM_FUNC_START(sm4_ce_do_crypt) +SYM_FUNC_START_SECTION(sm4_ce_do_crypt) ld1 {v8.4s}, [x2] ld1 {v0.4s-v3.4s}, [x0], #64 CPU_LE( rev32 v8.16b, v8.16b ) @@ -33,4 +33,4 @@ CPU_LE( rev32 v8.16b, v8.16b ) CPU_LE( rev32 v8.16b, v8.16b ) st1 {v8.4s}, [x1] ret -SYM_FUNC_END(sm4_ce_do_crypt) +SYM_FUNC_END_SECTION(sm4_ce_do_crypt) From patchwork Thu Dec 2 22:32:11 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653765 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id A3C61C433EF for ; Thu, 2 Dec 2021 22:34:16 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377347AbhLBWhi (ORCPT ); Thu, 2 Dec 2021 17:37:38 -0500 Received: from mga18.intel.com ([134.134.136.126]:48270 "EHLO mga18.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1349556AbhLBWg7 (ORCPT ); Thu, 2 Dec 2021 17:36:59 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="223730467" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="223730467" Received: from fmsmga007.fm.intel.com ([10.253.24.52]) by orsmga106.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:19 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="513054743" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga007.fm.intel.com with ESMTP; 02 Dec 2021 14:33:11 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYc028552; Thu, 2 Dec 2021 22:33:09 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 11/14] module: Reorder functions Date: Thu, 2 Dec 2021 23:32:11 +0100 Message-Id: <20211202223214.72888-12-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi Introduce a new config option to allow modules to be re-ordered by function. This option can be enabled independently of the kernel text KASLR or FG_KASLR settings so that it can be used by architectures that do not support either of these features. This option will be selected by default if CONFIG_FG_KASLR is selected. If a module has functions split out into separate text sections (i.e. compiled with the -ffunction-sections flag), reorder the functions to provide some code diversification to modules. Signed-off-by: Kristen Carlson Accardi Reviewed-by: Kees Cook Acked-by: Ard Biesheuvel Tested-by: Ard Biesheuvel Reviewed-by: Tony Luck Tested-by: Tony Luck Acked-by: Jessica Yu Tested-by: Jessica Yu Reported-by: kernel test robot # swap.cocci [ alobakin: make it work with ClangCFI ] Signed-off-by: Alexander Lobakin --- Makefile | 4 ++ init/Kconfig | 12 ++++++ kernel/kallsyms.c | 4 +- kernel/livepatch/core.c | 3 +- kernel/module.c | 91 ++++++++++++++++++++++++++++++++++++++++- 5 files changed, 109 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index a4d2eac5f81f..649c309d10e2 100644 --- a/Makefile +++ b/Makefile @@ -885,6 +885,10 @@ endif # ClangLTO implies -ffunction-sections -fdata-sections, no need # to specify them manually and trigger a pointless full rebuild ifndef CONFIG_LTO_CLANG +ifdef CONFIG_MODULE_FG_KASLR +KBUILD_CFLAGS_MODULE += -ffunction-sections +endif + ifneq ($(CONFIG_LD_DEAD_CODE_DATA_ELIMINATION)$(CONFIG_FG_KASLR),) KBUILD_CFLAGS_KERNEL += -ffunction-sections endif diff --git a/init/Kconfig b/init/Kconfig index 8baeaef382c9..1f7e57d323bb 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -2360,6 +2360,18 @@ config UNUSED_KSYMS_WHITELIST one per line. The path can be absolute, or relative to the kernel source tree. +config MODULE_FG_KASLR + bool "Module Function Granular Layout Randomization" + default FG_KASLR + depends on BROKEN + help + This option randomizes the module text section by reordering the text + section by function at module load time. In order to use this + feature, the module must have been compiled with the + -ffunction-sections compiler flag. + + If unsure, say N. + endif # MODULES config MODULES_TREE_LOOKUP diff --git a/kernel/kallsyms.c b/kernel/kallsyms.c index ff9d8b651966..4ff14a94d1bd 100644 --- a/kernel/kallsyms.c +++ b/kernel/kallsyms.c @@ -861,7 +861,7 @@ static int __kallsyms_open(struct inode *inode, struct file *file) * When function granular kaslr is enabled, we need to print out the symbols * at random so we don't reveal the new layout. */ -#ifdef CONFIG_FG_KASLR +#if defined(CONFIG_FG_KASLR) || defined(CONFIG_MODULE_FG_KASLR) static int update_random_pos(struct kallsyms_shuffled_iter *s_iter, loff_t pos, loff_t *new_pos) { @@ -1005,7 +1005,7 @@ static int kallsyms_random_open(struct inode *inode, struct file *file) #define kallsyms_open kallsyms_random_open #else #define kallsyms_open __kallsyms_open -#endif /* !CONFIG_FG_KASLR */ +#endif /* !CONFIG_FG_KASLR && !CONFIG_MODULE_FG_KASLR */ #ifdef CONFIG_KGDB_KDB const char *kdb_walk_kallsyms(loff_t *pos) diff --git a/kernel/livepatch/core.c b/kernel/livepatch/core.c index 10ea75111057..8a5240b5eb5e 100644 --- a/kernel/livepatch/core.c +++ b/kernel/livepatch/core.c @@ -174,7 +174,8 @@ static int klp_find_object_symbol(const char *objname, const char *name, * to resolve symbols when there are duplicates using the previous * symbol position (i.e. sympos != 0). */ - if (IS_ENABLED(CONFIG_FG_KASLR) && sympos) { + if ((IS_ENABLED(CONFIG_FG_KASLR) || IS_ENABLED(CONFIG_MODULE_FG_KASLR)) && + sympos) { pr_err("FG-KASLR is enabled, specifying symbol position %lu for symbol '%s' in object '%s' does not work\n", sympos, name, objname ? objname : "vmlinux"); goto out_err; diff --git a/kernel/module.c b/kernel/module.c index 84a9141a5e15..48d5919d09dd 100644 --- a/kernel/module.c +++ b/kernel/module.c @@ -57,6 +57,7 @@ #include #include #include +#include #include #include "module-internal.h" @@ -1527,7 +1528,7 @@ static void free_sect_attrs(struct module_sect_attrs *sect_attrs) for (section = 0; section < sect_attrs->nsections; section++) kfree(sect_attrs->attrs[section].battr.attr.name); - kfree(sect_attrs); + kvfree(sect_attrs); } static void add_sect_attrs(struct module *mod, const struct load_info *info) @@ -1544,7 +1545,7 @@ static void add_sect_attrs(struct module *mod, const struct load_info *info) size[0] = ALIGN(struct_size(sect_attrs, attrs, nloaded), sizeof(sect_attrs->grp.bin_attrs[0])); size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.bin_attrs[0]); - sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL); + sect_attrs = kvzalloc(size[0] + size[1], GFP_KERNEL); if (sect_attrs == NULL) return; @@ -2416,6 +2417,89 @@ static bool module_init_layout_section(const char *sname) return module_init_section(sname); } +/* + * shuffle_text_list() + * Use a Fisher Yates algorithm to shuffle a list of text sections. + */ +static void shuffle_text_list(Elf_Shdr **list, int size) +{ + u32 i, j; + + for (i = size - 1; i > 0; i--) { + /* + * pick a random index from 0 to i + */ + j = get_random_u32() % (i + 1); + + swap(list[i], list[j]); + } +} + +/* + * randomize_text() + * Look through the core section looking for executable code sections. + * Store sections in an array and then shuffle the sections + * to reorder the functions. + */ +static void randomize_text(struct module *mod, struct load_info *info) +{ + int max_sections = info->hdr->e_shnum; + int num_text_sections = 0; + Elf_Shdr **text_list; + int i, size; + + text_list = kvmalloc_array(max_sections, sizeof(*text_list), GFP_KERNEL); + if (!text_list) + return; + + for (i = 0; i < max_sections; i++) { + Elf_Shdr *shdr = &info->sechdrs[i]; + const char *sname = info->secstrings + shdr->sh_name; + + if (!(shdr->sh_flags & SHF_ALLOC) || + !(shdr->sh_flags & SHF_EXECINSTR) || + (shdr->sh_flags & ARCH_SHF_SMALL) || + module_init_layout_section(sname)) + continue; + + /* + * With CONFIG_CFI_CLANG, .text with __cfi_check() must come + * before any other text sections, and be aligned to PAGE_SIZE. + * Don't include it in the shuffle list. + */ + if (IS_ENABLED(CONFIG_CFI_CLANG) && !strcmp(sname, ".text")) + continue; + + if (!num_text_sections) + size = shdr->sh_entsize; + + text_list[num_text_sections] = shdr; + num_text_sections++; + } + + if (!num_text_sections) + goto exit; + + shuffle_text_list(text_list, num_text_sections); + + for (i = 0; i < num_text_sections; i++) { + Elf_Shdr *shdr = text_list[i]; + + /* + * get_offset has a section index for it's last + * argument, that is only used by arch_mod_section_prepend(), + * which is only defined by parisc. Since this type + * of randomization isn't supported on parisc, we can + * safely pass in zero as the last argument, as it is + * ignored. + */ + shdr->sh_entsize = get_offset(mod, &size, shdr, 0); + } + +exit: + kvfree(text_list); +} + /* * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld * might -- code, read-only data, read-write data, small data. Tally @@ -2510,6 +2594,9 @@ static void layout_sections(struct module *mod, struct load_info *info) break; } } + + if (IS_ENABLED(CONFIG_MODULE_FG_KASLR)) + randomize_text(mod, info); } static void set_license(struct module *mod, const char *license) From patchwork Thu Dec 2 22:32:12 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653719 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id CCDA7C433EF for ; Thu, 2 Dec 2021 22:33:43 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377445AbhLBWhE (ORCPT ); Thu, 2 Dec 2021 17:37:04 -0500 Received: from mga03.intel.com ([134.134.136.65]:52330 "EHLO mga03.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S244743AbhLBWgo (ORCPT ); Thu, 2 Dec 2021 17:36:44 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="236795858" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="236795858" Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by orsmga103.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:20 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="655540581" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga001.fm.intel.com with ESMTP; 02 Dec 2021 14:33:13 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYd028552; Thu, 2 Dec 2021 22:33:11 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 12/14] module: use a scripted approach for FG-KASLR Date: Thu, 2 Dec 2021 23:32:12 +0100 Message-Id: <20211202223214.72888-13-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org Use the same methods and scripts to generate an LD script for every module containing all the output text sections. The only difference there is that we don't need to reserve any space as the memory for every section is being allocated dynamically. Signed-off-by: Alexander Lobakin --- .gitignore | 1 + include/asm-generic/vmlinux.lds.h | 12 ++++++++++++ init/Kconfig | 15 ++++++++++++++- scripts/Makefile.modfinal | 19 ++++++++++++++++--- scripts/generate_text_sections.pl | 9 ++++++++- scripts/module.lds.S | 14 +++++++++++++- 6 files changed, 64 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 7afd412dadd2..a39d0eb87395 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ *.gz *.i *.ko +*.lds *.lex.c *.ll *.lst diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h index 8ddc08baf50c..13718807c027 100644 --- a/include/asm-generic/vmlinux.lds.h +++ b/include/asm-generic/vmlinux.lds.h @@ -127,6 +127,18 @@ #define TEXT_MAIN .text #endif +/* + * Same for modules. However, LD_DEAD_CODE_DATA_ELIMINATION doesn't touch + * them, so no need to check for it here. + */ +#if defined(CONFIG_LTO_CLANG) && !defined(CONFIG_MODULE_FG_KASLR) +#define TEXT_MAIN_MODULE .text .text.[0-9a-zA-Z_]* +#elif defined(CONFIG_MODULE_FG_KASLR) +#define TEXT_MAIN_MODULE .text.__unused__ +#else +#define TEXT_MAIN_MODULE .text +#endif + /* * Used by scripts/generate_text_sections.pl to inject text sections, * harmless if FG-KASLR is disabled. diff --git a/init/Kconfig b/init/Kconfig index 1f7e57d323bb..1cbd0ffcb6c0 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -2363,7 +2363,6 @@ config UNUSED_KSYMS_WHITELIST config MODULE_FG_KASLR bool "Module Function Granular Layout Randomization" default FG_KASLR - depends on BROKEN help This option randomizes the module text section by reordering the text section by function at module load time. In order to use this @@ -2372,6 +2371,20 @@ config MODULE_FG_KASLR If unsure, say N. +config MODULE_FG_KASLR_SHIFT + int "Module FG-KASLR granularity (functions per section shift)" + depends on MODULE_FG_KASLR + range 0 16 + default 0 + help + This sets the number of functions that will be put in each section + as a power of two. + Decreasing the value increases the randomization, but also increases + the size of the final kernel module due to the amount of sections. + 0 means that a separate section will be created for each function. + 16 almost disables the randomization, leaving only the manual + separation. + endif # MODULES config MODULES_TREE_LOOKUP diff --git a/scripts/Makefile.modfinal b/scripts/Makefile.modfinal index 7f39599e9fae..9353ce78a74e 100644 --- a/scripts/Makefile.modfinal +++ b/scripts/Makefile.modfinal @@ -28,13 +28,24 @@ quiet_cmd_cc_o_c = CC [M] $@ %.mod.o: %.mod.c FORCE $(call if_changed_dep,cc_o_c) +ifdef CONFIG_MODULE_FG_KASLR +quiet_cmd_gen_modules_lds = GEN [M] $@ + cmd_gen_modules_lds = \ + $(PERL) $(srctree)/scripts/generate_text_sections.pl \ + -s $(CONFIG_MODULE_FG_KASLR_SHIFT) $(filter %.o, $^) \ + < $(filter %.lds, $^) > $@ + +%.lds: %$(mod-prelink-ext).o scripts/module.lds FORCE + $(call if_changed,gen_modules_lds) +endif + ARCH_POSTLINK := $(wildcard $(srctree)/arch/$(SRCARCH)/Makefile.postlink) quiet_cmd_ld_ko_o = LD [M] $@ cmd_ld_ko_o += \ $(LD) -r $(KBUILD_LDFLAGS) \ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ - -T scripts/module.lds -o $@ $(filter %.o, $^); \ + -T $(filter %.lds, $^) -o $@ $(filter %.o, $^); \ $(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true) quiet_cmd_btf_ko = BTF [M] $@ @@ -56,13 +67,15 @@ if_changed_except = $(if $(call newer_prereqs_except,$(2))$(cmd-check), \ # Re-generate module BTFs if either module's .ko or vmlinux changed -$(modules): %.ko: %$(mod-prelink-ext).o %.mod.o scripts/module.lds $(if $(KBUILD_BUILTIN),vmlinux) FORCE +$(modules): %.ko: %$(mod-prelink-ext).o %.mod.o +$(modules): %.ko: $(if $(CONFIG_MODULE_FG_KASLR),%.lds,scripts/module.lds) +$(modules): %.ko: $(if $(KBUILD_BUILTIN),vmlinux) FORCE +$(call if_changed_except,ld_ko_o,vmlinux) ifdef CONFIG_DEBUG_INFO_BTF_MODULES +$(if $(newer-prereqs),$(call cmd,btf_ko)) endif -targets += $(modules) $(modules:.ko=.mod.o) +targets += $(modules) $(modules:.ko=.mod.o) $(if $(CONFIG_MODULE_FG_KASLR),$(modules:.ko=.lds)) # Add FORCE to the prequisites of a target to force it to be always rebuilt. # --------------------------------------------------------------------------- diff --git a/scripts/generate_text_sections.pl b/scripts/generate_text_sections.pl index 6871045fb7a6..d4c5614d9481 100755 --- a/scripts/generate_text_sections.pl +++ b/scripts/generate_text_sections.pl @@ -45,6 +45,7 @@ my $readelf = $ENV{'READELF'} || die "$0: ERROR: READELF not set?"; ## text sections array my @sections = (); my $has_ccf = 0; +my $vmlinux = 0; ## max alignment found to reserve some space my $max_align = 64; @@ -73,6 +74,12 @@ sub read_sections { $has_ccf = 1; } + ## If we're processing a module, don't reserve any space + ## at the end as its sections are being allocated separately. + if ($name eq ".sched.text") { + $vmlinux = 1; + } + if (!($name =~ /^\.text\.[0-9a-zA-Z_]*((\.constprop|\.isra|\.part)\.[0-9])*(|\.[0-9cfi]*)$/)) { next; } @@ -132,7 +139,7 @@ sub print_reserve { ## If we have text sections aligned with 64 bytes or more, make ## sure we reserve some space for them to not overlap _etext ## while shuffling sections. - if (!$count) { + if (!$vmlinux or !$count) { return; } diff --git a/scripts/module.lds.S b/scripts/module.lds.S index 1d0e1e4dc3d2..6e957aa614b1 100644 --- a/scripts/module.lds.S +++ b/scripts/module.lds.S @@ -3,6 +3,11 @@ * Archs are free to supply their own linker scripts. ld will * combine them automatically. */ + +#include + +#undef SANITIZER_DISCARDS + #ifdef CONFIG_CFI_CLANG # include # define ALIGN_CFI ALIGN(PAGE_SIZE) @@ -58,9 +63,16 @@ SECTIONS { */ .text : ALIGN_CFI { *(.text.__cfi_check) - *(.text .text.[0-9a-zA-Z_]* .text..L.cfi*) + *(TEXT_MAIN_MODULE) + *(.text..L.cfi.jumptable .text..L.cfi.jumptable.*) + } +#elif defined(CONFIG_MODULE_FG_KASLR) + .text : { + *(TEXT_MAIN_MODULE) } #endif + + TEXT_FG_KASLR } /* bring in arch-specific sections */ From patchwork Thu Dec 2 22:32:13 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653721 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id D9100C433FE for ; Thu, 2 Dec 2021 22:33:48 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377498AbhLBWhL (ORCPT ); Thu, 2 Dec 2021 17:37:11 -0500 Received: from mga09.intel.com ([134.134.136.24]:47741 "EHLO mga09.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S243146AbhLBWgq (ORCPT ); Thu, 2 Dec 2021 17:36:46 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="236669315" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="236669315" Received: from fmsmga004.fm.intel.com ([10.253.24.48]) by orsmga102.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:22 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="576948161" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga004.fm.intel.com with ESMTP; 02 Dec 2021 14:33:15 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYe028552; Thu, 2 Dec 2021 22:33:12 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 13/14] Documentation: add documentation for FG-KASLR Date: Thu, 2 Dec 2021 23:32:13 +0100 Message-Id: <20211202223214.72888-14-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org From: Kristen Carlson Accardi Describe the main principles behind the FG-KASLR hardening feature in a new doc section. Signed-off-by: Kristen Carlson Accardi Signed-off-by: Alexander Lobakin --- .../admin-guide/kernel-parameters.txt | 6 + Documentation/security/fgkaslr.rst | 172 ++++++++++++++++++ Documentation/security/index.rst | 1 + 3 files changed, 179 insertions(+) create mode 100644 Documentation/security/fgkaslr.rst diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 9725c546a0d4..3940b8610140 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -2224,6 +2224,12 @@ kernel and module base offset ASLR (Address Space Layout Randomization). + nofgkaslr [KNL] + When CONFIG_FG_KASLR is set, this parameter + disables kernel function granular ASLR + (Address Space Layout Randomization). + See Documentation/security/fgkaslr.rst. + kasan_multi_shot [KNL] Enforce KASAN (Kernel Address Sanitizer) to print report on every invalid memory access. Without this diff --git a/Documentation/security/fgkaslr.rst b/Documentation/security/fgkaslr.rst new file mode 100644 index 000000000000..50dc24f675b5 --- /dev/null +++ b/Documentation/security/fgkaslr.rst @@ -0,0 +1,172 @@ +.. SPDX-License-Identifier: GPL-2.0 + +===================================================================== +Function Granular Kernel Address Space Layout Randomization (fgkaslr) +===================================================================== + +:Date: 6 April 2020 +:Author: Kristen Accardi + +Kernel Address Space Layout Randomization (KASLR) was merged into the kernel +with the objective of increasing the difficulty of code reuse attacks. Code +reuse attacks reused existing code snippets to get around existing memory +protections. They exploit software bugs which expose addresses of useful code +snippets to control the flow of execution for their own nefarious purposes. +KASLR as it was originally implemented moves the entire kernel code text as a +unit at boot time in order to make addresses less predictable. The order of the +code within the segment is unchanged - only the base address is shifted. There +are a few shortcomings to this algorithm. + +1. Low Entropy - there are only so many locations the kernel can fit in. This + means an attacker could guess without too much trouble. +2. Knowledge of a single address can reveal the offset of the base address, + exposing all other locations for a published/known kernel image. +3. Info leaks abound. + +Finer grained ASLR has been proposed as a way to make ASLR more resistant +to info leaks. It is not a new concept at all, and there are many variations +possible. Function reordering is an implementation of finer grained ASLR +which randomizes the layout of an address space on a function level +granularity. The term "fgkaslr" is used in this document to refer to the +technique of function reordering when used with KASLR, as well as finer grained +KASLR in general. + +The objective of this patch set is to improve a technology that is already +merged into the kernel (KASLR). This code will not prevent all code reuse +attacks, and should be considered as one of several tools that can be used. + +Implementation Details +====================== + +The over-arching objective of the fgkaslr implementation is incremental +improvement over the existing KASLR algorithm. It is designed to work with +the existing solution, and there are two main area where code changes occur: +Build time, and Load time. + +Build time +---------- + +GCC has had an option to place functions into individual .text sections +for many years now (-ffunction-sections). This option is used to implement +function reordering at load time. The final compiled vmlinux retains all the +section headers, which can be used to help find the address ranges of each +function. Using this information and an expanded table of relocation addresses, +individual text sections can be shuffled immediately after decompression. +Some data tables inside the kernel that have assumptions about order +require sorting after the update. In order to modify these tables, +a few key symbols from the objcopy symbol stripping process are preserved +for use after shuffling the text segments. Any special input sections which are +defined by the kernel build process and collected into the .text output +segment are left unmodified and will still be present inside the .text segment, +unrandomized other than normal base address randomization. + +Load time +--------- + +The boot kernel was modified to parse the vmlinux elf file after +decompression to check for symbols for modifying data tables, and to +look for any .text.* sections to randomize. The sections are then shuffled, +and tables are updated or resorted. The existing code which updated relocation +addresses was modified to account for not just a fixed delta from the load +address, but the offset that the function section was moved to. This requires +inspection of each address to see if it was impacted by a randomization. + +In order to hide the new layout, symbols reported through /proc/kallsyms will +be displayed in a random order. + +Performance Impact +================== + +There are two areas where function reordering can impact performance: boot +time latency, and run time performance. + +Boot time latency +----------------- + +This implementation of finer grained KASLR impacts the boot time of the kernel +in several places. It requires additional parsing of the kernel ELF file to +obtain the section headers of the sections to be randomized. It calls the +random number generator for each section to be randomized to determine that +section's new memory location. It copies the decompressed kernel into a new +area of memory to avoid corruption when laying out the newly randomized +sections. It increases the number of relocations the kernel has to perform at +boot time vs. standard KASLR, and it also requires a lookup on each address +that needs to be relocated to see if it was in a randomized section and needs +to be adjusted by a new offset. Finally, it re-sorts a few data tables that +are required to be sorted by address. + +Booting a test VM on a modern, well appointed system showed an increase in +latency of approximately 1 second. + +Run time +-------- + +The performance impact at run-time of function reordering varies by workload. +Randomly reordering the functions will cause an increase in cache misses +for some workloads. Some workloads perform significantly worse under FGKASLR, +while others stay the same or even improve. In general, it will depend on the +code flow whether or not finer grained KASLR will impact a workload, and how +the underlying code was designed. Because the layout changes per boot, each +time a system is rebooted the performance of a workload may change. + +Image Size +========== + +fgkaslr increases the size of the kernel binary due to the extra section +headers that are included, as well as the extra relocations that need to +be added. You can expect fgkaslr to increase the size of the resulting +vmlinux by about 3%, and the compressed image (bzImage) by 15%. + +Memory Usage +============ + +fgkaslr increases the amount of heap that is required at boot time, +although this extra memory is released when the kernel has finished +decompression. As a result, it may not be appropriate to use this feature +on systems without much memory. + +Building +======== + +To enable fine grained KASLR, you need to have the following config options +set (including all the ones you would use to build normal KASLR) + +``CONFIG_FG_KASLR=y`` + +fgkaslr for the kernel is only supported for the X86_64 architecture. + +Modules +======= + +Modules are randomized similarly to the rest of the kernel by shuffling +the sections at load time prior to moving them into memory. The module must +also have been build with the -ffunction-sections compiler option. + +Although fgkaslr for the kernel is only supported for the X86_64 architecture, +it is possible to use fgkaslr with modules on other architectures. To enable +this feature, select the following config option: + +``CONFIG_MODULE_FG_KASLR`` + +This option is selected automatically for X86_64 when CONFIG_FG_KASLR is set. + +Disabling +========= + +Disabling normal kaslr using the nokaslr command line option also disables +fgkaslr. In addition, it is possible to disable fgkaslr separately by booting +with "nofgkaslr" on the commandline. + +Further Information +=================== + +There are a lot of academic papers which explore finer grained ASLR. +This paper in particular contributed significantly to the implementation design. + +Selfrando: Securing the Tor Browser against De-anonymization Exploits, +M. Conti, S. Crane, T. Frassetto, et al. + +For more information on how function layout impacts performance, see: + +Optimizing Function Placement for Large-Scale Data-Center Applications, +G. Ottoni, B. Maher diff --git a/Documentation/security/index.rst b/Documentation/security/index.rst index 16335de04e8c..41444124090f 100644 --- a/Documentation/security/index.rst +++ b/Documentation/security/index.rst @@ -7,6 +7,7 @@ Security Documentation credentials IMA-templates + fgkaslr keys/index lsm lsm-development From patchwork Thu Dec 2 22:32:14 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alexander Lobakin X-Patchwork-Id: 12653763 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 534A2C433EF for ; Thu, 2 Dec 2021 22:33:58 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1377543AbhLBWhS (ORCPT ); Thu, 2 Dec 2021 17:37:18 -0500 Received: from mga17.intel.com ([192.55.52.151]:46501 "EHLO mga17.intel.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1349757AbhLBWgr (ORCPT ); Thu, 2 Dec 2021 17:36:47 -0500 X-IronPort-AV: E=McAfee;i="6200,9189,10186"; a="217546806" X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="217546806" Received: from fmsmga005.fm.intel.com ([10.253.24.32]) by fmsmga107.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 02 Dec 2021 14:33:24 -0800 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.87,282,1631602800"; d="scan'208";a="748394126" Received: from irvmail001.ir.intel.com ([10.43.11.63]) by fmsmga005.fm.intel.com with ESMTP; 02 Dec 2021 14:33:17 -0800 Received: from newjersey.igk.intel.com (newjersey.igk.intel.com [10.102.20.203]) by irvmail001.ir.intel.com (8.14.3/8.13.6/MailSET/Hub) with ESMTP id 1B2MWmYf028552; Thu, 2 Dec 2021 22:33:14 GMT From: Alexander Lobakin To: linux-hardening@vger.kernel.org, x86@kernel.org Cc: Alexander Lobakin , Jesse Brandeburg , Kristen Carlson Accardi , Kees Cook , Miklos Szeredi , Ard Biesheuvel , Tony Luck , Bruce Schlobohm , Jessica Yu , kernel test robot , Miroslav Benes , Evgenii Shatokhin , Jonathan Corbet , Masahiro Yamada , Michal Marek , Nick Desaulniers , Herbert Xu , "David S. Miller" , Thomas Gleixner , Will Deacon , Ingo Molnar , Borislav Petkov , Dave Hansen , "H. Peter Anvin" , Andy Lutomirski , Peter Zijlstra , Arnd Bergmann , Josh Poimboeuf , Nathan Chancellor , Masami Hiramatsu , Marios Pomonis , Sami Tolvanen , linux-kernel@vger.kernel.org, linux-kbuild@vger.kernel.org, linux-arch@vger.kernel.org, live-patching@vger.kernel.org, llvm@lists.linux.dev Subject: [PATCH v8 14/14] maintainers: add MAINTAINERS entry for FG-KASLR Date: Thu, 2 Dec 2021 23:32:14 +0100 Message-Id: <20211202223214.72888-15-alexandr.lobakin@intel.com> X-Mailer: git-send-email 2.33.1 In-Reply-To: <20211202223214.72888-1-alexandr.lobakin@intel.com> References: <20211202223214.72888-1-alexandr.lobakin@intel.com> MIME-Version: 1.0 Precedence: bulk List-ID: X-Mailing-List: linux-kbuild@vger.kernel.org Add an entry for FG-KASLR containing the maintainers, reviewers, public mailing lists, files and so on. Signed-off-by: Alexander Lobakin --- MAINTAINERS | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 360e9aa0205d..336cae4c08b4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7853,6 +7853,18 @@ L: platform-driver-x86@vger.kernel.org S: Maintained F: drivers/platform/x86/fujitsu-tablet.c +FUNCTION-GRAINED KASLR (FG-KASLR) +M: Alexander Lobakin +R: Kristen Carlson Accardi +R: Kees Cook +L: linux-hardening@vger.kernel.org +S: Supported +F: Documentation/security/fgkaslr.rst +F: arch/x86/boot/compressed/fgkaslr.c +F: arch/x86/boot/compressed/utils.c +F: arch/x86/boot/compressed/vmlinux.symbols +F: scripts/generate_text_sections.pl + FUSE: FILESYSTEM IN USERSPACE M: Miklos Szeredi L: linux-fsdevel@vger.kernel.org