Introduce VIRTIO_CRYPTO_MAX_AKCIPHER_KEY_LEN. We set this hard
limit to 1MB, which mirrors the linux kernel's internal payload
restriction for the 'add_key' syscall.

Signed-off-by: helei <[email protected]>
---
 hw/virtio/virtio-crypto.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/hw/virtio/virtio-crypto.c b/hw/virtio/virtio-crypto.c
index 6fceb39681..06be93a0ac 100644
--- a/hw/virtio/virtio-crypto.c
+++ b/hw/virtio/virtio-crypto.c
@@ -25,6 +25,13 @@
 #include "system/cryptodev-vhost.h"
 
 #define VIRTIO_CRYPTO_VM_VERSION 1
+/*
+ * The virtio-crypto spec does not limit akcipher key lengths. To prevent
+ * guest-introduced OOM attacks via excessive host memory allocation, we
+ * enforce a 1MB limit. This aligns with the linux kernel's internal max
+ * payload limit for the add_key syscall.
+ */
+#define VIRTIO_CRYPTO_MAX_AKCIPHER_KEY_LEN ((1024 * 1024) - 1)
 
 typedef struct VirtIOCryptoSessionReq {
     VirtIODevice *vdev;
@@ -216,6 +223,12 @@ virtio_crypto_create_asym_session(VirtIOCrypto *vcrypto,
         return -VIRTIO_CRYPTO_NOTSUPP;
     }
 
+    if (keylen > VIRTIO_CRYPTO_MAX_AKCIPHER_KEY_LEN) {
+        error_report("virtio-crypto length of akcipher key is too large: %u",
+                     keylen);
+        return -VIRTIO_CRYPTO_ERR;
+    }
+
     if (keylen) {
         asym_info->key = g_malloc(keylen);
         if (iov_to_buf(iov, out_num, 0, asym_info->key, keylen) != keylen) {
-- 
2.43.0


Reply via email to