[2/3] x86/ptrace: Reject system segements

Message ID 20231213163443.70490-3-brgerst@gmail.com
State New
Headers
Series Reject setting system segments from userspace |

Commit Message

Brian Gerst Dec. 13, 2023, 4:34 p.m. UTC
  Do not allow system segments (TSS and LDT) from being poked into segment
registers via ptrace.  Loading these segments into a segment register
normally results in a general protection fault.  But in the case of
ptrace, setting CS or SS to a system segment will cause IRET to fault.
This then results in the instruction decoder attempting to use the
invalid segment.  This can be avoided by rejecting system segments in
PTRACE_SETREGS.

Signed-off-by: Brian Gerst <brgerst@gmail.com>
Reported-By: Michal Luczaj <mhal@rbox.co>
Link: https://lore.kernel.org/lkml/20231206004654.2986026-1-mhal@rbox.co/
---
 arch/x86/include/asm/segment.h | 11 +++++++++++
 arch/x86/kernel/ptrace.c       | 12 ++----------
 2 files changed, 13 insertions(+), 10 deletions(-)
  

Patch

diff --git a/arch/x86/include/asm/segment.h b/arch/x86/include/asm/segment.h
index a155843d0c37..ede1fa5aa4cc 100644
--- a/arch/x86/include/asm/segment.h
+++ b/arch/x86/include/asm/segment.h
@@ -359,6 +359,17 @@  static inline void __loadsegment_fs(unsigned short value)
 #define savesegment(seg, value)				\
 	asm("mov %%" #seg ",%0":"=r" (value) : : "memory")
 
+/*
+ * Determines whether a value may be installed in a segment register.
+ */
+static inline bool valid_user_selector(u16 value)
+{
+	if (unlikely(!(value & SEGMENT_TI_MASK) && value >= (GDT_SYSTEM_START * 8)))
+		return false;
+
+	return likely(value == 0 || (value & SEGMENT_RPL_MASK) == USER_RPL);
+}
+
 #endif /* !__ASSEMBLY__ */
 #endif /* __KERNEL__ */
 
diff --git a/arch/x86/kernel/ptrace.c b/arch/x86/kernel/ptrace.c
index 095f04bdabdc..4c3a2278691e 100644
--- a/arch/x86/kernel/ptrace.c
+++ b/arch/x86/kernel/ptrace.c
@@ -162,14 +162,6 @@  const char *regs_query_register_name(unsigned int offset)
 				  X86_EFLAGS_DF | X86_EFLAGS_OF |	\
 				  X86_EFLAGS_RF | X86_EFLAGS_AC))
 
-/*
- * Determines whether a value may be installed in a segment register.
- */
-static inline bool invalid_selector(u16 value)
-{
-	return unlikely(value != 0 && (value & SEGMENT_RPL_MASK) != USER_RPL);
-}
-
 #ifdef CONFIG_X86_32
 
 #define FLAG_MASK		FLAG_MASK_32
@@ -206,7 +198,7 @@  static int set_segment_reg(struct task_struct *task,
 	/*
 	 * The value argument was already truncated to 16 bits.
 	 */
-	if (invalid_selector(value))
+	if (!valid__user_selector(value))
 		return -EIO;
 
 	/*
@@ -296,7 +288,7 @@  static int set_segment_reg(struct task_struct *task,
 	/*
 	 * The value argument was already truncated to 16 bits.
 	 */
-	if (invalid_selector(value))
+	if (!valid_user_selector(value))
 		return -EIO;
 
 	/*