Skip to contentSkip to conversation

Guest introspection

RFC PATCH In review Adalbert Lazar 5 participants 38 messages Jun 16, 2017 – Jun 27, 2017

Subsystems (6)
Memory management x86 KVM MM core +2 more subsystems
lore
Share & tools
lore
#0 lore raw

cover Guest introspection

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

In order to control the guests, we found that the following list of introspection commands/events is required:

Commands - messages sent from introspection tool to KVMi
========

- KVMI_GET_GUEST_INFO

Get the number of online VCPUs and the TSC speed.

- KVMI_PAUSE_GUEST, KVMI_UNPAUSE_GUEST

Pause/unpause all VCPUs.

- KVMI_SHUTDOWN_GUEST

- KVMI_GET_REGISTERS

Get general purpose, special and a small subset of MSRs (the ones controlling the syscall behaviour).

- KVMI_SET_REGISTERS

Set the general purpose registers.

- KVMI_GET_MTRR_TYPE

Get the guest memory type for a specific physical address.

- KVMI_GET_MTRRS

Get MSR_IA32_CR_PAT, MSR_MTRRcap and MSR_MTRRdefType.

- KVMI_GET_XSAVE_INFO

	Get vcpu->arch.guest_xstate_size.

- KVMI_GET_PAGE_ACCESS, KVMI_SET_PAGE_ACCESS

Get/set the spte flags (rwx - present, write & user).

- KVMI_INJECT_PAGE_FAULT, KVMI_INJECT_BREAKPOINT

Used to instruct the OS to do a page in

- KVMI_READ_PHYSICAL, KVMI_WRITE_PHYSICAL

- KVMI_MAP_PHYSICAL_PAGE_TO_SVA, KVMI_UNMAP_PHYSICAL_PAGE_FROM_SVA

A faster alternative to read/write messages (above).

- KVMI_EVENT_CONTROL

Enable event reports (see the event list bellow).

- KVMI_CR_CONTROL, KVMI_MSR_CONTROL

Filter VCPUs events regarding CR and MSR registers (if enabled with KVMI_EVENT_CONTROL).

Events - messages sent from KVMi to introspection tool
======

- KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF

Send the guest UUID.
On KVMI_EVENT_GUEST_ON, the introspection tool connects back with the UUID, in order to establish a control channel for this guest.

- KVMI_EVENT_VCPU

This message is used to send one of the following events (if enabled with KVMI_EVENT_CONTROL - see above), together with the registers (see KVMI_GET_REGISTERS). The introspection tool can reply with the KVMI_EVENT_SET_REGS flag set and provide new values for the registers, as with the KVMI_SET_REGISTERS command.

- KVMI_EVENT_CR

A CR register was modified. If the event reporting for this specific CR was enabled with KVMI_CR_CONTROL, send a message to the introspection tool with the CR number, the old value, the new value, and wait for a reply with one or more actions/flags:

+ KVMI_EVENT_ALLOW (allow the new value to be set)
+ KVMI_EVENT_SET_REGS (override the registers)

otherwise, block this modification.

- KVMI_EVENT_MSR

Similar with KVMI_EVENT_CR. Filtered with KVMI_MSR_CONTROL.

- KVMI_EVENT_XSETBV

An extended control register was modified. Send the value. The introspection tool can reply with KVMI_EVENT_SET_REGS.

- KVMI_EVENT_BREAKPOINT

A breakpoint was reached. Send the guest address. The introspection tool can reply with KVMI_EVENT_SET_REGS and KVMI_EVENT_ALLOW.

- KVMI_EVENT_USER_CALL

User hypercall.
The introspection tool can reply with KVMI_EVENT_SET_REGS.

- KVMI_EVENT_TRAP

A trap will be delivered to the guest (#PF, INT3 etc.). The introspection tool can reply with KVMI_EVENT_SET_REGS.

- KVMI_EVENT_PAGE_FAULT

A hypervisor page fault was encountered.
The introspection tool can reply with:
+ KVMI_EVENT_ALLOW (otherwise EMULATE_FAIL will be returned)
+ KVMI_EVENT_NOEMU (EMULATE_DONE)
+ KVMI_EVENT_SET_REGS
+ KVMI_EVENT_SET_CTX (change the emulation context)

The control channels are handled by workqueue jobs, receiving messages from the introspection tool and signaling the proper VCPU threads to act on the message.

Currently, all the commands will pause/unpause the guest, but we will like to avoid this when possible.

This patch series is not complete. Your input would be greatly appreciated.

Adalbert Lazar (2):
kvm: Add the introspection subsystem
kvm: x86: Handle KVM_REQ_INTROSPECTION

Mihai Dontu (17):
kvm: x86: mmu: Add kvm_mmu_get_spte() and kvm_mmu_set_spte()
kvm: x86: Add kvm_arch_vcpu_set_regs()
mm: Add vm_replace_page()
kvm: Add kvm_enum()
kvm: Add uuid member in struct kvm + support for KVM_CAP_VM_UUID
kvm: Add kvm_vm_shutdown()
kvm: x86: Add kvm_arch_msr_intercept()
kvm: Hook in kvmi on VM on/off events
kvm: vmx: Hook in kvmi_page_fault()
kvm: x86: Hook in kvmi_breakpoint_event()
kvm: x86: Hook in kvmi_trap_event()
kvm: x86: Hook in kvmi_cr_event()
kvm: x86: Hook in kvmi_xsetbv_event()
kvm: x86: Hook in kvmi_msr_event()
kvm: x86: Change the emulation context
kvm: x86: Hook in kvmi_vmcall_event()
kvm: x86: Set the new spte flags before entering the guest

 arch/x86/include/asm/kvm_host.h |   11 +-
 arch/x86/kvm/Kconfig            |    2 +
 arch/x86/kvm/Makefile           |    1 +
 arch/x86/kvm/mmu.c              |  126 ++-
 arch/x86/kvm/mmu.h              |    3 +
 arch/x86/kvm/svm.c              |   10 +
 arch/x86/kvm/vmx.c              |   79 +-
 arch/x86/kvm/x86.c              |  148 ++-
 include/linux/kvm_host.h        |   36 +
 include/linux/mm.h              |    1 +
 include/uapi/linux/kvm.h        |    2 +
 include/uapi/linux/kvm_para.h   |    4 +
 include/uapi/linux/kvmi.h       |  263 +++++
 mm/memory.c                     |   69 ++
 virt/kvm/kvm_main.c             |   81 ++
 virt/kvm/kvmi.c                 | 2252 +++++++++++++++++++++++++++++++++++++++
 virt/kvm/kvmi.h                 |   42 +
 virt/kvm/kvmi_socket.c          |  412 +++++++
 virt/kvm/kvmi_socket.h          |   33 +
 19 files changed, 3566 insertions(+), 9 deletions(-)
 create mode 100644 include/uapi/linux/kvmi.h
 create mode 100644 virt/kvm/kvmi.c
 create mode 100644 virt/kvm/kvmi.h
 create mode 100644 virt/kvm/kvmi_socket.c
 create mode 100644 virt/kvm/kvmi_socket.h
Signature · 1 line
2.12.2
#1 lore raw

RFC PATCH 1/19 kvm: x86: mmu: Add kvm_mmu_get_spte() and kvm_mmu_set_spte()

From: Mihai Dontu <[email protected]>

These are helpers used by the introspection subsystem to adjust the SPTE rwx flags. At present, the code assumes we're deadling with 4-level hardware shadow page tables.

---
 arch/x86/kvm/mmu.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu.h |  3 +++
 2 files changed, 78 insertions(+)
arch/x86/kvm/mmu.c +75 -0
index cb8225969255..12e4c33ff879 100644
@@ -5350,3 +5350,78 @@ void kvm_mmu_module_exit(void)
 	unregister_shrinker(&mmu_shrinker);
 	mmu_audit_disable();
 }
+
+u64 kvm_mmu_get_spte(struct kvm *kvm, struct kvm_vcpu *vcpu, gpa_t gpa)
+{
+	u64 spte = -1;
+	unsigned int c = 0;
+	const u64 mask = PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
+	struct kvm_shadow_walk_iterator iterator;
+
+	spin_lock(&kvm->mmu_lock);
+	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
+		goto error;
+	for_each_shadow_entry(vcpu, gpa & PAGE_MASK, iterator) {
+		u64 __spte = *iterator.sptep;
+
+		if (!(__spte & mask))
+			break;
+		else if (++c == PT64_ROOT_LEVEL) {
+			spte = __spte;
+			break;
+		}
+	}
+	if (spte == (u64) -1)
+		goto error;
+	spin_unlock(&kvm->mmu_lock);
+	return spte & mask;
+error:
+	spin_unlock(&kvm->mmu_lock);
+	return -ENOENT;
+}
+
+int kvm_mmu_set_spte(struct kvm *kvm, struct kvm_vcpu *vcpu, gpa_t gpa,
+		     unsigned int r, unsigned int w, unsigned int x)
+{
+	int flush = 0;
+	u64 *pspte[4] = { };
+	u64 spte;
+	u64 old_spte;
+	unsigned int c = 0;
+	const u64 mask = PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
+	struct kvm_shadow_walk_iterator iterator;
+
+	spin_lock(&kvm->mmu_lock);
+	if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
+		goto error;
+	for_each_shadow_entry(vcpu, gpa & PAGE_MASK, iterator) {
+		u64 __spte = *iterator.sptep;
+
+		if (!(__spte & mask))
+			break;
+		pspte[c++] = iterator.sptep;
+	}
+	if (c < PT64_ROOT_LEVEL || !pspte[c - 1])
+		goto error;
+	c--;
+	old_spte = *pspte[c];
+	spte = old_spte & ~mask;
+	if (r)
+		spte |= PT_PRESENT_MASK;
+	if (w)
+		spte |= PT_WRITABLE_MASK;
+	if (x)
+		spte |= PT_USER_MASK;
+	if (old_spte != spte)
+		flush |= mmu_spte_update(pspte[c], spte);
+	while (c-- > 0) {
+		spte = *pspte[c];
+		if ((spte & mask) != mask)
+			flush |= mmu_spte_update(pspte[c], spte | mask);
+	}
+	spin_unlock(&kvm->mmu_lock);
+	return flush;
+error:
+	spin_unlock(&kvm->mmu_lock);
+	return -ENOENT;
+}
arch/x86/kvm/mmu.h +3 -0
index 330bf3a811fb..82246fdc0479 100644
@@ -204,4 +204,7 @@ void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn);
 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
 				    struct kvm_memory_slot *slot, u64 gfn);
 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu);
+u64 kvm_mmu_get_spte(struct kvm *kvm, struct kvm_vcpu *vcpu, gpa_t gpa);
+int kvm_mmu_set_spte(struct kvm *kvm, struct kvm_vcpu *vcpu, gpa_t gpa,
+		     unsigned int r, unsigned int w, unsigned int x);
 #endif
Signature · 1 line
2.12.2
#2 lore raw

RFC PATCH 2/19 kvm: x86: Add kvm_arch_vcpu_set_regs()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

This is a version of kvm_arch_vcpu_ioctl_set_regs() which does not touch the exceptions vector.

---
 arch/x86/kvm/x86.c       | 34 ++++++++++++++++++++++++++++++++++
 include/linux/kvm_host.h |  1 +
 2 files changed, 35 insertions(+)
arch/x86/kvm/x86.c +34 -0
index 87d3cb901935..1a7493982310 100644
@@ -7291,6 +7291,40 @@ int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
 	return 0;
 }
 
+/*
+ * Similar to kvm_arch_vcpu_ioctl_set_regs() but it does not reset
+ * the exceptions
+ */
+void kvm_arch_vcpu_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
+{
+	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
+	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
+
+	kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
+	kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
+	kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
+	kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
+	kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
+	kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
+	kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
+	kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
+#ifdef CONFIG_X86_64
+	kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
+	kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
+	kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
+	kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
+	kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
+	kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
+	kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
+	kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
+#endif
+
+	kvm_rip_write(vcpu, regs->rip);
+	kvm_set_rflags(vcpu, regs->rflags);
+
+	kvm_make_request(KVM_REQ_EVENT, vcpu);
+}
+
 void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
 {
 	struct kvm_segment cs;
include/linux/kvm_host.h +1 -0
index 8c0664309815..48cd2d856132 100644
@@ -748,6 +748,7 @@ int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
 
 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
+void kvm_arch_vcpu_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
 				  struct kvm_sregs *sregs);
 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
Signature · 1 line
2.12.2
#3 lore raw

RFC PATCH 3/19 mm: Add vm_replace_page()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

This function is used to get two processes to share a page. It's inspired by replace_page() from KSM.

---
 include/linux/mm.h |  1 +
 mm/memory.c        | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)
include/linux/mm.h +1 -0
index b892e95d4929..9cd088ef9d0c 100644
@@ -2296,6 +2296,7 @@ int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
 			unsigned long pfn, pgprot_t pgprot);
 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
 			pfn_t pfn);
+int vm_replace_page(struct vm_area_struct *vma, struct page *page);
 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len);
 
 
mm/memory.c +69 -0

75 lines not on this page · raw message

Signature · 1 line
2.12.2
#4 lore raw

RFC PATCH 4/19 kvm: Add kvm_enum()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

This is a helper used by the introspection subsystem to find a specific VM by UUID or to build a list of UUIDs.

---
 include/linux/kvm_host.h |  2 ++
 virt/kvm/kvm_main.c      | 12 ++++++++++++
 2 files changed, 14 insertions(+)
include/linux/kvm_host.h +2 -0
index 48cd2d856132..88d4e4cbaba5 100644
@@ -549,6 +549,8 @@ static inline void kvm_irqfd_exit(void)
 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
 		  struct module *module);
 void kvm_exit(void);
+void kvm_enum(int (*enum_cb) (const struct kvm *kvm, void *param),
+	      void *param);
 
 void kvm_get_kvm(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
virt/kvm/kvm_main.c +12 -0
index f0fe9d02f6bb..cfd2d1bf8ac4 100644
@@ -4046,3 +4046,15 @@ void kvm_exit(void)
 	kvm_vfio_ops_exit();
 }
 EXPORT_SYMBOL_GPL(kvm_exit);
+
+void kvm_enum(int (*enum_cb) (const struct kvm *kvm, void *param), void *param)
+{
+	struct kvm *kvm;
+
+	spin_lock(&kvm_lock);
+	list_for_each_entry(kvm, &vm_list, vm_list) {
+		if (enum_cb(kvm, param))
+			break;
+	}
+	spin_unlock(&kvm_lock);
+}
Signature · 1 line
2.12.2
#5 lore raw

RFC PATCH 5/19 kvm: Add uuid member in struct kvm + support for KVM_CAP_VM_UUID

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

The introspection subsystem uses UUIDs to identify VMs.

This patch adds support for QEMU to query for KVM_CAP_VM_UUID and set the uuid with KVM_SET_VM_UUID.

The kvm_from_uuid() helper is used to search and 'get' a kvm struct by UUID, in order to link the VM and the guest introspection tool with a control socket connection.

---
 include/linux/kvm_host.h |  4 ++++
 include/uapi/linux/kvm.h |  2 ++
 virt/kvm/kvm_main.c      | 26 ++++++++++++++++++++++++++
 3 files changed, 32 insertions(+)
include/linux/kvm_host.h +4 -0
index 88d4e4cbaba5..545964ed6a63 100644
@@ -27,6 +27,7 @@
 #include <linux/irqbypass.h>
 #include <linux/swait.h>
 #include <linux/refcount.h>
+#include <linux/uuid.h>
 #include <asm/signal.h>
 
 #include <linux/kvm.h>
@@ -438,6 +439,8 @@ struct kvm {
 	struct kvm_stat_data **debugfs_stat_data;
 	struct srcu_struct srcu;
 	struct srcu_struct irq_srcu;
+
+	uuid_le uuid;
 };
 
 #define kvm_err(fmt, ...) \
@@ -551,6 +554,7 @@ int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
 void kvm_exit(void);
 void kvm_enum(int (*enum_cb) (const struct kvm *kvm, void *param),
 	      void *param);
+struct kvm *kvm_from_uuid(const uuid_le *uuid);
 
 void kvm_get_kvm(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
include/uapi/linux/kvm.h +2 -0
index 577429a95ad8..9b5813597d71 100644
@@ -895,6 +895,7 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_SPAPR_TCE_VFIO 142
 #define KVM_CAP_X86_GUEST_MWAIT 143
 #define KVM_CAP_ARM_USER_IRQ 144
+#define KVM_CAP_VM_UUID 145
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
@@ -1318,6 +1319,7 @@ struct kvm_s390_ucas_mapping {
 #define KVM_S390_GET_IRQ_STATE	  _IOW(KVMIO, 0xb6, struct kvm_s390_irq_state)
 /* Available with KVM_CAP_X86_SMM */
 #define KVM_SMI                   _IO(KVMIO,   0xb7)
+#define KVM_SET_VM_UUID           _IOW(KVMIO, 0xb8, uuid_le)
 
 #define KVM_DEV_ASSIGN_ENABLE_IOMMU	(1 << 0)
 #define KVM_DEV_ASSIGN_PCI_2_3		(1 << 1)
virt/kvm/kvm_main.c +26 -0
index cfd2d1bf8ac4..31bcdc92f1ea 100644
@@ -2924,6 +2924,7 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
 #endif
 	case KVM_CAP_IOEVENTFD_ANY_LENGTH:
 	case KVM_CAP_CHECK_EXTENSION_VM:
+	case KVM_CAP_VM_UUID:
 		return 1;
 #ifdef CONFIG_KVM_MMIO
 	case KVM_CAP_COALESCED_MMIO:
@@ -3106,6 +3107,13 @@ static long kvm_vm_ioctl(struct file *filp,
 	case KVM_CHECK_EXTENSION:
 		r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
 		break;
+	case KVM_SET_VM_UUID:
+		r = -EFAULT;
+		if (copy_from_user(&kvm->uuid, argp, sizeof(kvm->uuid)))
+			goto out;
+
+		r = 0;
+		break;
 	default:
 		r = kvm_arch_vm_ioctl(filp, ioctl, arg);
 	}
@@ -4058,3 +4066,21 @@ void kvm_enum(int (*enum_cb) (const struct kvm *kvm, void *param), void *param)
 	}
 	spin_unlock(&kvm_lock);
 }
+
+/* Make sure to call kvm_put_kvm() when done */
+struct kvm *kvm_from_uuid(const uuid_le *uuid)
+{
+	struct kvm *kvm;
+	struct kvm *found = NULL;
+
+	spin_lock(&kvm_lock);
+	list_for_each_entry(kvm, &vm_list, vm_list) {
+		if (!memcmp(&kvm->uuid, uuid, sizeof(kvm->uuid))) {
+			kvm_get_kvm(kvm);
+			found = kvm;
+			break;
+		}
+	}
+	spin_unlock(&kvm_lock);
+	return found;
+}
Signature · 1 line
2.12.2
#6 lore raw

RFC PATCH 6/19 kvm: Add kvm_vm_shutdown()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

This function is used by the introspection subsystem to shutdown a specific VM.

---
 include/linux/kvm_host.h |  1 +
 virt/kvm/kvm_main.c      | 27 +++++++++++++++++++++++++++
 2 files changed, 28 insertions(+)
include/linux/kvm_host.h +1 -0
index 545964ed6a63..2f00b5c64632 100644
@@ -555,6 +555,7 @@ void kvm_exit(void);
 void kvm_enum(int (*enum_cb) (const struct kvm *kvm, void *param),
 	      void *param);
 struct kvm *kvm_from_uuid(const uuid_le *uuid);
+void kvm_vm_shutdown(struct kvm *kvm);
 
 void kvm_get_kvm(struct kvm *kvm);
 void kvm_put_kvm(struct kvm *kvm);
virt/kvm/kvm_main.c +27 -0
index 31bcdc92f1ea..52d92fcf39ff 100644
@@ -4084,3 +4084,30 @@ struct kvm *kvm_from_uuid(const uuid_le *uuid)
 	spin_unlock(&kvm_lock);
 	return found;
 }
+
+static int kvm_vcpu_kill(int sig, struct kvm_vcpu *vcpu)
+{
+	int err = -ESRCH;
+	struct pid *pid;
+	struct siginfo siginfo[1] = { };
+
+	rcu_read_lock();
+	pid = rcu_dereference(vcpu->pid);
+	if (pid)
+		err = kill_pid_info(sig, siginfo, pid);
+	rcu_read_unlock();
+
+	return err;
+}
+
+void kvm_vm_shutdown(struct kvm *kvm)
+{
+	int i;
+	struct kvm_vcpu *vcpu;
+
+	mutex_lock(&kvm->lock);
+	kvm_for_each_vcpu(i, vcpu, kvm) {
+		kvm_vcpu_kill(SIGTERM, vcpu);
+	}
+	mutex_unlock(&kvm->lock);
+}
Signature · 1 line
2.12.2
#7 lore raw

RFC PATCH 7/19 kvm: x86: Add kvm_arch_msr_intercept()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

This function is used by the introspection subsytem to enable/disable MSR register interception.

The patch adds back the __vmx_enable_intercept_for_msr() function removed with 40d8338d095e6117112f4d303e5d6cf776069e38 (KVM: VMX: remove functions that enable msr intercepts).

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/svm.c              |  7 ++++++
 arch/x86/kvm/vmx.c              | 52 +++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.c              |  6 +++++
 4 files changed, 67 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 695605eb1dfb..ff94a3512347 100644
@@ -1048,6 +1048,7 @@ struct kvm_x86_ops {
 	void (*cancel_hv_timer)(struct kvm_vcpu *vcpu);
 
 	void (*setup_mce)(struct kvm_vcpu *vcpu);
+	void (*msr_intercept)(unsigned int msr, bool enable);
 };
 
 struct kvm_arch_async_pf {
@@ -1429,4 +1430,5 @@ static inline int kvm_cpu_get_apicid(int mps_cpu)
 #endif
 }
 
+void kvm_arch_msr_intercept(unsigned int msr, bool enable);
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/svm.c +7 -0
index ba9891ac5c56..7f1b00b74199 100644
@@ -5262,6 +5262,11 @@ static void svm_setup_mce(struct kvm_vcpu *vcpu)
 	vcpu->arch.mcg_cap &= 0x1ff;
 }
 
+static void svm_msr_intercept(unsigned int msr, bool enable)
+{
+	set_msr_interception(msrpm, msr, enable, enable);
+}
+
 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
 	.cpu_has_kvm_support = has_svm,
 	.disabled_by_bios = is_disabled,
@@ -5374,6 +5379,8 @@ static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
 	.deliver_posted_interrupt = svm_deliver_avic_intr,
 	.update_pi_irte = svm_update_pi_irte,
 	.setup_mce = svm_setup_mce,
+
+	.msr_intercept = svm_msr_intercept,
 };
 
 static int __init svm_init(void)
arch/x86/kvm/vmx.c +52 -0

64 lines not on this page · raw message

arch/x86/kvm/x86.c +6 -0
index 1a7493982310..9a47f640a7b5 100644
@@ -8734,6 +8734,12 @@ bool kvm_vector_hashing_enabled(void)
 }
 EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
 
+void kvm_arch_msr_intercept(unsigned int msr, bool enable)
+{
+	kvm_x86_ops->msr_intercept(msr, enable);
+}
+EXPORT_SYMBOL_GPL(kvm_arch_msr_intercept);
+
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
Signature · 1 line
2.12.2
#8 lore raw

RFC PATCH 8/19 kvm: Add the introspection subsystem

In reply to Adalbert Lazar

On kvmi_init(), an workqueue job is added to listen on a vsock port. The guest introspection tool connections are handled by the accept_socket_cb(). It should check that the other end is indeed the introspection tool. Based on the first 16 bytes (UUID) read from the socket, the connection is used as the main connection (if UUID=={0}) or as a VM connection, and an workqueue job is added to wait introspection commands.

With the exception of the first 16 bytes sent by the introspection tool, and another 16 bytes sent on the main connection (the UUID of the guest introspection tool), all the other messages between the introspection subsystem and the guest introspection tool have a common header:

	struct kvmi_socket_hdr {
		__u16 msg_id;
		__u16 size; /* msg. data following this hdr */
		__u32 seq;  /* maintained by the sending party */
	};

With the exception of KVMI_EVENT_GUEST_ON and KVMI_EVENT_GUEST_OFF, all the other messages must have a reply. The reply has the same sequence number and KVMI_FLAG_RESPONSE added to msg_id.

Because the introspection commands are received on a different thread, the VCPU threads have to be signaled with:
kvm_make_request(KVM_REQ_INTROSPECTION,vcpu)
call, which in turn will call kvmi_handle_controller_request() to handle the request: REQ_PAUSE, REQ_RESUME, REQ_CMD (introspection command, dispatched with the guest_responses[]), REQ_REPLY (reply from the guest introspection tool, signaled from handle_event_reply()), REQ_CLOSE (socket close, uninit).

The introspection needs VHOST_VSOCK, but only KVM_INTEL depends on it, for now. Probably, moving this subsystem in another module will be better.

---
 arch/x86/include/asm/kvm_host.h |    3 +
 arch/x86/kvm/Kconfig            |    2 +
 arch/x86/kvm/Makefile           |    1 +
 include/linux/kvm_host.h        |   28 +
 include/uapi/linux/kvmi.h       |  263 +++++
 virt/kvm/kvm_main.c             |   13 +
 virt/kvm/kvmi.c                 | 2252 +++++++++++++++++++++++++++++++++++++++
 virt/kvm/kvmi.h                 |   42 +
 virt/kvm/kvmi_socket.c          |  412 +++++++
 virt/kvm/kvmi_socket.h          |   33 +
 10 files changed, 3049 insertions(+)
 create mode 100644 include/uapi/linux/kvmi.h
 create mode 100644 virt/kvm/kvmi.c
 create mode 100644 virt/kvm/kvmi.h
 create mode 100644 virt/kvm/kvmi_socket.c
 create mode 100644 virt/kvm/kvmi_socket.h
arch/x86/include/asm/kvm_host.h +3 -0
index ff94a3512347..40d1ee68474a 100644
@@ -70,6 +70,7 @@
 #define KVM_REQ_HV_RESET          28
 #define KVM_REQ_HV_EXIT           29
 #define KVM_REQ_HV_STIMER         30
+#define KVM_REQ_INTROSPECTION     31
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -678,6 +679,8 @@ struct kvm_vcpu_arch {
 
 	/* GPA available (AMD only) */
 	bool gpa_available;
+
+	atomic_t next_interrupt_enabled;
 };
 
 struct kvm_lpage_info {
arch/x86/kvm/Kconfig +2 -0
index 760433b2574a..a84f9de2e4b0 100644
@@ -60,6 +60,8 @@ config KVM
 config KVM_INTEL
 	tristate "KVM for Intel processors support"
 	depends on KVM
+	# for kvmi
+	depends on VHOST_VSOCK
 	# for perf_guest_get_msrs():
 	depends on CPU_SUP_INTEL
 	---help---
arch/x86/kvm/Makefile +1 -0
index 09d4b17be022..aee76a0a74fb 100644
@@ -8,6 +8,7 @@ CFLAGS_vmx.o := -I.
 KVM := ../../../virt/kvm
 
 kvm-y			+= $(KVM)/kvm_main.o $(KVM)/coalesced_mmio.o \
+				$(KVM)/kvmi_socket.o $(KVM)/kvmi.o \
 				$(KVM)/eventfd.o $(KVM)/irqchip.o $(KVM)/vfio.o
 kvm-$(CONFIG_KVM_ASYNC_PF)	+= $(KVM)/async_pf.o
 
include/linux/kvm_host.h +28 -0
index 2f00b5c64632..aeda9e1d7a45 100644
@@ -28,6 +28,8 @@
 #include <linux/swait.h>
 #include <linux/refcount.h>
 #include <linux/uuid.h>
+#include <linux/mutex.h>
+#include <linux/radix-tree.h>
 #include <asm/signal.h>
 
 #include <linux/kvm.h>
@@ -268,6 +270,19 @@ struct kvm_vcpu {
 	bool preempted;
 	struct kvm_vcpu_arch arch;
 	struct dentry *debugfs_dentry;
+	size_t pause_count;
+	u8 ctx_data[256];
+	u32 ctx_size;
+	u32 ctx_pos;
+	struct semaphore sock_sem;
+	unsigned long sem_requests;
+	u8 sock_cmd_buf[960];
+	void *sock_cmd_ctx;
+	void *sock_rsp_buf;
+	size_t sock_rsp_size;
+	size_t sock_rsp_received;
+	u32 sock_rsp_seq;
+	bool sock_rsp_waiting;
 };
 
 static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
@@ -441,6 +456,19 @@ struct kvm {
 	struct srcu_struct irq_srcu;
 
 	uuid_le uuid;
+	atomic_t event_mask;
+	unsigned long cr_mask;
+	struct {
+		unsigned long low[BITS_TO_LONGS(8192)];
+		unsigned long hypervisor[BITS_TO_LONGS(8192)];
+		unsigned long high[BITS_TO_LONGS(8192)];
+	} msr_mask;
+	unsigned long introduced;
+	struct radix_tree_root access_tree;
+	struct mutex access_tree_lock;
+	struct list_head access_list;
+	void *socket_ctx;
+	rwlock_t socket_ctx_lock;
 };
 
 #define kvm_err(fmt, ...) \
include/uapi/linux/kvmi.h new file +263 -0

263 lines not on this page · raw message

virt/kvm/kvm_main.c +13 -0
index 52d92fcf39ff..c819b6b0a36e 100644
@@ -61,6 +61,7 @@
 #include "coalesced_mmio.h"
 #include "async_pf.h"
 #include "vfio.h"
+#include "kvmi.h"
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/kvm.h>
@@ -279,6 +280,8 @@ int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
 	kvm_vcpu_set_dy_eligible(vcpu, false);
 	vcpu->preempted = false;
 
+	sema_init(&vcpu->sock_sem, 0);
+
 	r = kvm_arch_vcpu_init(vcpu);
 	if (r < 0)
 		goto fail_free_run;
@@ -690,6 +693,11 @@ static struct kvm *kvm_create_vm(unsigned long type)
 
 	preempt_notifier_inc();
 
+	INIT_LIST_HEAD(&kvm->access_list);
+	mutex_init(&kvm->access_tree_lock);
+	rwlock_init(&kvm->socket_ctx_lock);
+	INIT_RADIX_TREE(&kvm->access_tree, GFP_KERNEL);
+
 	return kvm;
 
 out_err:
@@ -728,6 +736,7 @@ static void kvm_destroy_vm(struct kvm *kvm)
 	int i;
 	struct mm_struct *mm = kvm->mm;
 
+	mutex_destroy(&kvm->access_tree_lock);
 	kvm_destroy_vm_debugfs(kvm);
 	kvm_arch_sync_events(kvm);
 	spin_lock(&kvm_lock);
@@ -4011,6 +4020,9 @@ int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
 	r = kvm_vfio_ops_init();
 	WARN_ON(r);
 
+	r = kvmi_init();
+	WARN_ON(r);
+
 	return 0;
 
 out_undebugfs:
@@ -4039,6 +4051,7 @@ EXPORT_SYMBOL_GPL(kvm_init);
 
 void kvm_exit(void)
 {
+	kvmi_uninit();
 	debugfs_remove_recursive(kvm_debugfs_dir);
 	misc_deregister(&kvm_dev);
 	kmem_cache_destroy(kvm_vcpu_cache);
virt/kvm/kvmi.c new file +2252 -0

2,252 lines not on this page · raw message

virt/kvm/kvmi.h new file +42 -0

42 lines not on this page · raw message

virt/kvm/kvmi_socket.c new file +412 -0

318 lines not on this page · raw message

virt/kvm/kvmi_socket.h new file +33 -0
new file mode 100644
index 000000000000..0a89ada84804

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.12.2

Part of the diff is not shown here. View the raw message.

#12 lore raw

RFC PATCH 9/19 kvm: Hook in kvmi on VM on/off events

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Notify the guest introspection tool when a VM is created (KVMI_EVENT_GUEST_ON) or destroyed (KVMI_EVENT_GUEST_OFF).

---
 virt/kvm/kvm_main.c | 3 +++
 1 file changed, 3 insertions(+)
virt/kvm/kvm_main.c +3 -0
index c819b6b0a36e..179b688a8aef 100644
@@ -784,6 +784,7 @@ static int kvm_vm_release(struct inode *inode, struct file *filp)
 {
 	struct kvm *kvm = filp->private_data;
 
+	kvmi_vm_powered_off(kvm);
 	kvm_irqfd_release(kvm);
 
 	kvm_put_kvm(kvm);
@@ -2574,6 +2575,8 @@ static long kvm_vcpu_ioctl(struct file *filp,
 				synchronize_rcu();
 			put_pid(oldpid);
 		}
+		if (!test_and_set_bit(0, &vcpu->kvm->introduced))
+			kvmi_vm_powered_on(vcpu->kvm);
 		r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
 		trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
 		break;
Signature · 1 line
2.12.2
#13 lore raw

RFC PATCH 10/19 kvm: vmx: Hook in kvmi_page_fault()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Notify the guest introspection tool when a #PF occurs due to a failed permission check in the shadow page tables.

This call and the code involved in managing the shadow page tables permissions are the essence of a security solution using guest introspection facilities.

The shadow page tables are used to guarantee the purpose of code areas inside the guest (code, rodata, stack, heap etc.) Each attempt at an operation unfitting for a certain memory range (eg. execute code in heap) triggers a #PF and gives the introspection tool the chance to audit the code attempting the operation. The possible responses can be:

* allow it
* allow it via emulation
* allow it via emulation and with custom input (see the 'Change emulation context' patch)
* deny it by skipping the instruction

The #PF event is generated only for pages for which the guest introspection tool has shown interest (ie. has previously touched it by adjusting the permissions).

Page size is essential for performance (the smaller the better), that's why huge pages should be split. At the time of writing this patch, they are disabled with CONFIG_TRANSPARENT_HUGEPAGE=n.

---
 arch/x86/include/asm/kvm_host.h |  4 ++--
 arch/x86/kvm/mmu.c              | 51 +++++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx.c              | 24 ++++++++++++++++---
 3 files changed, 72 insertions(+), 7 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -2
index 40d1ee68474a..8d1d80bd2230 100644
@@ -1238,8 +1238,8 @@ void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu);
 
 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu);
 
-int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t gva, u64 error_code,
-		       void *insn, int insn_len);
+int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
+		       void *insn, int insn_len, unsigned long gva, bool pf);
 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva);
 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu);
 
arch/x86/kvm/mmu.c +49 -2

84 lines not on this page · raw message

arch/x86/kvm/vmx.c +21 -3
index 7a594cfcb2ea..f99fcc86f141 100644
@@ -5653,7 +5653,8 @@ static int handle_exception(struct kvm_vcpu *vcpu)
 
 		if (kvm_event_needs_reinjection(vcpu))
 			kvm_mmu_unprotect_page_virt(vcpu, cr2);
-		return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
+		return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0, 0,
+					  false);
 	}
 
 	ex_no = intr_info & INTR_INFO_VECTOR_MASK;
@@ -6204,6 +6205,8 @@ static int handle_task_switch(struct kvm_vcpu *vcpu)
 
 static int handle_ept_violation(struct kvm_vcpu *vcpu)
 {
+	bool pf = false;
+	unsigned long gla = 0;
 	unsigned long exit_qualification;
 	gpa_t gpa;
 	u32 error_code;
@@ -6234,6 +6237,21 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
 	gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
 	trace_kvm_page_fault(gpa, exit_qualification);
 
+	if ((exit_qualification & EPT_VIOLATION_GVA_TRANSLATED)) {
+		pf  = true;
+		gla = vmcs_readl(GUEST_LINEAR_ADDRESS);
+
+		/*
+		 * It can happen for kvm_read_cr3() to return 0 event though
+		 * the page fault took place as a result of a guest page table
+		 * translation
+		 *
+		 * TODO: Fix kvm_read_cr3(). The problem is in is_paging()
+		 */
+		vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
+		__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
+	}
+
 	/* Is it a read fault? */
 	error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
 		     ? PFERR_USER_MASK : 0;
@@ -6252,7 +6270,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
 	vcpu->arch.gpa_available = true;
 	vcpu->arch.exit_qualification = exit_qualification;
 
-	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
+	return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0, gla, pf);
 }
 
 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
@@ -6273,7 +6291,7 @@ static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
 					      EMULATE_DONE;
 
 	if (unlikely(ret == RET_MMIO_PF_INVALID))
-		return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
+		return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0, 0, false);
 
 	if (unlikely(ret == RET_MMIO_PF_RETRY))
 		return 1;
Signature · 1 line
2.12.2
#14 lore raw

RFC PATCH 11/19 kvm: x86: Hook in kvmi_breakpoint_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Inform the guest introspection tool than a breakpoint instruction (INT3) is being executed. These one-byte intructions are placed in the slack space of various functions and used as notification for when the OS or an application has reached a certain state or is trying to perform a certain operation (like creating a process).

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/svm.c              |  3 +++
 arch/x86/kvm/vmx.c              |  3 +++
 arch/x86/kvm/x86.c              | 14 ++++++++++++++
 4 files changed, 22 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 8d1d80bd2230..7024f8e3962b 100644
@@ -1434,4 +1434,6 @@ static inline int kvm_cpu_get_apicid(int mps_cpu)
 }
 
 void kvm_arch_msr_intercept(unsigned int msr, bool enable);
+int kvm_breakpoint(struct kvm_vcpu *vcpu);
+
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/svm.c +3 -0
index 7f1b00b74199..69d4d5c9e469 100644
@@ -2133,6 +2133,9 @@ static int bp_interception(struct vcpu_svm *svm)
 {
 	struct kvm_run *kvm_run = svm->vcpu.run;
 
+	if (kvm_breakpoint(svm->vcpu, svm->vmcb->control.exit_info_2))
+		return 1;
+
 	kvm_run->exit_reason = KVM_EXIT_DEBUG;
 	kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
 	kvm_run->debug.arch.exception = BP_VECTOR;
arch/x86/kvm/vmx.c +3 -0
index f99fcc86f141..405b739cd07b 100644
@@ -5682,6 +5682,9 @@ static int handle_exception(struct kvm_vcpu *vcpu)
 		kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
 		/* fall through */
 	case BP_VECTOR:
+		if (kvm_breakpoint(vcpu))
+			return 1;
+
 		/*
 		 * Update instruction length as we may reinject #BP from
 		 * user space while in guest debugging mode. Reading it for
arch/x86/kvm/x86.c +14 -0
index 9a47f640a7b5..3a50710629b5 100644
@@ -54,6 +54,7 @@
 #include <linux/kvm_irqfd.h>
 #include <linux/irqbypass.h>
 #include <linux/sched/stat.h>
+#include "../../../../virt/kvm/kvmi.h"
 
 #include <trace/events/kvm.h>
 
@@ -8740,6 +8741,19 @@ void kvm_arch_msr_intercept(unsigned int msr, bool enable)
 }
 EXPORT_SYMBOL_GPL(kvm_arch_msr_intercept);
 
+int kvm_breakpoint(struct kvm_vcpu *vcpu)
+{
+	gpa_t gpa;
+	struct kvm_segment cs;
+
+	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
+	gpa = kvm_mmu_gva_to_gpa_read(vcpu, cs.base + kvm_rip_read(vcpu), NULL);
+	if (kvmi_breakpoint_event(vcpu, gpa))
+		return 0;
+	return 1;
+}
+EXPORT_SYMBOL_GPL(kvm_breakpoint);
+
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
Signature · 1 line
2.12.2
#17 lore raw

RFC PATCH 12/19 kvm: x86: Hook in kvmi_trap_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Inform the guest introspection tool that a trap was successfully injected.

It can happen for the tool to queue a pagefault but have it overwritten by an interrupt picked up during guest reentry. kvmi_trap_event() is used to inform the tool of all pending traps giving it a chance to determine if it should try again later.

---
 arch/x86/kvm/x86.c | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
arch/x86/kvm/x86.c +24 -0
index 3a50710629b5..29d07f8aa7fa 100644
@@ -6928,6 +6928,30 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 		vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
 	}
 
+	if (atomic_read(&vcpu->arch.next_interrupt_enabled)) {
+		if (vcpu->arch.exception.pending) {
+			unsigned int nr = vcpu->arch.exception.nr;
+			unsigned int type;
+
+			if (kvm_exception_is_soft(nr))
+				type = INTR_TYPE_SOFT_EXCEPTION;
+			else
+				type = INTR_TYPE_HARD_EXCEPTION;
+			kvmi_trap_event(vcpu, nr, type,
+					vcpu->arch.exception.error_code,
+					vcpu->arch.cr2);
+		} else if (vcpu->arch.interrupt.pending) {
+			unsigned int nr = vcpu->arch.interrupt.nr;
+			unsigned int type;
+
+			if (vcpu->arch.interrupt.soft)
+				type = INTR_TYPE_SOFT_INTR;
+			else
+				type = INTR_TYPE_EXT_INTR;
+			kvmi_trap_event(vcpu, nr, type, 0, vcpu->arch.cr2);
+		}
+	}
+
 	kvm_x86_ops->run(vcpu);
 
 	/*
Signature · 1 line
2.12.2
#18 lore raw

RFC PATCH 13/19 kvm: x86: Hook in kvmi_cr_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Notify the guest introspection tool that cr{0,3,4} is going to be changed. The function kvmi_cr_event() will load in crX the new value if the tool permits it.

---
 arch/x86/kvm/x86.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
arch/x86/kvm/x86.c +12 -1
index 29d07f8aa7fa..5298f93412db 100644
@@ -648,6 +648,9 @@ int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
 	if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
 		return 1;
 
+	if (old_cr0 != cr0 && !kvmi_cr_event(vcpu, 0, old_cr0, &cr0))
+		return 1;
+
 	kvm_x86_ops->set_cr0(vcpu, cr0);
 
 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
@@ -785,6 +788,9 @@ int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 			return 1;
 	}
 
+	if (!kvmi_cr_event(vcpu, 4, old_cr4, &cr4))
+		return 1;
+
 	if (kvm_x86_ops->set_cr4(vcpu, cr4))
 		return 1;
 
@@ -801,11 +807,13 @@ EXPORT_SYMBOL_GPL(kvm_set_cr4);
 
 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
 {
+	unsigned long old_cr3 = kvm_read_cr3(vcpu);
+
 #ifdef CONFIG_X86_64
 	cr3 &= ~CR3_PCID_INVD;
 #endif
 
-	if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
+	if (cr3 == old_cr3 && !pdptrs_changed(vcpu)) {
 		kvm_mmu_sync_roots(vcpu);
 		kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
 		return 0;
@@ -818,6 +826,9 @@ int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
 		   !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
 		return 1;
 
+	if (!kvmi_cr_event(vcpu, 3, old_cr3, &cr3))
+		return 1;
+
 	vcpu->arch.cr3 = cr3;
 	__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
 	kvm_mmu_new_cr3(vcpu);
Signature · 1 line
2.12.2
#19 lore raw

RFC PATCH 14/19 kvm: x86: Hook in kvmi_xsetbv_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Notify the guest introspection tool that the extended control register has been changed.

---
 arch/x86/kvm/x86.c | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/x86.c +4 -0
index 5298f93412db..248fb7e99423 100644
@@ -728,6 +728,10 @@ static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
 			return 1;
 	}
+
+	if (xcr0 != old_xcr0)
+		kvmi_xsetbv_event(vcpu, xcr);
+
 	vcpu->arch.xcr0 = xcr0;
 
 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
Signature · 1 line
2.12.2
#20 lore raw

RFC PATCH 15/19 kvm: x86: Hook in kvmi_msr_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Inform the guest introspection tool that an MSR is going to be changed.

The kvmi_msr_event() function will check a bitmap of MSR-s of interest (configured via a KVMI_EVENT_CONTROL(KVMI_MSR_CONTROL) request) and, if the new value differs from the previous one, it will generate a notification. The introspection tool can respond by allowing the guest to continue with normal execution or by discarding the change.

This is meant to prevent malicious changes to MSR-s such as MSR_IA32_SYSENTER_EIP.

---
 arch/x86/kvm/x86.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
arch/x86/kvm/x86.c +17 -0
index 248fb7e99423..b7d2a9901665 100644
@@ -1090,6 +1090,23 @@ EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  */
 int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 {
+	if (!msr->host_initiated) {
+		struct msr_data __msr;
+
+		memset(&__msr, 0, sizeof(__msr));
+		__msr.host_initiated = true;
+		__msr.index = msr->index;
+
+		if (!kvm_get_msr(vcpu, &__msr)) {
+			u64 data = msr->data;
+
+			if (kvmi_msr_event(vcpu, msr->index, __msr.data, &data))
+				msr->data = data;
+			else
+				return 0;
+		}
+	}
+
 	switch (msr->index) {
 	case MSR_FS_BASE:
 	case MSR_GS_BASE:
Signature · 1 line
2.12.2
#21 lore raw

RFC PATCH 16/19 kvm: x86: Change the emulation context

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Certain instructions that generate a #PF due to the unset read bit in the corresponding spte, need to be emulated and passed a certain input (usually 8 bytes in length).

This is used to hide injected code by the introspecting tool from integrity checkers running inside the guest.

---
 arch/x86/kvm/x86.c | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
arch/x86/kvm/x86.c +15 -1
index b7d2a9901665..9465856a9e37 100644
@@ -4480,6 +4480,10 @@ static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
 				      struct x86_exception *exception)
 {
 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+
+	if (vcpu->ctx_size)
+		return kvmi_patch_emul_instr(vcpu, val, bytes);
+
 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
 }
 
@@ -4487,7 +4491,12 @@ static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
 		unsigned long addr, void *val, unsigned int bytes)
 {
 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
-	int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
+	int r;
+
+	if (vcpu->ctx_size)
+		return kvmi_patch_emul_instr(vcpu, val, bytes);
+
+	r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
 
 	return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
 }
@@ -4773,6 +4782,11 @@ static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
 				  unsigned int bytes,
 				  struct x86_exception *exception)
 {
+	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+
+	if (vcpu->ctx_size)
+		return kvmi_patch_emul_instr(vcpu, val, bytes);
+
 	return emulator_read_write(ctxt, addr, val, bytes,
 				   exception, &read_emultor);
 }
Signature · 1 line
2.12.2
#22 lore raw

RFC PATCH 17/19 kvm: x86: Hook in kvmi_vmcall_event()

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Code residing inside the introspected guest can call the introspection tool to report certain details about its operation. For example, a classic antimalware remediation tool can report what it has found during a scan.

The VMCALL convention is the one used on Xen (DOMCTL + subop). This code is largely untested. Its purpose is only to show how guest code communicates with the introspection tool.

---
 arch/x86/kvm/x86.c            | 15 +++++++++++++++
 include/uapi/linux/kvm_para.h |  4 ++++
 2 files changed, 19 insertions(+)
arch/x86/kvm/x86.c +15 -0
index 9465856a9e37..cafe878ba148 100644
@@ -6302,6 +6302,21 @@ int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
 		break;
 #endif
+	case KVM_HC_XEN_HVM_OP:{
+		unsigned long subop;
+
+		if (op_64_bit) {
+			subop = kvm_register_read(vcpu, VCPU_REGS_RDI);
+			subop &= 0xFFFFFFFF;
+		} else
+			subop = a0;
+
+		if (subop == KVM_HC_XEN_HVM_OP_GUEST_REQUEST_VM_EVENT)
+			kvmi_vmcall_event(vcpu);
+
+		ret = kvm_register_read(vcpu, VCPU_REGS_RAX);
+		break;
+	}
 	default:
 		ret = -KVM_ENOSYS;
 		break;
include/uapi/linux/kvm_para.h +4 -0
index fed506aeff62..297b75435831 100644
@@ -25,6 +25,10 @@
 #define KVM_HC_MIPS_EXIT_VM		7
 #define KVM_HC_MIPS_CONSOLE_OUTPUT	8
 #define KVM_HC_CLOCK_PAIRING		9
+#define KVM_HC_XEN_HVM_OP		34
+/* Matches Xen's __HYPERVISOR_hvm_op */
+
+#define KVM_HC_XEN_HVM_OP_GUEST_REQUEST_VM_EVENT 24
 
 /*
  * hypercalls use architecture specific
Signature · 1 line
2.12.2
#23 lore raw

RFC PATCH 18/19 kvm: x86: Set the new spte flags before entering the guest

In reply to Adalbert Lazar

From: Mihai Dontu <[email protected]>

Apply the changes made to the shadow page tables by the guest introspection tool. These changes involve only the page permissions bits.

---
 arch/x86/kvm/x86.c | 2 ++
 1 file changed, 2 insertions(+)
arch/x86/kvm/x86.c +2 -0
index cafe878ba148..30f4d301453c 100644
@@ -6793,6 +6793,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 	bool req_immediate_exit = false;
 
+	kvmi_flush_mem_access(vcpu);
+
 	if (vcpu->requests) {
 		if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
 			kvm_mmu_unload(vcpu);
Signature · 1 line
2.12.2
#24 lore raw

RFC PATCH 19/19 kvm: x86: Handle KVM_REQ_INTROSPECTION

In reply to Adalbert Lazar

This VCPU request is needed to handle introspection requests: pause, unpause, command, reply, close.

---
 arch/x86/kvm/x86.c | 3 +++
 1 file changed, 3 insertions(+)
arch/x86/kvm/x86.c +3 -0
index 30f4d301453c..32a757939474 100644
@@ -6880,6 +6880,9 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 		 */
 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
 			kvm_hv_process_stimers(vcpu);
+
+		if (kvm_check_request(KVM_REQ_INTROSPECTION, vcpu))
+			kvmi_handle_controller_request(vcpu);
 	}
 
 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
Signature · 1 line
2.12.2
#25 lore raw
In reply to Adalbert Lazar
Quoted 5 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

Quoted 9 lines

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

Also, this looks like as if it can easily work against the userspace part of the hypervisor - bad idea.

API/ABI documentation is missing.

Did you check if the concept is portable to other architectures? Another reason to try hard to reuse existing interfaces.

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RDA ITP SES-DE
Corporate Competence Center Embedded Linux
#26 lore raw

Hi Jan,

Quoted 6 lines · Jan Kiszka
Quoted 5 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

Quoted 8 lines
Quoted 8 lines

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Thank you very much for taking a look over this series!

Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

If instead you are suggesting we integrate the kernel-side API into the debug framework, I see no problem with that right now. We'll need a bit more time to look into what that entails.

Quoted 2 lines

Also, this looks like as if it can easily work against the userspace part of the hypervisor - bad idea.

The way it is implemented right now, it works behind its back (qemu specifically), in that it intercepts and handles certain events before it. It should be possible to put some code in qemu and move part of the logic in it, but we're trying hard to avoid context switches as guest exits themselves are currently quite expensive. The experience comes from working with Xen. We have no benchmark numbers for KVM.

Quoted 1 line

API/ABI documentation is missing.

Understood. We will try to put something together in the coming weeks.

Quoted 2 lines

Did you check if the concept is portable to other architectures? Another reason to try hard to reuse existing interfaces.

The API that we propose is the result of work done for x86 and ARM, though for the latter we're still working on a PoC. It's fairly generic.

Quoted 1 line

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Good catch! We'll make the adjustment.

Thank-you!

Signature · 1 line
Mihai Donțu
#27 lore raw
Quoted 20 lines · Mihai Donțu

Hi Jan,

Quoted 6 lines · Jan Kiszka
Quoted 5 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

Quoted 8 lines
Quoted 8 lines

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Thank you very much for taking a look over this series!

Quoted 7 lines
Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

Communication alone does not require isolation. Interpretation of what can be sees may benefit from that, though.

Quoted 4 lines

If instead you are suggesting we integrate the kernel-side API into the debug framework, I see no problem with that right now. We'll need a bit more time to look into what that entails.

The hypervisor process could terminate your link, providing that other VM the introspection access. Or you even have a gdb-speaking process running on the host, just reusing the existing gdbstub of QEMU. Just wild ideas, I didn't look into details, and you may further elaborate on your requirements.

Quoted 10 lines
Quoted 3 lines

Also, this looks like as if it can easily work against the userspace part of the hypervisor - bad idea.

The way it is implemented right now, it works behind its back (qemu specifically), in that it intercepts and handles certain events before it. It should be possible to put some code in qemu and move part of the logic in it, but we're trying hard to avoid context switches as guest exits themselves are currently quite expensive. The experience comes from working with Xen. We have no benchmark numbers for KVM.

Even if you don't run the hot-paths through QEMU, you should inform it about what is going on. Starting/stopping behind its back it bad, so is fiddling with guest stats. Keep in mind that your introspection VM is, well, just another VM that could be scheduled, suspended or even migrated away, and then you leave the original VM rather clueless behind.

Migration is actually an interesting topic of its own...

Quoted 12 lines
Quoted 2 lines

API/ABI documentation is missing.

Understood. We will try to put something together in the coming weeks.

Quoted 2 lines

Did you check if the concept is portable to other architectures? Another reason to try hard to reuse existing interfaces.

The API that we propose is the result of work done for x86 and ARM, though for the latter we're still working on a PoC. It's fairly generic.

Quoted 6 lines
Quoted 1 line

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Good catch! We'll make the adjustment.

Thank-you!

BTW, I remember that there was/is some larger research community interested in such kind of interfaces as well, or they even have their own out-of-tree tooling. Hope they will speak up and review your proposals as well so that the result is of general use.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RDA ITP SES-DE
Corporate Competence Center Embedded Linux
#28 lore raw
Quoted 50 lines · Jan Kiszka
Quoted 18 lines · Mihai Donțu
Quoted 6 lines · Jan Kiszka
Quoted 5 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

Quoted 8 lines
Quoted 8 lines

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Thank you very much for taking a look over this series!

Quoted 7 lines
Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

Communication alone does not require isolation. Interpretation of what can be sees may benefit from that, though.

Quoted 3 lines

If instead you are suggesting we integrate the kernel-side API into the debug framework, I see no problem with that right now. We'll need a bit more time to look into what that entails.

The hypervisor process could terminate your link, providing that other VM the introspection access. Or you even have a gdb-speaking process running on the host, just reusing the existing gdbstub of QEMU. Just wild ideas, I didn't look into details, and you may further elaborate on your requirements.

Quoted 9 lines
Quoted 2 lines

Also, this looks like as if it can easily work against the userspace part of the hypervisor - bad idea.

The way it is implemented right now, it works behind its back (qemu specifically), in that it intercepts and handles certain events before it. It should be possible to put some code in qemu and move part of the logic in it, but we're trying hard to avoid context switches as guest exits themselves are currently quite expensive. The experience comes from working with Xen. We have no benchmark numbers for KVM.

Quoted 7 lines

Even if you don't run the hot-paths through QEMU, you should inform it about what is going on. Starting/stopping behind its back it bad, so is fiddling with guest stats. Keep in mind that your introspection VM is, well, just another VM that could be scheduled, suspended or even migrated away, and then you leave the original VM rather clueless behind.

Migration is actually an interesting topic of its own...

On this topic specifically, a complete security solution using guest introspection interfaces will need to tap into the management application and be notified when a migration is taking place. The reason being, and I'm talking from our perspective only, that the introspected guest is patched and those patches „talk” with the security solution. A guest that reaches the destination in this state will remain in limbo and (so far) can only be recovered through a reboot.

Quoted 22 lines
Quoted 11 lines
Quoted 1 line

API/ABI documentation is missing.

Understood. We will try to put something together in the coming weeks.

Quoted 2 lines

Did you check if the concept is portable to other architectures? Another reason to try hard to reuse existing interfaces.

The API that we propose is the result of work done for x86 and ARM, though for the latter we're still working on a PoC. It's fairly generic.

Quoted 6 lines
Quoted 1 line

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Good catch! We'll make the adjustment.

Thank-you!

BTW, I remember that there was/is some larger research community interested in such kind of interfaces as well, or they even have their own out-of-tree tooling. Hope they will speak up and review your proposals as well so that the result is of general use.

Signature · 1 line
Mihai Donțu
maintainer
#36 lore raw
In reply to Mihai Donțu
Quoted 2 lines · Mihai Donțu
Quoted 1 line

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Good catch! We'll make the adjustment.

LGPL is GPL-compatible. If there's anything LGPL to share this code with, I have no issue with that.

Paolo

#37 lore raw
Quoted 8 lines · Paolo Bonzini
Quoted 2 lines · Mihai Donțu
Quoted 1 line

Last but not least: LGPL slipped into your kernel parts - the kernel is GPL.

Good catch! We'll make the adjustment.

LGPL is GPL-compatible. If there's anything LGPL to share this code with, I have no issue with that.

It can falsely suggests that linking against this removes certain obligations of the GPL that the rest is licensed under. For core code, it's therefore not a good choice.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RDA ITP SES-DE
Corporate Competence Center Embedded Linux
#29 lore raw
In reply to Jan Kiszka
Quoted 37 lines · Jan Kiszka
Quoted 20 lines · Mihai Donțu

Hi Jan,

Quoted 6 lines · Jan Kiszka
Quoted 5 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

Quoted 8 lines
Quoted 8 lines

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Thank you very much for taking a look over this series!

Quoted 7 lines
Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

Communication alone does not require isolation. Interpretation of what can be sees may benefit from that, though.

Quoted 4 lines

If instead you are suggesting we integrate the kernel-side API into the debug framework, I see no problem with that right now. We'll need a bit more time to look into what that entails.

Quoted 5 lines

The hypervisor process could terminate your link, providing that other VM the introspection access. Or you even have a gdb-speaking process running on the host, just reusing the existing gdbstub of QEMU. Just wild ideas, I didn't look into details, and you may further elaborate on your requirements.

QEMU userspace can provide the interface on an AF_VSOCK listen socket. Here is a rough idea:

  qemu --chardev socket,id=chardev0,type=vsock,port=1234,server,nowait \
       --guest-introspection chardev=chardev0,allowed-cids=10

Since it uses a chardev this means the guest introspection API is also available via UNIX domain sockets to local applications, etc.

In this example only CID 10 has access to the guest introspection API. Connections from other VMs will be dropped.

Stefan

#30 lore raw
Quoted 32 lines · Stefan Hajnoczi
Quoted 25 lines · Jan Kiszka
Quoted 16 lines · Mihai Donțu
Quoted 14 lines · Jan Kiszka
Quoted 13 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Quoted 7 lines
Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

Quoted 5 lines

The hypervisor process could terminate your link, providing that other VM the introspection access. Or you even have a gdb-speaking process running on the host, just reusing the existing gdbstub of QEMU. Just wild ideas, I didn't look into details, and you may further elaborate on your requirements.

Quoted 8 lines

QEMU userspace can provide the interface on an AF_VSOCK listen socket. Here is a rough idea:

  qemu --chardev socket,id=chardev0,type=vsock,port=1234,server,nowait \
       --guest-introspection chardev=chardev0,allowed-cids=10

Since it uses a chardev this means the guest introspection API is also available via UNIX domain sockets to local applications, etc.

Exposing the introspections commands and events as IOCTLs can be done easily.

However, dropping the vsock access from the kernel, or having the IOCTL <-> vsock adapter only in userspace will change more things. With the proposed API, the guest introspection looks like:

------------------ -----------------------------

|                  |<-- /dev/kvm -->| qemu        VM1             |
|                  |                |-------                      |
|                  |                | Linux |                     |
| KVM              |                 -----------------------------
|                  |<-- /dev/kvm -->| qemu        VM2             |
|                  |                |---------                    |
|                  |                | Windows |                   |
|                  |                 -----------------------------
|                  |<-- /dev/kvm -->| qemu        VM3             |
|    --------------|                |---------------------------  |
|   | kvmi <- vhost-vsock -----------> guest introspection tool | |
 ------------------                  -----------------------------

The introspection tool connects directly to the introspection subsystem (kvmi).

Moving the vsock to userland will change this:

                                     -----------------------------
                 /----- /dev/kvm -->| new_tool (guest on/off/list)|<-- vsock -->\
                 |                   -----------------------------              |
                 |                                                              |
 ----------------v-                  -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM1             |<-- vsock -->|
|                  |                |-------                      |             |
|                  |                | Linux |                     |             |
| KVM              |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM2             |<-- vsock -->|
|                  |                |---------                    |             |
|                  |                | Windows |                   |             |
|                  |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM3      /----->|<-- vsock -->/
|           -------|                |---------------------v----   |
|          | kvmi  |                | guest introspection tool |  |
 ------------------                  -----------------------------

There will be a need for a new tool (and/or libvirt modified) to get the guest events (on/off/list) and change the VM1, VM2 invocations (to make them connect with the introspection tool). This might also be a problem with products having the host locked down (eg. RHEV).

Moving more code to QEMU will make the introspection harder with other hw emulators (from kvmtool to Google's implementation) because they will need more than just:
- migration notification: the introspection tool needs to unhook from the introspected guests [minor change]
- KVM_SET_VM_UUID support [minor change]
- vsock [medium change], but only if this particular emulator is used to start the guest introspection tool

Also, the path between kvmi and the introspection tool (when running isolated in a guest) will be bigger, adding some overhead, which is a big problem with live introspectors. EXTERIOR VMI paper shows[1] between 5-20 times slower execution for small programs (ps, uptime). So, a smaller path will help in keeping the overhead lower.

My colleague will follow up with some stats collected during an introspection session. Hopefully they will shed more light on the performance required from the tool-KVM communication channel.

[1]: https://www.utdallas.edu/~zhiqiang.lin/file/VEE13-Slides.pdf

#31 lore raw
Quoted 84 lines · On 2017-06-20 16:58, [email protected] wrote:
Quoted 32 lines · Stefan Hajnoczi
Quoted 25 lines · Jan Kiszka
Quoted 16 lines · Mihai Donțu
Quoted 14 lines · Jan Kiszka
Quoted 13 lines · Adalbert Lazar

This patch series proposes an interface that will allow a guest introspection tool to monitor and control other guests, in order to protect them against different forms of exploits. This type of interface is already present in the XEN hypervisor.

With the current implementation, the introspection tool connects to the KVMi (the introspection subsystem from KVM) using a vsock socket, establishes a main communication channel, used for a few messages (KVMI_EVENT_GUEST_ON, KVMI_EVENT_GUEST_OFF, KVMI_GET_GUESTS and KVMI_GET_VERSION).

Every KVMI_EVENT_GUEST_ON notification, makes the introspection tool establish a new connection, used to monitor and control that guest.

Quoted 7 lines
Quoted 2 lines

What prevented building this on top of the already existing guest debug interfaces of KVM, maybe extending it where needed? Could be win-win.

I might be mistaking, but this would require the application using the introspection capabilities to run on the host. If so, what we are trying to do is to isolate the application into its own VM. This is why we use vSock to communicate with the host.

Quoted 5 lines

The hypervisor process could terminate your link, providing that other VM the introspection access. Or you even have a gdb-speaking process running on the host, just reusing the existing gdbstub of QEMU. Just wild ideas, I didn't look into details, and you may further elaborate on your requirements.

Quoted 8 lines

QEMU userspace can provide the interface on an AF_VSOCK listen socket. Here is a rough idea:

  qemu --chardev socket,id=chardev0,type=vsock,port=1234,server,nowait \
       --guest-introspection chardev=chardev0,allowed-cids=10

Since it uses a chardev this means the guest introspection API is also available via UNIX domain sockets to local applications, etc.

Exposing the introspections commands and events as IOCTLs can be done easily.

However, dropping the vsock access from the kernel, or having the IOCTL <-> vsock adapter only in userspace will change more things. With the proposed API, the guest introspection looks like:

------------------ -----------------------------

|                  |<-- /dev/kvm -->| qemu        VM1             |
|                  |                |-------                      |
|                  |                | Linux |                     |
| KVM              |                 -----------------------------
|                  |<-- /dev/kvm -->| qemu        VM2             |
|                  |                |---------                    |
|                  |                | Windows |                   |
|                  |                 -----------------------------
|                  |<-- /dev/kvm -->| qemu        VM3             |
|    --------------|                |---------------------------  |
|   | kvmi <- vhost-vsock -----------> guest introspection tool | |
 ------------------                  -----------------------------

The introspection tool connects directly to the introspection subsystem (kvmi).

Moving the vsock to userland will change this:

                                     -----------------------------
                 /----- /dev/kvm -->| new_tool (guest on/off/list)|<-- vsock -->\
                 |                   -----------------------------              |
                 |                                                              |
 ----------------v-                  -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM1             |<-- vsock -->|
|                  |                |-------                      |             |
|                  |                | Linux |                     |             |
| KVM              |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM2             |<-- vsock -->|
|                  |                |---------                    |             |
|                  |                | Windows |                   |             |
|                  |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM3      /----->|<-- vsock -->/
|           -------|                |---------------------v----   |
|          | kvmi  |                | guest introspection tool |  |
 ------------------                  -----------------------------
Quoted 7 lines

There will be a need for a new tool (and/or libvirt modified) to get the guest events (on/off/list) and change the VM1, VM2 invocations (to make them connect with the introspection tool). This might also be a problem with products having the host locked down (eg. RHEV).

Moving more code to QEMU will make the introspection harder with other hw emulators (from kvmtool to Google's implementation) because they will

I would bet that (not only) Google folks will look rather skeptical at any proposal to widen the existing kvm user interface anyway, because of security implications. Reducing that should be a primary design goal IMHO.

Jan

Quoted 19 lines

need more than just:
- migration notification: the introspection tool needs to unhook from the introspected guests [minor change]
- KVM_SET_VM_UUID support [minor change]
- vsock [medium change], but only if this particular emulator is used to start the guest introspection tool

Also, the path between kvmi and the introspection tool (when running isolated in a guest) will be bigger, adding some overhead, which is a big problem with live introspectors. EXTERIOR VMI paper shows[1] between 5-20 times slower execution for small programs (ps, uptime). So, a smaller path will help in keeping the overhead lower.

My colleague will follow up with some stats collected during an introspection session. Hopefully they will shed more light on the performance required from the tool-KVM communication channel.

[1]: https://www.utdallas.edu/~zhiqiang.lin/file/VEE13-Slides.pdf

Signature · 2 lines
Siemens AG, Corporate Technology, CT RDA ITP SES-DE
Corporate Competence Center Embedded Linux
#32 lore raw
In reply to [email protected]
Quoted 25 lines · On Tue, Jun 20, 2017 at 05:58:41PM +0300, [email protected] wrote:
Quoted 4 lines · Stefan Hajnoczi
Quoted 3 lines · Jan Kiszka
Quoted 2 lines · Mihai Donțu
Quoted 1 line · Jan Kiszka

On 2017-06-16 15:43, Adalbert Lazar wrote:

Moving the vsock to userland will change this:

                                     -----------------------------
                 /----- /dev/kvm -->| new_tool (guest on/off/list)|<-- vsock -->\
                 |                   -----------------------------              |
                 |                                                              |
 ----------------v-                  -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM1             |<-- vsock -->|
|                  |                |-------                      |             |
|                  |                | Linux |                     |             |
| KVM              |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM2             |<-- vsock -->|
|                  |                |---------                    |             |
|                  |                | Windows |                   |             |
|                  |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM3      /----->|<-- vsock -->/
|           -------|                |---------------------v----   |
|          | kvmi  |                | guest introspection tool |  |
 ------------------                  -----------------------------
Quoted 4 lines

There will be a need for a new tool (and/or libvirt modified) to get the guest events (on/off/list) and change the VM1, VM2 invocations (to make them connect with the introspection tool). This might also be a problem with products having the host locked down (eg. RHEV).

I think that is desirable in fact. kvmi should be an explicit feature that is controlled by the management tools. This way the policy can be decided by the administrator. Libvirt changes will be necessary.

Some KVM users do not want kvmi. Think of the new memory encryption hardware support that is coming out - the point is to prevent the hypervisor from looking inside the VMs! What you are doing is the opposite of that.

Also, anyone who doesn't actually use kvmi would be better of disabling the feature to minimize the attack surface.

I'm not sure if kvmi should be inside the QEMU process though. If a guest is compromised and escapes into QEMU, then kvmi is defeated. It may be a better design for kvmi to be an isolated component.

Stefan

maintainer
#15 lore raw

Re: [RFC PATCH 11/19] kvm: x86: Hook in kvmi_breakpoint_event()

In reply to Adalbert Lazar

arch/x86/kvm/x86.c void kvm_arch_msr_intercept(unsigned int msr, bool enable) · line 8756

Quoted 13 lines · Adalbert Lazar
arch/x86/kvm/x86.c +13 -0
+int kvm_breakpoint(struct kvm_vcpu *vcpu)
+{
+	gpa_t gpa;
+	struct kvm_segment cs;
+
+	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
+	gpa = kvm_mmu_gva_to_gpa_read(vcpu, cs.base + kvm_rip_read(vcpu), NULL);
+	if (kvmi_breakpoint_event(vcpu, gpa))
+		return 0;
+	return 1;
+}
+EXPORT_SYMBOL_GPL(kvm_breakpoint);
+

Please create a separate file with all these functions. x86.c/vmx.c/svm.c are already too big, let's not make it worse.

Paolo

maintainer
#9 lore raw

Re: [RFC PATCH 08/19] kvm: Add the introspection subsystem

In reply to Adalbert Lazar

virt/kvm/kvmi.c line 377

Quoted 10 lines · Adalbert Lazar
virt/kvm/kvmi.c new file +10 -0
+	while (!list_empty(&kvm->access_list)) {
+		struct kvmi_mem_access *m =
+		    list_first_entry(&kvm->access_list, struct kvmi_mem_access,
+				     link);
+
+		list_del(&m->link);
+		INIT_LIST_HEAD(&m->link);
+
+		kvmi_apply_mem_access(vcpu, m->gfn, m->access);
+	}

How does this work when multiple VCPUs are running with different MMU roles? One VCPU is emptying the access_list for all, but kvm_mmu_set_spte is using for_each_shadow_entry per-VCPU.

I'm really afraid of introducing subtle bugs, with possible security effects. I'm not really able to provide a suggestion yet, since I haven't grasped the protocol entirely.

Paolo

#10 lore raw

Re: [RFC PATCH 08/19] kvm: Add the introspection subsystem

Hi Paolo,

Quoted 12 lines · Paolo Bonzini

virt/kvm/kvmi.c line 377

Quoted 11 lines · Adalbert Lazar
virt/kvm/kvmi.c new file +3 -0
+	while (!list_empty(&kvm->access_list)) {
+		struct kvmi_mem_access *m =
+		    list_first_entry(&kvm->access_list, struct

kvmi_mem_access,

virt/kvm/kvmi.c new file +7 -0
+				     link);
+
+		list_del(&m->link);
+		INIT_LIST_HEAD(&m->link);
+
+		kvmi_apply_mem_access(vcpu, m->gfn, m->access);
+	}

Thank you taking a look over this!

The entire mechanism for altering spte-s will need a separate discussion, because right now it interferes with other mmu features like dirty page logging and possibly other that I might not be aware of.

The present code merely illustrates what we're really trying to
achieve: control the page permissions in the shadow page tables. The mechanics are quite simple: while a VCPU is paused the introspection tool creates a list of all spte's it wants to alter and then it unpauses the VCPU which, on its wait back into the guest, walks the list and applies the changes. This list-based approach is used because sometimes accessing spte-s requires access to qemu's address space which is tricky to do when the introspection tool runs as a separate process. We tried using something on top of switch_mm() but it proved unreliable. It also requires exporting some very deep x86-specific data in order to build kvm-intel.ko.

Quoted 3 lines

How does this work when multiple VCPUs are running with different MMU roles?  One VCPU is emptying the access_list for all, but kvm_mmu_set_spte is using for_each_shadow_entry per-VCPU.

Indeed, here we assume all VCPU-s' spt pointers are loaded with the same address. A correct approach would iterate over all vCPU-s and I suspect it would need to be a bit more complex with Intel's multiple EPT views.

Quoted 3 lines

I'm really afraid of introducing subtle bugs, with possible security effects.  I'm not really able to provide a suggestion yet, since I haven't grasped the protocol entirely.

Signature · 1 line
Mihai Donțu
#16 lore raw

Re: [RFC PATCH 11/19] kvm: x86: Hook in kvmi_breakpoint_event()

In reply to Paolo Bonzini
Quoted 10 lines · Paolo Bonzini
Quoted 9 lines · Adalbert Lazar
arch/x86/kvm/x86.c +7 -0
+int kvm_breakpoint(struct kvm_vcpu *vcpu)
+{
+	gpa_t gpa;
+	struct kvm_segment cs;
+
+	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
+	gpa = kvm_mmu_gva_to_gpa_read(vcpu, cs.base +

kvm_rip_read(vcpu), NULL);

arch/x86/kvm/x86.c +1 -0
+	if (kvmi_breakpoint_event(vcpu, gpa))
Quoted 8 lines

arch/x86/kvm/x86.c void kvm_arch_msr_intercept(unsigned int msr, bool enable) · line 8756

Quoted 5 lines
arch/x86/kvm/x86.c +5 -0
+		return 0;
+	return 1;
+}
+EXPORT_SYMBOL_GPL(kvm_breakpoint);
+

Please create a separate file with all these functions. x86.c/vmx.c/svm.c are already too big, let's not make it worse.

Noted. Thank you!

Signature · 1 line
Mihai Donțu
maintainer
#11 lore raw

Re: [RFC PATCH 08/19] kvm: Add the introspection subsystem

In reply to Mihai Donțu
Quoted 4 lines · Mihai Donțu

The entire mechanism for altering spte-s will need a separate discussion, because right now it interferes with other mmu features like dirty page logging and possibly other that I might not be aware of.

Okay, this is the stuff that should be put in the cover letter. The current cover letter instead is an attempt at documentation that should, of course, be in Documentation/ instead. :)

I think the right way to do it is to rebuild the MMU when the radix tree is modified, with KVM_REQ_MMU_SYNC (or maybe even kvm_mmu_reset_context is enough, I am not sure). kvm_mmu_get_page can modify role.access according to the result of the radix tree lookup. When you make the page read-only, the role (which is part of the hash key) changes and the EPT tables will also be made read-only.

Paolo

Quoted 20 lines

The present code merely illustrates what we're really trying to
achieve: control the page permissions in the shadow page tables. The mechanics are quite simple: while a VCPU is paused the introspection tool creates a list of all spte's it wants to alter and then it unpauses the VCPU which, on its wait back into the guest, walks the list and applies the changes. This list-based approach is used because sometimes accessing spte-s requires access to qemu's address space which is tricky to do when the introspection tool runs as a separate process. We tried using something on top of switch_mm() but it proved unreliable. It also requires exporting some very deep x86-specific data in order to build kvm-intel.ko.

Quoted 3 lines

How does this work when multiple VCPUs are running with different MMU roles? One VCPU is emptying the access_list for all, but kvm_mmu_set_spte is using for_each_shadow_entry per-VCPU.

Indeed, here we assume all VCPU-s' spt pointers are loaded with the same address. A correct approach would iterate over all vCPU-s and I suspect it would need to be a bit more complex with Intel's multiple EPT views.

maintainer
#33 lore raw
In reply to Stefan Hajnoczi
Quoted 20 lines · On 21/06/2017 13:04, Stefan Hajnoczi wrote:> On Tue, Jun 20, 2017 at…
Quoted 20 lines

Moving the vsock to userland will change this:

                                     -----------------------------
                 /----- /dev/kvm -->| new_tool (guest on/off/list)|<-- vsock -->\
                 |                   -----------------------------              |
                 |                                                              |
 ----------------v-                  -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM1             |<-- vsock -->|
|                  |                |-------                      |             |
|                  |                | Linux |                     |             |
| KVM              |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM2             |<-- vsock -->|
|                  |                |---------                    |             |
|                  |                | Windows |                   |             |
|                  |                 -----------------------------              |
|                  |<-- /dev/kvm -->| qemu        VM3      /----->|<-- vsock -->/
|           -------|                |---------------------v----   |
|          | kvmi  |                | guest introspection tool |  |
 ------------------                  -----------------------------
Quoted 3 lines
Quoted 3 lines

There will be a need for a new tool (and/or libvirt modified) to get the guest events (on/off/list) and change the VM1, VM2 invocations (to make them connect with the introspection tool

This kind of event should be provided directly by QEMU to the guest introspection tool---see below.

Quoted 10 lines
Quoted 2 lines

This might also be a
problem with products having the host locked down (eg. RHEV).

I think that is desirable in fact. kvmi should be an explicit feature that is controlled by the management tools. This way the policy can be decided by the administrator. Libvirt changes will be necessary.

Some KVM users do not want kvmi. Think of the new memory encryption hardware support that is coming out - the point is to prevent the hypervisor from looking inside the VMs! What you are doing is the opposite of that.

I think Stefan has made quite a point here. The policy manager for kvmi should definitely be on the host, not on the introspector machine. There can be multiple introspectors, some on the host and some on an appliance, though I suppose a limit of one introspector per VM is acceptable.

And this should be the starting point of the design.

Compared to Stefan's proposed command line:

  qemu --chardev socket,id=chardev0,type=vsock,port=1234,server,nowait \
       --guest-introspection chardev=chardev0,allowed-cids=10

I would do it in the opposite direction. The introspector is the one that presents a server socket; QEMU connects to the introspection VM, possibly does some handshaking, and passes the file descriptor to KVM. With another small change, replacing --guest-introspection with the generic --object, that gives the following:

  qemu --chardev socket,id=chardev0,type=vsock,cid=10,port=1234,nowait \
       --object introspection chardev=chardev0,allow=all,id=kvmi \
       --accel kvm,introspection=kvmi

The policy is specified via kvmi-{allow,deny} parameters and passed to KVM via ioctls together with the socket file descriptor.

This lets you reuse common POSIX concepts and simplify the kernel code. KVMI_EVENT_GUEST_ON is just POLLIN on the server socket (plus handshaking on the client socket); KVMI_EVENT_GUEST_OFF is POLLHUP on the client socket. There's no need for KVM to know a UUID, as the introspection application can just have your usual poll() event loop or thread, and look up the VM from the file descriptor.

QEMU supports socket reconnection, so you don't need KVMI_GET_GUESTS either. If KVM cannot write to the socket, it should exit to userspace with a new KVM_EXIT_KVMI vmexit (which can have multiple subcodes, one of them being KVM_EXIT_KVMI_SOCKET_ERROR).

Of course the link need not even be VSOCK-based. It can be a Unix socket as Stefan has already mentioned, which is always nice when debugging or writing unit tests. I assume you'll want later some VMFUNC-based access to the guest's memory; local introspection tools could use an alternative way via file descriptor passing, similar to what is used already by vhost-user. And dually, a hypothetical vhost-user server living in a VM could use VMFUNC to access guest memory without being able to do all the kind of ugly traps that your current usecase does. This is another reason why policy has to be in userspace.

Also, as a matter of fact: this series does not include either documentation or unit tests. That's seriously bad.

Patch 1 should explain the socket protocol in English and only affect Documentation/ and possibly arch/x86/include/uapi. There's no way that I can review 2000 lines of code without even knowing what it is supposed to be like. In fact, for the next RFC, perhaps you should only submit patch 1. :)

Paolo

#34 lore raw
Quoted 21 lines · Paolo Bonzini
Quoted 20 lines · Stefan Hajnoczi
Quoted 19 lines · On Tue, Jun 20, 2017 at 05:58:41PM +0300, [email protected] wrote:

Moving the vsock to userland will change this:

                                     -----------------------------
                 /----- /dev/kvm -->| new_tool (guest on/off/list)|<-- vsock -->\

                 |                   -----------------------------              |
                 |                                                              |
 ----------------v-                  -----------------------------              |
>                  |<-- /dev/kvm -->| qemu        VM1             |<-- vsock -->|
>                  |                |-------                      |             |
>                  |                | Linux |                     |             |
> KVM              |                 -----------------------------              |
>                  |<-- /dev/kvm -->| qemu        VM2             |<-- vsock -->|
>                  |                |---------                    |             |
>                  |                | Windows |                   |             |
>                  |                 -----------------------------              |
>                  |<-- /dev/kvm -->| qemu        VM3      /----->|<-- vsock -->/
>           -------|                |---------------------v----   |
>          | kvmi  |                | guest introspection tool |  |
Quoted 20 lines
Quoted 5 lines
Quoted 5 lines

 ------------------                  -----------------------------

There will be a need for a new tool (and/or libvirt modified) to get the guest events (on/off/list) and change the VM1, VM2 invocations (to make them connect with the introspection tool

This kind of event should be provided directly by QEMU to the guest introspection tool---see below.

Quoted 11 lines
Quoted 2 lines

This might also be a
problem with products having the host locked down (eg. RHEV).

I think that is desirable in fact.  kvmi should be an explicit feature that is controlled by the management tools.  This way the policy can be decided by the administrator.  Libvirt changes will be necessary.

Some KVM users do not want kvmi.  Think of the new memory encryption hardware support that is coming out - the point is to prevent the hypervisor from looking inside the VMs!  What you are doing is the opposite of that.

Apologies for the late reply.

Quoted 5 lines

I think Stefan has made quite a point here.  The policy manager for kvmi should definitely be on the host, not on the introspector machine. There can be multiple introspectors, some on the host and some on an appliance, though I suppose a limit of one introspector per VM is acceptable.

The host should, indeed, control whether the introspection feature should be made available. I can see this being a checkbox in, say, virt-manager.

Assuming the feature is enabled, the only policy we are interested in is whether our application should indeed try and introspect a guest, and this is connected to libvirt. For example, our management solution will query libvirt about running VM-s and then, depending on configuration made by an administrator, will tell our application which VM-s to actually introspect. This is where the UUID comes into play:
the management solution refers to VM-s by their UUID and in turn the application must be able to convert those to an actual handle (a file descriptor or something else).

The flow you described below seems to make room for this: during the initial handshake, qemu could tell our application the UUID of the guest and we'd keep a map of sorts. No need to put that in kernel.

Quoted 13 lines

And this should be the starting point of the design.

Compared to Stefan's proposed command line:

  qemu --chardev socket,id=chardev0,type=vsock,port=1234,server,nowait \
       --guest-introspection chardev=chardev0,allowed-cids=10

I would do it in the opposite direction.  The introspector is the one that presents a server socket; QEMU connects to the introspection VM, possibly does some handshaking, and passes the file descriptor to KVM.  With another small change, replacing --guest-introspection with the generic --object, that gives the following:

Quoted 6 lines

  qemu --chardev socket,id=chardev0,type=vsock,cid=10,port=1234,nowait \
       --object introspection chardev=chardev0,allow=all,id=kvmi \
       --accel kvm,introspection=kvmi

The policy is specified via kvmi-{allow,deny} parameters and passed to KVM via ioctls together with the socket file descriptor.

I understand from this that the policy controls whether a certain VM can be introspected. I'd imagine that it will be default "false" and set to "true" respectively whenever an "introspection" object is specified.

Quoted 11 lines

This lets you reuse common POSIX concepts and simplify the kernel code. KVMI_EVENT_GUEST_ON is just POLLIN on the server socket (plus handshaking on the client socket); KVMI_EVENT_GUEST_OFF is POLLHUP on the client socket. There's no need for KVM to know a UUID, as the introspection application can just have your usual poll() event loop or thread, and look up the VM from the file descriptor.

QEMU supports socket reconnection, so you don't need KVMI_GET_GUESTS either. If KVM cannot write to the socket, it should exit to userspace with a new KVM_EXIT_KVMI vmexit (which can have multiple subcodes, one of them being KVM_EXIT_KVMI_SOCKET_ERROR).

If I understand all of the above correctly, qemu will initiate the connection to the introspection tool and after a handshake pass the file descritor to KVM thus making further communication take place only between the tool and the host kernel (no need to pass through the host user space).

Quoted 10 lines

Of course the link need not even be VSOCK-based.  It can be a Unix socket as Stefan has already mentioned, which is always nice when debugging or writing unit tests.  I assume you'll want later some VMFUNC-based access to the guest's memory; local introspection tools could use an alternative way via file descriptor passing, similar to what is used already by vhost-user. And dually, a hypothetical vhost-user server living in a VM could use VMFUNC to access guest memory without being able to do all the kind of ugly traps that your current usecase does.  This is another reason why policy has to be in userspace.

Quoted 8 lines

Also, as a matter of fact: this series does not include either documentation or unit tests.  That's seriously bad.

Patch 1 should explain the socket protocol in English and only affect Documentation/ and possibly arch/x86/include/uapi.  There's no way that I can review 2000 lines of code without even knowing what it is supposed to be like.  In fact, for the next RFC, perhaps you should only submit patch 1. :)

Noted! Thank you,

Signature · 1 line
Mihai Donțu
maintainer
#35 lore raw
Quoted 14 lines · Mihai Donțu

The host should, indeed, control whether the introspection feature should be made available. I can see this being a checkbox in, say, virt-manager.

Assuming the feature is enabled, the only policy we are interested in is whether our application should indeed try and introspect a guest, and this is connected to libvirt. For example, our management solution will query libvirt about running VM-s and then, depending on configuration made by an administrator, will tell our application which VM-s to actually introspect. This is where the UUID comes into play:
the management solution refers to VM-s by their UUID and in turn the application must be able to convert those to an actual handle (a file descriptor or something else).

Quoted 3 lines

The flow you described below seems to make room for this: during the initial handshake, qemu could tell our application the UUID of the guest and we'd keep a map of sorts. No need to put that in kernel.

Exactly. QEMU already knows the UUID.

Quoted 5 lines
Quoted 5 lines
  qemu --chardev socket,id=chardev0,type=vsock,cid=10,port=1234,nowait \
       --object introspection chardev=chardev0,allow=all,id=kvmi \
       --accel kvm,introspection=kvmi
Quoted 7 lines
Quoted 2 lines

The policy is specified via kvmi-{allow,deny} parameters and passed to KVM via ioctls together with the socket file descriptor.

I understand from this that the policy controls whether a certain VM can be introspected. I'd imagine that it will be default "false" and set to "true" respectively whenever an "introspection" object is specified.

It also controls what operations can be intercepted for introspection purposes. For example a VM may be okay with allowing memory access, but would not be okay with allowing the introspector to trap instructions or page faults. (Or vice versa, since memory access to an untrusted introspector effectively breaks security).

Quoted 10 lines
Quoted 4 lines

QEMU supports socket reconnection, so you don't need KVMI_GET_GUESTS either. If KVM cannot write to the socket, it should exit to userspace with a new KVM_EXIT_KVMI vmexit (which can have multiple subcodes, one of them being KVM_EXIT_KVMI_SOCKET_ERROR).

If I understand all of the above correctly, qemu will initiate the connection to the introspection tool and after a handshake pass the file descritor to KVM thus making further communication take place only between the tool and the host kernel (no need to pass through the host user space).

Right, though host user space is invoked at least for the error case, in order to reconnect to the introspector. This is useful in case the introspector is restarted after an update or crash.

I'm not sure if other cases will need userspace cooperation. We'll see!

Paolo