Skip to contentSkip to conversation

KVM: x86: Add more protection against undefined behavior in rsvd_bits()

PATCH Applied Sean Christopherson 2 participants 2 messages Jan 13, 2021 – Jan 18, 2021

Subsystems (3)
lore
Share & tools
lore

Sean Christopherson

author maintainer
#0 lore raw

PATCH 1/1 KVM: x86: Add more protection against undefined behavior in rsvd_bits()

Add compile-time asserts in rsvd_bits() to guard against KVM passing in garbage hardcoded values, and cap the upper bound at '63' for dynamic values to prevent generating a mask that would overflow a u64.

---
 arch/x86/kvm/mmu.h | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu.h +8 -1
index 581925e476d6..261be1d2032b 100644
@@ -44,8 +44,15 @@
 #define PT32_ROOT_LEVEL 2
 #define PT32E_ROOT_LEVEL 3
 
-static inline u64 rsvd_bits(int s, int e)
+static __always_inline u64 rsvd_bits(int s, int e)
 {
+	BUILD_BUG_ON(__builtin_constant_p(e) && __builtin_constant_p(s) && e < s);
+
+	if (__builtin_constant_p(e))
+		BUILD_BUG_ON(e > 63);
+	else
+		e &= 63;
+
 	if (e < s)
 		return 0;
 
Signature · 1 line
2.30.0.284.gd98b1dd5eaa7-goog
maintainer Applied
#1 lore raw
Quoted 22 lines · Sean Christopherson

Add compile-time asserts in rsvd_bits() to guard against KVM passing in garbage hardcoded values, and cap the upper bound at '63' for dynamic values to prevent generating a mask that would overflow a u64.

---
  arch/x86/kvm/mmu.h | 9 ++++++++-
  1 file changed, 8 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu.h +1 -1
index 581925e476d6..261be1d2032b 100644
@@ -44,8 +44,15 @@
  #define PT32_ROOT_LEVEL 2
  #define PT32E_ROOT_LEVEL 3
 
-static inline u64 rsvd_bits(int s, int e)
+static __always_inline u64 rsvd_bits(int s, int e)
  {

arch/x86/kvm/mmu.h line 58

Quoted 10 lines
arch/x86/kvm/mmu.h +7 -0
+	BUILD_BUG_ON(__builtin_constant_p(e) && __builtin_constant_p(s) && e < s);
+
+	if (__builtin_constant_p(e))
+		BUILD_BUG_ON(e > 63);
+	else
+		e &= 63;
+
  	if (e < s)
  		return 0;
 

Queued for 5.11, thanks.

Paolo